<?php
ob_start();
//ob_start();
//ini_set('display_errors', 'Off');
//error_reporting(0);
//define('MP_DB_DEBUG', false); 
ini_set('display_errors', 'Off');
//ini_set('display_errors', 'On');
//ini_set('error_reporting', E_ALL);
//ini_set('display_errors', 1);


defined('BASEPATH') OR exit('No direct script access allowed');


class Systemusers extends CI_Controller
{
	
	
	
    function __construct() {
		
	
        parent::__construct();
	ini_set('max_execution_time', 0);
//ini_set('memory_limit','5048M');
		$this->load->library('email');
        	$this->load->model('provincemodel','',TRUE);
			 $this->load->model('usermodel','',TRUE);
$this->load->model('adminusermodel','',TRUE);
		$this->load->dbutil();
		$this->load->model('districtmodel','',TRUE);
		$this->load->model('countymodel','',TRUE);
		//$this->load->library('encrypt');
			$this->load->library('encryption');

		$this->load->library('zend');
		$this->load->model('nationmodel','',TRUE);
		$this->load->model('countymodel','',TRUE);
 		$this->load->model('accomodationmodel','',TRUE);

 
 
  $this->load->model('systemusermodel','',TRUE);
   $this->load->model('studentprofilemodel','',TRUE);
   
   	  $this->load->helper('AfricasTalkingGateway');
	     include 'phpqrcode/qrlib.php';
	
	//add_filter('show_admin_bar', '__return_false');
	//$this->db2 = $this->load->database('smsdb', TRUE);
	
if( !isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], "order/place") === -1 ) {
    $this->load->helper('url');
    redirect('/page404');
}	
	
	$custom_key = 'KENGA';

        $encryption_config = [
            'cipher' => 'aes-256',
            'mode'   => 'cbc',
            'key'    => hash('sha256', $custom_key), 
        ];

        
        $this->encryption->initialize($encryption_config);

	
	
	
	
        if(($this->session->userdata('logged_in')=="")) {
            $this->session->set_flashdata('flash_data', 'You don\'t have access!');
            redirect('login');
        }
		
		global $mybranchid;
		global $mycompanyid;
		global $myoriginal;
			global $myusertype;
		global $myemail;
		global $mysurname;
		global $myfirstname;
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	  	  $data['original'] = $session_data['original'];
		  
		  
		     	$data['usertype'] = $session_data['usertype'];
	  $data['email'] = $session_data['email'];
	  	  $data['firstname'] = $session_data['firstname'];
  $data['surname'] = $session_data['surname'];

 $myusertype = $data['usertype'];
	 $myemail = $data['email'];
 $myfirstname = $data['firstname'];
	 $mysurname = $data['surname'];
	 $mybranchid = $data['branchid'];
	 $mycompanyid = $data['companyid'];
	 	 $myoriginal = $data['original'];
		
		
		
		  if(($myoriginal!="usercontroller")) {
            $this->session->set_flashdata('flash_data', 'You don\'t have access!');
            redirect('login');
        }

/*
if(!isset($_SERVER['HTTP_REFERER'])) {
	  show_error('You do NOT have access to this module or You can NOT access the page directly through url. Go back  ', 500);
redirect('login');	
//echo" You dont have access to this module";	
return false;
 
}
*/
    }
	
	
		public function barcode2222($code)
	{
		//I'm just using rand() function for data example
		//$temp = rand(10000, 99999);
		$this->set_barcode($code);

	}
	
	

	
			public function barcode($code)
	{


// For demonstration purposes, get pararameters that are passed in through $_GET or set to the default value
$filepath = (isset($_GET["filepath"])?$_GET["filepath"]:"");
$text = $code;
$size = (isset($_GET["size"])?$_GET["size"]:"80");
$orientation = (isset($_GET["orientation"])?$_GET["orientation"]:"horizontal");
$code_type = (isset($_GET["codetype"])?$_GET["codetype"]:"code128");
$print = (isset($_GET["print"])&&$_GET["print"]=='true'?false: true);
$sizefactor = (isset($_GET["sizefactor"])?$_GET["sizefactor"]:"1");

// This function call can be copied into your project and can be made from anywhere in your code
$this->getbarcode( $filepath, $text, $size, $orientation, $code_type, $print, $sizefactor );
	}
	
	
public function getbarcode( $filepath="", $text="0", $size="80", $orientation="horizontal", $code_type="code128", $print=false, $SizeFactor=1 ) {
	$code_string = "";
	// Translate the $text into barcode the correct $code_type
	if ( in_array(strtolower($code_type), array("code128", "code128b")) ) {
		$chksum = 104;
		// Must not change order of array elements as the checksum depends on the array's key to validate final code
		$code_array = array(" "=>"212222","!"=>"222122","\""=>"222221","#"=>"121223","$"=>"121322","%"=>"131222","&"=>"122213","'"=>"122312","("=>"132212",")"=>"221213","*"=>"221312","+"=>"231212",","=>"112232","-"=>"122132","."=>"122231","/"=>"113222","0"=>"123122","1"=>"123221","2"=>"223211","3"=>"221132","4"=>"221231","5"=>"213212","6"=>"223112","7"=>"312131","8"=>"311222","9"=>"321122",":"=>"321221",";"=>"312212","<"=>"322112","="=>"322211",">"=>"212123","?"=>"212321","@"=>"232121","A"=>"111323","B"=>"131123","C"=>"131321","D"=>"112313","E"=>"132113","F"=>"132311","G"=>"211313","H"=>"231113","I"=>"231311","J"=>"112133","K"=>"112331","L"=>"132131","M"=>"113123","N"=>"113321","O"=>"133121","P"=>"313121","Q"=>"211331","R"=>"231131","S"=>"213113","T"=>"213311","U"=>"213131","V"=>"311123","W"=>"311321","X"=>"331121","Y"=>"312113","Z"=>"312311","["=>"332111","\\"=>"314111","]"=>"221411","^"=>"431111","_"=>"111224","\`"=>"111422","a"=>"121124","b"=>"121421","c"=>"141122","d"=>"141221","e"=>"112214","f"=>"112412","g"=>"122114","h"=>"122411","i"=>"142112","j"=>"142211","k"=>"241211","l"=>"221114","m"=>"413111","n"=>"241112","o"=>"134111","p"=>"111242","q"=>"121142","r"=>"121241","s"=>"114212","t"=>"124112","u"=>"124211","v"=>"411212","w"=>"421112","x"=>"421211","y"=>"212141","z"=>"214121","{"=>"412121","|"=>"111143","}"=>"111341","~"=>"131141","DEL"=>"114113","FNC 3"=>"114311","FNC 2"=>"411113","SHIFT"=>"411311","CODE C"=>"113141","FNC 4"=>"114131","CODE A"=>"311141","FNC 1"=>"411131","Start A"=>"211412","Start B"=>"211214","Start C"=>"211232","Stop"=>"2331112");
		$code_keys = array_keys($code_array);
		$code_values = array_flip($code_keys);
		for ( $X = 1; $X <= strlen($text); $X++ ) {
			$activeKey = substr( $text, ($X-1), 1);
			$code_string .= $code_array[$activeKey];
			$chksum=($chksum + ($code_values[$activeKey] * $X));
		}
		$code_string .= $code_array[$code_keys[($chksum - (intval($chksum / 103) * 103))]];

		$code_string = "211214" . $code_string . "2331112";
	} elseif ( strtolower($code_type) == "code128a" ) {
		$chksum = 103;
		$text = strtoupper($text); // Code 128A doesn't support lower case
		// Must not change order of array elements as the checksum depends on the array's key to validate final code
		$code_array = array(" "=>"212222","!"=>"222122","\""=>"222221","#"=>"121223","$"=>"121322","%"=>"131222","&"=>"122213","'"=>"122312","("=>"132212",")"=>"221213","*"=>"221312","+"=>"231212",","=>"112232","-"=>"122132","."=>"122231","/"=>"113222","0"=>"123122","1"=>"123221","2"=>"223211","3"=>"221132","4"=>"221231","5"=>"213212","6"=>"223112","7"=>"312131","8"=>"311222","9"=>"321122",":"=>"321221",";"=>"312212","<"=>"322112","="=>"322211",">"=>"212123","?"=>"212321","@"=>"232121","A"=>"111323","B"=>"131123","C"=>"131321","D"=>"112313","E"=>"132113","F"=>"132311","G"=>"211313","H"=>"231113","I"=>"231311","J"=>"112133","K"=>"112331","L"=>"132131","M"=>"113123","N"=>"113321","O"=>"133121","P"=>"313121","Q"=>"211331","R"=>"231131","S"=>"213113","T"=>"213311","U"=>"213131","V"=>"311123","W"=>"311321","X"=>"331121","Y"=>"312113","Z"=>"312311","["=>"332111","\\"=>"314111","]"=>"221411","^"=>"431111","_"=>"111224","NUL"=>"111422","SOH"=>"121124","STX"=>"121421","ETX"=>"141122","EOT"=>"141221","ENQ"=>"112214","ACK"=>"112412","BEL"=>"122114","BS"=>"122411","HT"=>"142112","LF"=>"142211","VT"=>"241211","FF"=>"221114","CR"=>"413111","SO"=>"241112","SI"=>"134111","DLE"=>"111242","DC1"=>"121142","DC2"=>"121241","DC3"=>"114212","DC4"=>"124112","NAK"=>"124211","SYN"=>"411212","ETB"=>"421112","CAN"=>"421211","EM"=>"212141","SUB"=>"214121","ESC"=>"412121","FS"=>"111143","GS"=>"111341","RS"=>"131141","US"=>"114113","FNC 3"=>"114311","FNC 2"=>"411113","SHIFT"=>"411311","CODE C"=>"113141","CODE B"=>"114131","FNC 4"=>"311141","FNC 1"=>"411131","Start A"=>"211412","Start B"=>"211214","Start C"=>"211232","Stop"=>"2331112");
		$code_keys = array_keys($code_array);
		$code_values = array_flip($code_keys);
		for ( $X = 1; $X <= strlen($text); $X++ ) {
			$activeKey = substr( $text, ($X-1), 1);
			$code_string .= $code_array[$activeKey];
			$chksum=($chksum + ($code_values[$activeKey] * $X));
		}
		$code_string .= $code_array[$code_keys[($chksum - (intval($chksum / 103) * 103))]];

		$code_string = "211412" . $code_string . "2331112";
	} elseif ( strtolower($code_type) == "code39" ) {
		$code_array = array("0"=>"111221211","1"=>"211211112","2"=>"112211112","3"=>"212211111","4"=>"111221112","5"=>"211221111","6"=>"112221111","7"=>"111211212","8"=>"211211211","9"=>"112211211","A"=>"211112112","B"=>"112112112","C"=>"212112111","D"=>"111122112","E"=>"211122111","F"=>"112122111","G"=>"111112212","H"=>"211112211","I"=>"112112211","J"=>"111122211","K"=>"211111122","L"=>"112111122","M"=>"212111121","N"=>"111121122","O"=>"211121121","P"=>"112121121","Q"=>"111111222","R"=>"211111221","S"=>"112111221","T"=>"111121221","U"=>"221111112","V"=>"122111112","W"=>"222111111","X"=>"121121112","Y"=>"221121111","Z"=>"122121111","-"=>"121111212","."=>"221111211"," "=>"122111211","$"=>"121212111","/"=>"121211121","+"=>"121112121","%"=>"111212121","*"=>"121121211");

		// Convert to uppercase
		$upper_text = strtoupper($text);

		for ( $X = 1; $X<=strlen($upper_text); $X++ ) {
			$code_string .= $code_array[substr( $upper_text, ($X-1), 1)] . "1";
		}

		$code_string = "1211212111" . $code_string . "121121211";
	} elseif ( strtolower($code_type) == "code25" ) {
		$code_array1 = array("1","2","3","4","5","6","7","8","9","0");
		$code_array2 = array("3-1-1-1-3","1-3-1-1-3","3-3-1-1-1","1-1-3-1-3","3-1-3-1-1","1-3-3-1-1","1-1-1-3-3","3-1-1-3-1","1-3-1-3-1","1-1-3-3-1");

		for ( $X = 1; $X <= strlen($text); $X++ ) {
			for ( $Y = 0; $Y < count($code_array1); $Y++ ) {
				if ( substr($text, ($X-1), 1) == $code_array1[$Y] )
					$temp[$X] = $code_array2[$Y];
			}
		}

		for ( $X=1; $X<=strlen($text); $X+=2 ) {
			if ( isset($temp[$X]) && isset($temp[($X + 1)]) ) {
				$temp1 = explode( "-", $temp[$X] );
				$temp2 = explode( "-", $temp[($X + 1)] );
				for ( $Y = 0; $Y < count($temp1); $Y++ )
					$code_string .= $temp1[$Y] . $temp2[$Y];
			}
		}

		$code_string = "1111" . $code_string . "311";
	} elseif ( strtolower($code_type) == "codabar" ) {
		$code_array1 = array("1","2","3","4","5","6","7","8","9","0","-","$",":","/",".","+","A","B","C","D");
		$code_array2 = array("1111221","1112112","2211111","1121121","2111121","1211112","1211211","1221111","2112111","1111122","1112211","1122111","2111212","2121112","2121211","1121212","1122121","1212112","1112122","1112221");

		// Convert to uppercase
		$upper_text = strtoupper($text);

		for ( $X = 1; $X<=strlen($upper_text); $X++ ) {
			for ( $Y = 0; $Y<count($code_array1); $Y++ ) {
				if ( substr($upper_text, ($X-1), 1) == $code_array1[$Y] )
					$code_string .= $code_array2[$Y] . "1";
			}
		}
		$code_string = "11221211" . $code_string . "1122121";
	}

	// Pad the edges of the barcode
	$code_length = 20;
	if ($print) {
		$text_height = 30;
	} else {
		$text_height = 0;
	}
	
	for ( $i=1; $i <= strlen($code_string); $i++ ){
		$code_length = $code_length + (integer)(substr($code_string,($i-1),1));
        }

	if ( strtolower($orientation) == "horizontal" ) {
		$img_width = $code_length*$SizeFactor;
		$img_height = $size;
	} else {
		$img_width = $size;
		$img_height = $code_length*$SizeFactor;
	}

	$image = imagecreate($img_width, $img_height + $text_height);
	$black = imagecolorallocate ($image, 0, 0, 0);
	$white = imagecolorallocate ($image, 255, 255, 255);

	imagefill( $image, 0, 0, $white );
	if ( $print ) {
		imagestring($image, 5, 31, $img_height, $text, $black );
	}

	$location = 10;
	for ( $position = 1 ; $position <= strlen($code_string); $position++ ) {
		$cur_size = $location + ( substr($code_string, ($position-1), 1) );
		if ( strtolower($orientation) == "horizontal" )
			imagefilledrectangle( $image, $location*$SizeFactor, 0, $cur_size*$SizeFactor, $img_height, ($position % 2 == 0 ? $white : $black) );
		else
			imagefilledrectangle( $image, 0, $location*$SizeFactor, $img_width, $cur_size*$SizeFactor, ($position % 2 == 0 ? $white : $black) );
		$location = $cur_size;
	}
	
	// Draw barcode to the screen or save in a file
	if ( $filepath=="" ) {
		header ('Content-type: image/png');
		imagepng($image);
		imagedestroy($image);
	} else {
		imagepng($image,$filepath);
		imagedestroy($image);		
	}
}



		
	
	
	
	
	
	
	
	private function set_barcode($code)
	{
		  header('Content-type: image/png');
		//load library
		$this->load->library('zend');
		//load in folder Zend
		$this->zend->load('Zend/Barcode');
		//generate barcode
		
	
		  Zend_Barcode::render('code128', 'image', array('text'=>$code), array());
		  
		ob_end_clean();
	}
	
	
		public function myagent()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

				$this->load->view('userdata/myagent',$data);
		$this->load->view("template/footerpage");
	}
	



	
	  public function viewmydocuments() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
      $image_id = $_GET['image_id'];
	 
	 if($image_id==""){
		 
	
$myimg_id = $userid.rand(100, 9900000).time();	 
$documentDATA=array(		
						'image_id'=>$myimg_id,

								);
								 $this->usermodel->updatedata($documentDATA,'people','id',$itemid);







   	$data['image_id'] = $myimg_id;

	        		$data['viewdocuments'] = $this->usermodel->populateall('documents','mydocuments', $myimg_id);



	
	 }else{
		    	$data['image_id'] = $image_id;
			        		$data['viewdocuments'] = $this->usermodel->populateall('documents','mydocuments', $image_id);

	 }
	


   	$data['itemid'] = $itemid;
	   	$data['links'] = "";
	   	$data['total_rows'] =count((array)$data['viewdocuments']);

	$data['member'] = $this->usermodel->populatemember($itemid);
$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		$data['viewcategory'] = $this->usermodel->populatecategory($companyid);
    

		
		 $this->load->view('userdata/viewmydocuments',$data);
		$this->load->view("template/footerpage");
		
	}
  }
  
	
	
	
		
	
			public function viewbackup()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbackup']= $this->usermodel->populateall('backup','companyid',$companyid);

	

				$this->load->view('userdata/viewbackup',$data);
		$this->load->view("template/footerpage");
	}
	
		public function deliveryhome()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");







				$this->load->view('userdata/deliveryhome');
		$this->load->view("template/footerpage");
	}
	
				public function taskhome()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbackup']= $this->usermodel->populateall('backup','companyid',$companyid);

	

				$this->load->view('userdata/taskhome',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	function backup()
	{
		set_time_limit(0);
		$this->load->dbutil();
		$prefs = array(
			'format'      => 'txt',             // gzip, zip, txt
			'add_drop'    => FALSE,              // Whether to add DROP TABLE statements to backup file
			'add_insert'  => TRUE,              // Whether to add INSERT data to backup file
			'newline'     => "\n"               // Newline character used in backup file
    	);
		$backup =&$this->dbutil->backup($prefs);
		$backup = 'SET FOREIGN_KEY_CHECKS = 0;'."\n".$backup."\n".'SET FOREIGN_KEY_CHECKS = 1;';
		force_download('robipos.sql', $backup);
		
		
	}
	
	
	
	
	function backup2()
	{
		set_time_limit(0);
	    $this->load->dbutil();
    $db_format=array('format'=>'zip','add_insert'=>TRUE,'add_drop'=>FALSE,'filename'=>'robipos.sql','newline'=>"\n");
    $backup=$this->dbutil->backup($db_format);
			//$backup = 'SET FOREIGN_KEY_CHECKS = 0;'."\n".$backup."\n".'SET FOREIGN_KEY_CHECKS = 1;';

    $dbname='backup-on-'.date('Y-m-d').'.zip';
    $save='downloads/'.$dbname;
    write_file($save,$backup);

   //force_download($dbname,$backup);
		
	}
	

		
		
		
		
		
		
		
		
		public function uploadoldserialnumbers()
        {

        if(isset($_POST["btn_uploadoldserials"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $status = "new";
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();
				
				
				 		 

					$description="";
	  				  		     $invoice = "";
$buyingprice="";
$sellingprice="";
$name="";


	

				  
				  						  $createdate = date('Y-m-d H:i:s');


                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				      $code =  $emapData['B'];
							     $branch =  $emapData['C'];
				  if($code!=""){
	
	
		if( $branch=="Main"){
											 $myproducts = $this->usermodel->populateallarray('products','code', $code);

				}else{
										 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);
	
				}
				
		if($emapData['D']!=""){
$buyingprice= $emapData['D'];

		}else{
$buyingprice=$myproducts[0]['buyingprice'];

		}			
				
				
		if($emapData['E']!=""){
$sellingprice= $emapData['E'];


		}else{
$sellingprice= $myproducts[0]['sellingprice'];


		}	
			$description=$myproducts[0]['description'];

			$name=$myproducts[0]['name'];
	
			 
				  
				  if($myproducts!=false){
				  
						 $myserialcode = $emapData['A'];
			
				if($myserialcode!=""){
				
				
					
					
					
			
						  
						  
						  	    $data[] = array(
                              
                               'serial' => $emapData['A'],
                          
										'qty' => 1,
									'itemid' =>"",
									'buyingprice' => $buyingprice,
									'sellingprice' => $sellingprice,
									
									'createdate' => $createdate,
									'name' => $name,
 									'description' => $description,
								'status' => $status,
									'invoice' => $invoice,
 									'code' => $code,
 										'userid' => $userid,
											'batchno' => 1,
										'branch' => $branch,
 									'companyid' => $companyid,
 									
                                );
						  
						  

	
								
								
				
		   $i++;
				}
				}
	
							  
	}else{
	
		$description="";
			$name="";
	
}



	
       }              	               
              
			  $usr_result =$this->db->insert_batch('serials', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded serial numbers  !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Serials were not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function uploadserialnumbers()
        {

        if(isset($_POST["btn_uploadserials"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $status = "new";
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();
				
				 $myid = $this->input->post("id");
				 		     $code = $this->input->post("code");

				  				  		     $invoice = $this->input->post("salesid");



				  		$newstock = $this->usermodel->populateallarray('newstock','id',$myid);
						
				  		$products = $this->usermodel->populateallarray('products','code',$code);
$name=$products[0]["name"];
	$sellingprice=$newstock[0]["sellingprice"];			  
				$buyingprice=$newstock[0]["buyingprice"];
	$description=$newstock[0]["description"];	  
		$branch=$newstock[0]["type"];				  
				  						  $createdate = date('Y-m-d H:i:s');


                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				  
				  
				 
				  
				  
				  
						 $myserialcode = $emapData['A'];
			
				if($myserialcode!=""){
				
				
					
					
					
			
						  
						  
						  	    $data[] = array(
                              
                               'serial' => $emapData['A'],
                          
										'qty' => 1,
									'itemid' => $myid,
									'buyingprice' => $buyingprice,
									'sellingprice' => $sellingprice,
									
									'createdate' => $createdate,
									'name' => $name,
 									'description' => $description,
								'status' => $status,
									'invoice' => $invoice,
 									'code' => $code,
 										'userid' => $userid,
											'batchno' => 1,
										'branch' => $branch,
 									'companyid' => $companyid,
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('serials', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded serial numbers  !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Serials were not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function uploadproducts()
        {

        if(isset($_POST["btn_uploaduploadproducts"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $code = $emapData['A'];
			
				if($code!=""){
				
				
					$credit = $emapData['E'];
					
					
						  $new_date=	date('Y-m-d');
						  
					
					 
					 if($emapData['M']!=""){
						  $producttype=$emapData['M'];
					 }else{
						 
						 		 $producttype="Inventory";

					 }
					 
					 
					 
					  if($emapData['N']!=""){
						  $orderamount=$emapData['N'];
					 }else{
						 
						 		 $orderamount="mainitem";

					 }
					   if($emapData['O']!=""){
						  $vattype=$emapData['O'];
					 }else{
						 
						 		 $vattype="VATABLE";
					 }
					 
					   if($emapData['P']!=""){
						  $vatrate=$emapData['P'];
					 }else{
						 
						 		 $vatrate="16";

					 }
					 
					 	   if($emapData['Q']!=""){
						  $reorderquantity=$emapData['Q'];
					 }else{
						 
						 		 $reorderquantity="0";

					 }
					 
					 
					 
						  	  $data[] = array(
                              
                               'code' => $emapData['A'],
                                 'name' => $emapData['B'],
 							
 									'description' => $emapData['C'],
									'qty' => $emapData['D'],
									'buyingprice' => $emapData['E'],
									'sellingprice' => $emapData['F'],
									'wholesaleprice' => $emapData['G'],
									'reorderevel' => $emapData['H'],
									'category' => $emapData['I'],
									'supplier' => $emapData['J'],
									'store' => $emapData['K'],
									'producttype' => $producttype,
								
									'hscode' => $emapData['R'],
									'itemclassification' => $emapData['S'],
									'country' => $emapData['T'],
									'itemtype' => $emapData['U'],
									'packagingunit' => $emapData['V'],
									'salesunit' => $emapData['W'],
									'itemstatus' => $emapData['X'],
									'itemtax' => $emapData['Y'],

									'userid' => $userid,
									'orderamount' => $orderamount,
									'tax_included' => $vatrate,
									'vattype' => $vattype,
									'reorderquantity' => $reorderquantity,

 									'companyid' => $companyid,
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('products', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded products !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Products were not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
public function updateall()
        {

        if(isset($_POST["btn_uploadall"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $code = $emapData['B'];
			$newcode = $emapData['C'];
				if($code!=""){
				
				
				
					
						  $new_date=	date('Y-m-d');
						  
					
					
					 
					 
			$alldata=array(		
			'code'=>$newcode,
											

			

								);
					$usr_result = $this->usermodel->updatedata($alldata,'products','code',$code);
					$usr_result = $this->usermodel->updatedata($alldata,'productlist','code',$code);
					$usr_result = $this->usermodel->updatedata($alldata,'uomproducts','code',$code);
					$usr_result = $this->usermodel->updatedata($alldata,'uomproducts','uom',$code);

						
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              


if ($usr_result ==TRUE) //active user record is present
							
						  
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded products !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Products were not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		public function uploadpayrollsetup()
        {

          if(isset($_POST["btn_uploadpayrollsetup"]))
            { 
				$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
		   $createdate = date('Y-m-d H:i:s');

 $userid = $data['id'];
		     $view = $this->input->post("view");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $idno = $emapData['C'];
						 $number = $emapData['D'];
						$memberid="";		
					if($idno!=""){
$people = $this->usermodel->populateallarray('people','idno',$idno);

      $memberid=$people[0]["id"];
				}else{
				$people = $this->usermodel->populateallarray('people','idno',$idno);

      $memberid=$people[0]["id"];	
				}
				
					if($memberid!=""){
					$credit = $emapData['E'];
					
					
						  $new_date=	date('Y-m-d');
						  
					
					 

					 
					 
						  	  $data[] = array(
                              
                              
                                 'name' => $emapData['E'],
									'code' => $emapData['F'],
 									'category' => $emapData['G'],
									'statutory' => $emapData['H'],
									'amount' => $emapData['I'],
									'quantity' => $emapData['J'],
									'amountmode' => $emapData['K'],
									'qtymode' => $emapData['L'],
									
									//'store' => $emapData[10],
								'createdate' => $createdate,
									'memberid' => $memberid,

									'userid' => $userid,
 									'companyid' => $companyid,
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				
	
				}

	
       }              	               
              
  if(!empty($data)){
			  $usr_result =$this->db->insert_batch('employeecharges', $data); 

  }else{
	  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>   payroll setup was not uploaded. Try check if all the ID Numbers exist in the system then try again.</div>');
						 redirect($view);
	  
  }
        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded payroll setup !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>   payroll setup was not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
			
			
			
			
			
			
			
			
			
			
	
public function uploadassets()
        {

          if(isset($_POST["btn_uploadassets"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		
		   $currenttime = date('Y-m-d H:i:s');
		    $status = $this->input->post("status");
					    $fromdate = $this->input->post("fromdate");
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				              //	$finalsalesid = $userid.time()+ 1;
						$code = $emapData['A'];
					$name = $emapData['G'];
				if($code!=""){
				
                 $debit = $emapData['T'];
					$credit = $emapData['U'];
					
					
					 $debit2 = $emapData['W'];
					$credit2 = $emapData['V'];
               
       
							$description= $emapData['E'];	
								$branchid= $emapData['F'];	
						$supplier= $emapData['A'];
               
                   $finaltotalamount=$emapData['H'];
							                   $Acumulativefinaltotalamount=$emapData['S'];
                   	$invoice = $userid.time()+ $i;

   $myfromdate = date("Y-m-d H:i:s", strtotime($emapData['M']));
	   $mytodate = date("Y-m-d H:i:s", strtotime($emapData['N']));





//
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
									'code' => $emapData['A'],

                                 'name' => $emapData['B'],
 							      'status' => $emapData['C'],

 									'assetcondition' => $emapData['D'],
									'mode' => $emapData['E'],
									'category' => $emapData['F'],
									'supplier' => $emapData['G'],
									'buyingprice' => $emapData['H'],
									'depreciationpercent' => $emapData['I'],

									'assetvalue' => $emapData['Q'],
									
									'serialno' => $emapData['J'],
									'qty' => $emapData['K'],
									'branch' => $emapData['L'],
									'start_date' => $myfromdate,
									'expdate' => $mytodate,
									'store' => $emapData['O'],
									'description' => $emapData['P'],
									
									
									
									'depreciation' => $emapData['R'],
									'assetaccount' => $emapData['T'],
									'salesaccount' => $emapData['U'],
									'accumulativeaccount' => $emapData['V'],
									'expenseaccount' => $emapData['W'],
											
									
									
									
									'invoice' => $invoice,

									'userid' => $userid,
 									'companyid' => $companyid,
									 'dateposted' => $currenttime,

 									
 									
                                );
                    
                        $usr_result = $this->usermodel->uploadASSETS($mydata);
						
					if($usr_result ==TRUE) //active user record is present
							{
									if($code!=""){
								 $debitdata=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>" Asset Opening Balance Equity",'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset",'refno'=> $code);


					$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$finaltotalamount,'description'=>$description,'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset",'refno'=> $code);

						
							$this->usermodel->add($debitdata,'debitcredit');
							$this->usermodel->add($creditdata,'debitcredit');							
							if($status=="old"){
							

$olddebitdata=array( 'userid'=>$userid,'account'=>$debit2,'debit'=>$Acumulativefinaltotalamount,'description'=>" Asset Opening Balance Equity",'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset");


					$oldcreditdata=array( 'userid'=>$userid,'account'=>$credit2,'credit'=>$Acumulativefinaltotalamount,'description'=>$description,'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset");

					
							$this->usermodel->add($olddebitdata,'debitcredit');	
									$this->usermodel->add($oldcreditdata,'debitcredit');
							}
	
						}
				}
		   $i++;
				}
	
	

	
       }              	               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
								
								
								
								
								
								
								
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded assets data!</div>');
								
								 redirect('user/viewassets');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Assets might have been added since they already exist or No data was saved.Try again</div>');
								
								 redirect('user/viewassets');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


public function uploadinventory()
        {

          if(isset($_POST["btn_uploadinventory"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		$totalcredit=0;
		   $currenttime = date('Y-m-d H:i:s');
		    $status = $this->input->post("status");
					    $fromdate = $this->input->post("fromdate");
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	     $debit=$configuration[0]["assetaccount"];
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
$debitdata = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				              //	$finalsalesid = $userid.time()+ 1;
						$code = $emapData['A'];
					$name = $emapData['B'];
				if($code!=""){
				
				
					$credit = $emapData['E'];
					
					
       
							
								$branchid= $emapData['F'];	
						$QTY= $emapData['C'];
						$BPRICE= $emapData['D'];
           
                   $TTAMAOUNT=$QTY*$BPRICE;
				   					$finaltotalamount= $this->MyformatMoney($TTAMAOUNT, true);

								$totalcredit= $this->MyformatMoney(($totalcredit+ $TTAMAOUNT),true);
							            
                   	$invoice = $userid.time()+ $i;

						  $new_date=	date('Y-m-d');
						  
						  
						  
						  
						   $debitdata[]=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>" Stock Opening Balance ",'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "inventory");
	
								
								
							 // $usr_result =	$this->usermodel->add($debitdata,'debitcredit');
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('debitcredit', $debitdata); 



        if($this->db->affected_rows() > 0)
	{
			
								
									if($totalcredit>0){

					$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$totalcredit,'description'=>"Stock Opening Balance Equity",'code'=>$invoice,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset");


						
					
							$this->usermodel->add($creditdata,'debitcredit');							
					
	
						}
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded inventory GL data!</div>');
								
								 redirect('user/viewproductlist');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Inventory might have not been  added since they already exist or No data was saved.Try again</div>');
								
								 redirect('user/viewproductlist');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
		
		public function uploadstocktaking()
        {

          if(isset($_POST["btn_uploadstocktaking"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		    $branchid = $this->input->post("branchid");
					    $fromdate = $this->input->post("fromdate");
   $type = $this->input->post("type");
		 $postedtime = date('Y-m-d');

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
			
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$updatestocktaingArray = array();
				$bothstockandprice = array();
				$bothpricesonly = array();
				$stockonly = array();
				$BothandNames = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
					

				if($branchid!=""){
					$names = $emapData['B'];
						$added = $emapData['D'];
					$buyingprice = $emapData['E'];
					$sellingprice = $emapData['F'];
					
							$wholesaleprice = $emapData['G'];

						$code = $emapData['A'];
					$getstock  = $this->usermodel->populatealldataarrayOpenstock('stocktaking','code', $code,'branchid', $branchid,'startdate', $fromdate,'companyid', $companyid);

					      $myid=$getstock[0]["id"];
					       $open=$getstock[0]["open"];
						   $productid="";
				
											 $balance = (double)$added- (double)$open;
											 
											 
											 
						
								
											 
			if($branchid=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);
    $productid=$productname[0]["id"];
			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);
    $productid=$productname[0]["id"];
			}	
								
								
								
								
									$BothandNames[]=array(		
									'name'=>$names,		
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
								'wholesaleprice'=>$wholesaleprice,

									'id'=>$productid,
										
													);
								
								$bothpricesonly[]=array(		
							'wholesaleprice'=>$wholesaleprice,

								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
									'id'=>$productid,
										
													);
												 
											 
											 
											 
				$updatestocktaingArray[]=array(		
												'added'=>$added,
											'balance'=>$balance,
													'updatedby'=>$userid,
													'closedate'=>$postedtime,
														'id'=>$myid,
													);
		
								$stockonly[]=array(		
												'qty'=>$added,
							
									'id'=>$productid,
												
													);
													
													
														$bothstockandprice[]=array(		
												'qty'=>$added,
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
															'wholesaleprice'=>$wholesaleprice,

									'id'=>$productid,
										
													);
							
										//$usr_result = $this->usermodel->updatedata($salesorderlist,'stocktaking','id',$myid);
						
				
	
	
	
	   $i++;
	   
				}
	
                   	  }  



if(!empty($updatestocktaingArray)){
  $usr_result =	$this->db->update_batch('stocktaking',$updatestocktaingArray, 'id');

}else{
 $usr_result =0;
	
}

	

			  

			  
			
			
			
                
       if($usr_result > 0)	
		   {
			   
			   	if($type=="Stock"){
					//// ---4--
					
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$stockonly, 'id');
	
						}else{
							if($branchid=="all"){
																				  $usr_result =	$this->db->update_batch('productlist',$stockonly, 'code');

							}else{
								
																				  $usr_result =	$this->db->update_batch('productlist',$stockonly, 'id');

							}
	
							
						}
							
			}else if($type=="Prices"){
					//// ---4--
					
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$bothpricesonly, 'id');
	
						}else{
							
								if($branchid=="all"){
																				  $usr_result =	$this->db->update_batch('productlist',$bothpricesonly, 'code');

							}else{
																			  $usr_result =	$this->db->update_batch('productlist',$bothpricesonly, 'id');
	
								
							}
							
	
							
						}
							
			}else if($type=="BothandNames"){
					//// ---4--
					
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$BothandNames, 'id');
	
						}else{
							
							
							
								if($branchid=="all"){
																				  $usr_result =	$this->db->update_batch('productlist',$BothandNames, 'code');

							}else{
																			  $usr_result =	$this->db->update_batch('productlist',$BothandNames, 'id');
	
								
							}
							
	
							
						}
							
			}else{
				
	if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$bothstockandprice, 'id');
	
						}else{
							
							
								if($branchid=="all"){
																				  $usr_result =	$this->db->update_batch('productlist',$bothstockandprice, 'code');

							}else{
								
																				  $usr_result =	$this->db->update_batch('productlist',$bothstockandprice, 'id');

							}
							
							
	
							
						
				
			}	
				
			} 
			   
			   
			   
			   
			   
			   
			   
			   
			   
			   
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded and updated stock taking!</div>');
								
								 redirect('user/viewtocktaking');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock taking was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/viewtocktaking');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function uploadbulkpricing()
        {

          if(isset($_POST["btn_uploadbulkuprices"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		    $branchid = $this->input->post("branchid");
					    $fromdate = $this->input->post("fromdate");
   $type = $this->input->post("type");
		 $postedtime = date('Y-m-d');

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
			
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$updatestocktaingArray = array();
				$bothstockandprice = array();
				$bothpricesonly = array();
				$stockonly = array();
				$BothandNames = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
					

				if($branchid!=""){
					$names = $emapData['B'];
						$added = $emapData['D'];
					$buyingprice = $emapData['E'];
					$sellingprice = $emapData['F'];
				$wholesaleprice = $emapData['G'];

						$code = $emapData['A'];

					     
						   $productid="";
				
											// $balance = $added-$open;
											 
											 
											 
						
								
											 
			if($branchid=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);
    $productid=$productname[0]["id"];
			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);
    $productid=$productname[0]["id"];
			}	
								
								
								
									$BothandNames[]=array(		
									'name'=>$names,		
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
									'id'=>$productid,
										
													);
									$BothandNames1[]=array(		
									'name'=>$names,		
								'sellingprice'=>$sellingprice,
								'wholesaleprice'=>$wholesaleprice,
								'buyingprice'=>$buyingprice,
								
											'code'=>$code,
													);
								
								$bothpricesonly[]=array(		
											
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
								'wholesaleprice'=>$wholesaleprice,
									'id'=>$productid,
										
													);
												 
											 		
								$bothpricesonly1[]=array(		
											
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
								'wholesaleprice'=>$wholesaleprice,
										'code'=>$code,

													);
											 
					$stockonly[]=array(		
												'qty'=>$added,
							
									'id'=>$productid,
													);
		
								$stockonly1[]=array(		
												'qty'=>$added,
							
												'code'=>$code,
													);
													
													
														$bothstockandprice[]=array(		
												'qty'=>$added,
								'sellingprice'=>$sellingprice,
								'wholesaleprice'=>$wholesaleprice,
								'buyingprice'=>$buyingprice,
									'id'=>$productid,
										
													);
															$bothstockandprice1[]=array(		
												'qty'=>$added,
								'sellingprice'=>$sellingprice,
								'wholesaleprice'=>$wholesaleprice,
								'buyingprice'=>$buyingprice,
								
										'code'=>$code,
													);
							
										//$usr_result = $this->usermodel->updatedata($salesorderlist,'stocktaking','id',$myid);
						
				
	
	
	
	   $i++;
	   
				}
	
                   	  }  



//if(!empty($updatestocktaingArray)){
  //$usr_result =	$this->db->update_batch('stocktaking',$updatestocktaingArray, 'id');

//}else{
 //$usr_result =0;
	
//}

	

			  

			  
			
			

			   	if($type=="Stock"){
					//// ---4--
					
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$stockonly, 'id');
	
						}else{
							
							
							if($branchid=="all"){
									$usr_result =	$this->db->update_batch('productlist',$stockonly, 'code');
							       $this->db->update_batch('products',$stockonly, 'code');

							}else{
								
								 $usr_result =	$this->db->update_batch('productlist',$stockonly, 'id');

							}
	
							
						}
							
			}else if($type=="Prices"){
					//// ---4--
				
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$bothpricesonly, 'id');
	
						}else{
							
							if($branchid=="all"){
								
									
							 $usr_result =	$this->db->update_batch('productlist',$bothpricesonly1, 'code');
								$this->db->update_batch('products',$bothpricesonly1, 'code');
							}else{
								
								
								
								
							$usr_result =	$this->db->update_batch('productlist',$bothpricesonly, 'id');
	
								
							}
							
	
							
						}
							
			}else if($type=="BothandNames"){
					//// ---4--
					
						if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$BothandNames, 'id');
	
						}else{
							
							
							
								if($branchid=="all"){
				 $usr_result =	$this->db->update_batch('productlist',$BothandNames1, 'code');
								$this->db->update_batch('products',$BothandNames1, 'code');

							}else{
				 $usr_result =	$this->db->update_batch('productlist',$BothandNames, 'id');
	
								
							}
							
	
							
						}
							
			}else{
				
	if($branchid=="Main"){
							
						  $usr_result =	$this->db->update_batch('products',$bothstockandprice, 'id');
	
						}else{
							
							
								if($branchid=="all"){
					 $usr_result =	$this->db->update_batch('productlist',$bothstockandprice1, 'code');
								$this->db->update_batch('products',$bothstockandprice1, 'code');

							}else{
					$usr_result =	$this->db->update_batch('productlist',$bothstockandprice, 'id');

							}
							
							
	
							
						
				
			}	
				
			} 
			   
			   
			   
			     if($usr_result > 0)	
		   {
			   
			   
			   
			   
			   
			   
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded prices in bulk!</div>');
								
								 redirect('user/viewproducts');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bulk Prices were not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/viewproducts');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function uploadpayrollist()
        {

          if(isset($_POST["btn_uploadpayrollraw"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		    $fiscalyear = $this->input->post("fiscalyear");
					    $fromdate = $this->input->post("fromdate");

		$getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$fiscalyear);

      $startdate=$getfiscalyear[0]["startdate"];
		 $enddate=$getfiscalyear[0]["enddate"];	 

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="supplier";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['G']!=""){
				
    
               
                   	$finalsalesid = $userid.time()+ $i;
					$finaltotalamount= $emapData['G'];
											$idno= $emapData['I'];
	
						  $new_date=	date('Y-m-d');
                       
								
								
								
										$peopledata=array(		
												'salary'=>$finaltotalamount,
											
													);
								
								
										  $usr_result =$this->usermodel->updatedata($peopledata,'people','idno',$idno);
							
							
							
                    
						
						if ($usr_result ==TRUE) //active user record is present
							{
						
						
							
									
							
							
							
							}
	
	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded the payroll!</div>');
								
								 redirect('user/salaryhistory');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some data were not saved.Try again</div>');
								
								 redirect('user/salaryhistory');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

		
		
		
		
		public function uploadsupplierinvoice()
        {

          if(isset($_POST["btn_uploadsupplierinvoice"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		    $fiscalyear = $this->input->post("fiscalyear");
					    $fromdate = $this->input->post("fromdate");

		$getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$fiscalyear);

      $startdate=$getfiscalyear[0]["startdate"];
		 $enddate=$getfiscalyear[0]["enddate"];	 

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="supplier";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['A']!=""){
				
        $debit = $emapData['C'];
					$credit = $emapData['D'];
               
                   	$finalsalesid = $userid.time()+ $i;
					$finaltotalamount= $emapData['B'];
							$description= $emapData['E'];	
								$branchid= $emapData['F'];	
						$supplier= $emapData['A'];
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
									'supplier' => $emapData['A'],

                                 'amount' => $emapData['B'],
 							      'balance' => $emapData['B'],

 									'description' => $emapData['E'],
									'branchid' => $emapData['F'],

									'status' => "Opening Balance",
									'fromdate' => $fromdate,
									'invoice' => $finalsalesid,

									'userid' => $userid,

 									'companyid' => $companyid,
									 'createdate' => $currenttime,
									 'paiddate' => $currenttime,

 									
 									
                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("purchaseorder",$mydata);
						
						if ($usr_result ==TRUE) //active user record is present
							{
						
						
								 $debitdata=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>"Opening Balance Equity",'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);


$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$finaltotalamount,'description'=>$description,'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);

							$this->usermodel->add($creditdata,'debitcredit');
							$this->usermodel->add($debitdata,'debitcredit');	
							
							
							
							
								$openingbalancedata=array(		
			'userid'=>$userid,
			
				'description'=>"Opening Balance",
							'enddate'=>$enddate,
							'customerid'=>$supplier,

'startdate'=>$startdate,

		  	'opening'=>$finaltotalamount,
				 'companyid'=>$companyid,

				 			'type'=>$type,

			'createdate'=>$currenttime,
			'closing'=>0,
			

			
								);
								
									$this->usermodel->add($openingbalancedata,'customersupplierbalance');
							
							
							
								$peopledata=array(		
												'supplierbalance'=>$finaltotalamount,
												'lastbalancedate'=>$currenttime,
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$supplier);
							
							
							
							
							
							}
	
	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded supplier opening balances data!</div>');
								
								 redirect('user/viewpurchases');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some  supplier opening balances was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/viewpurchases');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

		
		
	
public function uploadcustomerbalancess()
        {

          if(isset($_POST["btn_uploadcustomerbalancess"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		    $fiscalyear = $this->input->post("fiscalyear");
					    $fromdate = $this->input->post("fromdate");

		$getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$fiscalyear);

      $startdate=$getfiscalyear[0]["startdate"];
		 $enddate=$getfiscalyear[0]["enddate"];	 

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="customer";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['A']!=""){
				
        $debit = $emapData['C'];
					$credit = $emapData['D'];
               
                   	$finalsalesid = $userid.time()+ $i;
					$finaltotalamount= $emapData['B'];
							$description= $emapData['E'];	
								$branchid= $emapData['F'];	
						$supplier= $emapData['A'];
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
									'customer' => $emapData['A'],

                                 //'amount' => $emapData['B'],
 							      'balance' => "-".$emapData['B'],
									'credit' => $emapData['B'],
								'total' => $emapData['B'],

 									'description' => $emapData['E'],
									'branch' => $emapData['F'],

									'type' => "Opening Balance",
									//'fromdate' => $fromdate,
									'invoice' => $finalsalesid,

									'userid' => $userid,
									'salestype' => "retail",
 									'companyid' => $companyid,
									 'dateposted' => $fromdate,
									 'due_date' => $fromdate,
									 	'card' => 0,
									 	'voucher' => 0,
										'points' => 0,
									 	'mpesa' => 0,
 									'cheque' => 0,
 										'cash' => 0,
                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("sales",$mydata);
						
						if ($usr_result ==TRUE) //active user record is present
							{
						
						
								 $debitdata=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>"Opening Balance Equity",'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);


$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$finaltotalamount,'description'=>$description,'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);

							$this->usermodel->add($creditdata,'debitcredit');
							$this->usermodel->add($debitdata,'debitcredit');	
							
							
							
							
								$openingbalancedata=array(		
			'userid'=>$userid,
			
				'description'=>"Opening Balance",
							'enddate'=>$enddate,
							'customerid'=>$supplier,

'startdate'=>$startdate,

		  	'opening'=>$finaltotalamount,
				 'companyid'=>$companyid,

				 			'type'=>$type,

			'createdate'=>$currenttime,
			'closing'=>0,
			

			
								);
								
									$this->usermodel->add($openingbalancedata,'customersupplierbalance');
							
							
							
								$peopledata=array(		
												'balance'=>$finaltotalamount,
													'lastbalancedate'=>$currenttime,
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$supplier);
							
							
							
							
							
							}
	
	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Customer opening balances data!</div>');
								
								 redirect('user/allinvoices');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some  Customer opening balances was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/allinvoices');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

	
	
	
	
	
	
	
	
	
	
	
	
	
	public function uploadbudget()
        {

          if(isset($_POST["btn_uploadbudget"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		
					    $fromdate = $this->input->post("fromdate");
					    $year = $this->input->post("year");
					    $month = $this->input->post("month");

	

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="customer";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['A']!=""){
				
          $accounttype = $emapData['C'];
					
         

						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
								
			
				'code'=>$emapData['B'],
				'year'=>$year,
				'createdate'=>$fromdate,
				'month'=>$month,

				'description'=>$emapData['D'],
				'branch'=>$emapData['E'],


		  	'expamount'=>$emapData['C'],
				 'companyid'=>$companyid,
			
				 
				 

                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("budget",$mydata);
						
                    

	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Budget!</div>');
								
								 redirect('user/viewbudget');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some  Data was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/viewbudget');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


		
		
	
	
	
	
	
	
	
	
	
	
	
	

public function uploadcharts()
        {

          if(isset($_POST["btn_uploadcharts"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		
					    $fromdate = $this->input->post("fromdate");

	

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="customer";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['A']!=""){
				
          $accounttype = $emapData['C'];
					
               
                   	$finalsalesid = $userid.time()+ $i;
				$acctype = $this->usermodel->populateallarray('glgroups','id', $accounttype);


						 $myaccounttype=$acctype[0]['accounttype'];
					$acctype = $this->usermodel->populateallarray('accounttype','id', $myaccounttype);
						 $description=$acctype[0]['id'];


						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
									'number' => $emapData['A'],
									'accountname' => $emapData['B'],
									'accounttype' => $emapData['C'],
								'bankname' => $emapData['D'],

 								'amount' => $emapData['E'],
									'currency' => $emapData['F'],
										'openingdate' =>$fromdate,
										'createdate' =>$currenttime,

										  	'description'=>$description,
		

												'userid'=>$userid,
												'companyid'=>$companyid,
                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("glaccounts",$mydata);
						
                    

	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded charts of Account!</div>');
								
								 redirect('user/allaccounting');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some  Data was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/allaccounting');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


		
		
		
		
		
			
	
public function uploadlabour()
        {

          if(isset($_POST["btn_uploadlabour"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
					
				
                
                //  $inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                  //$inserdata[$i]['Address'] = $emapData['E'];
               
                   
							
						  $newtime=	date('H:i:s');
						  $exactdate=$emapData['F']." ".$newtime;
						  
						  $MYMONTH= ucfirst($emapData['D']);
						  								   	   $MYFINALexactdate = date("Y-m-d H:i:s", strtotime($exactdate));
														
if(($i !=0) || ($emapData['A'] !="")){
	
	
		$people= $this->usermodel->populateallarray('people','idno',$emapData['A']);

$employeeids=$people[0]["id"];
	
	
	 $accounts = $this->usermodel->populateallarraytwo('employeecharges','memberid',$employeeids,'code',$emapData['B']);
$rate=$accounts[0]["unit"];
$total=$rate* $emapData['C'];




	
                            $mydata = array(
                              
									'employeeid' => $emapData['A'],

                                 'code' => $emapData['B'],
 							      'qty' => $emapData['C'],
									'rate' => $rate,
 									'month' => $MYMONTH,
									'description' => $emapData['E'],
									'exactdate' => $MYFINALexactdate,
								
								'total' => $total,
 									'branch' => $branchid,

									'userid' => $userid,
 									'companyid' => $companyid,
									 'createdate' => $currenttime,

 									
 									
                                );
                        $usr_result = $this->usermodel->uploadlabour($mydata);
                    
						
						
}
	
	
	
	
	
	   $i++;
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Labour sheet data!</div>');
								
								 redirect('user/viewlabour');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Labour data was not uploded..Check the format and try again.Try again</div>');
								
								 redirect('user/viewlabour');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

		
		
		
		
		
		
		
			
	
public function uploadupgrade()
        {

          if(isset($_POST["btn_uploadupgrade"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		
	
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
					
				
                
                //  $inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                  //$inserdata[$i]['Address'] = $emapData['E'];
               
                   
							
								

                            $mydata = array(
                              
									'version' => $emapData['A'],

                                 'name' => $emapData['B'],
 							      'description' => $emapData['C'],

 									'exactdate' => $emapData['D'],
									'package' => $emapData['E'],
								

									'userid' => $userid,
 									'companyid' => $companyid,
									 'entrydate' => $currenttime,

 									
 									
                                );
                        $usr_result = $this->usermodel->uploadupgrade($mydata);
                    
						
						
	
	
	
	
	
	
	   $i++;
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded New Upgrade !</div>');
								
								 redirect('user/viewupgrade');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> New Upgrade  data was not uploaded..Check the format and try again.Try again</div>');
								
								 redirect('user/viewupgrade');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

					
					
					
					
					
					
					public function uploadDetailedsales()
        {

        if(isset($_POST["btn_uploaddetailedsales"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $code = $emapData['C'];
			
				if($code!=""){
				
				
				          $dateposted = date("Y-m-d H:i:s", strtotime($emapData['H'])); 
 $date = date("Y-m-d H:i:s", strtotime($emapData['U'])); 
					
					
						  $new_date=	date('Y-m-d H:i:s');
						  
						  
						  	    $data[] = array(
//'id' => $emapData['A'],
'invoice' => $emapData['B'],
'code' => $emapData['C'],
'qty' => $emapData['D'],
'amount' => $emapData['E'],
'salestype' => $emapData['F'],
'discount' => $emapData['G'],
'dateposted' => $dateposted,
'address' => $emapData['I'],
'description' => $emapData['J'],
'user' => $emapData['K'],
'bprice' => $emapData['L'],
'type' => $emapData['M'],
'tax' => $emapData['N'],
'sprice' => $emapData['O'],
'balance' => $emapData['P'],
'customer' => $emapData['Q'],
'userid' => $emapData['R'],
'mode' => $emapData['S'],
'companyid' => $emapData['T'],
'date' => $date,
'maincategory' => $emapData['V'],
'category' => $emapData['W'],
'status' => $emapData['X'],
'branch' => $emapData['Y'],
'ordersales' => $emapData['Z'],
'uom' => $emapData['AA'],
'sales' => $emapData['AB'],
'updatedat' => $emapData['AC'],
'updatedby' => $emapData['AD'],
'taxindicator' => $emapData['AE'],
'serial' => $emapData['AF'],
'tax2' => $emapData['AG'],
'discountype' => $emapData['AH'],
'discountvalue' => $emapData['AI'],	
'vattype' => $emapData['AJ'],
'taxable' => $emapData['AL'],	
'uomqty' => $emapData['AL'],	
'stockbefore' => $emapData['AM'],	
'stockafter' => $emapData['AN'],	
'taxtype' => $emapData['AO'],
'myinvoice' => $emapData['AP'],



   
									//'store' => $emapData[10],
									//'updatedby' => $userid,
 									//'updatedat' => $updatedat,
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('sales_order', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Sales !</div>');
								
								 redirect("user/startsales");
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Sales were not uploaded.Try again</div>');
								 redirect("user/startsales");
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
					
					
					
					
					
					
					
					
					
					
					
					
					
					public function uploadsummarysales()
        {

        if(isset($_POST["btn_uploadsummarysales"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $code = $emapData['C'];
			
				if($code!=""){
				
				
				          $due_date = date("Y-m-d H:i:s", strtotime($emapData['E'])); 
						  $dateposted = date("Y-m-d H:i:s", strtotime($emapData['I'])); 

 $date = date("Y-m-d H:i:s", strtotime($emapData['U'])); 
					
					
						  $new_date=	date('Y-m-d H:i:s');
						  
						  
						  	    $data[] = array(
'id' => $emapData['A'],
'cashier' => $emapData['B'],
'type' => $emapData['C'],
'amount' => $emapData['D'],
'due_date' => $due_date,
'name' => $emapData['F'],
'balance' => $emapData['G'],
'userid' => $emapData['H'],
'dateposted' => $dateposted,
'customer' => $emapData['J'],
'cash' => $emapData['K'],
'total' => $emapData['L'],
'companyid' => $emapData['M'],
'salestype' => $emapData['N'],
'maindiscount' => $emapData['O'],
'discountedtotal' => $emapData['P'],
'branch' => $emapData['Q'],
'card' => $emapData['R'],
'voucher' => $emapData['S'],
'credit' => $emapData['T'],
'points' => $emapData['U'],
'mpesa' => $emapData['V'],
'cheque' => $emapData['W'],
'ordersales' => $emapData['X'],
'description' => $emapData['Y'],
'mytable' => $emapData['Z'],
'maincategory' => $emapData['AA'],
'creditnote' => $emapData['AB'],
'invoice' => $emapData['AC'],
'paymentstatus' => $emapData['AD'],
'updatedby' => $emapData['AE'],
'updatedat' => $emapData['AF'],
'plotno' => $emapData['AG'],
'houseno' => $emapData['AH'],
'baddebt' => $emapData['AI'],
'tax1' => $emapData['AJ'],
'tax2' => $emapData['AK'],
'cardnumber' => $emapData['AL'],
'savedcoins' => $emapData['AM'],
'savedpoints' => $emapData['AN'],
'salesperson' => $emapData['AO'],
'cashier' => $emapData['AP'],
'receiptno' => $emapData['AQ'],



   
									//'store' => $emapData[10],
									//'updatedby' => $userid,
 									//'updatedat' => $updatedat,
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('sales', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Sales !</div>');
								
								 redirect("user/startsales");
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Sales were not uploaded.Try again</div>');
								 redirect("user/startsales");
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
					
					
					
					
					
					
					
					
					
					
					
		public function downloaddetailedsles() {
			
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

			   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  		 $maincategory = $this->input->post("maincategory");

		 $fromdate = $this->input->post("fromdate");
			 $todate = $this->input->post("todate");
						 $group = $this->input->post("group");
						 $downloadtype = $this->input->post("downloadtype");

			 
			 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		  
		 $branchid = $this->input->post("branchid");
		    $searchdata = array(
			             'maincategory' => $maincategory,
							'group' => $group,
						 'downloadtype' => $downloadtype,

                         'branchid' => $branchid,
						 'fromdate' => $finalfromdate,
                          'todate' => $finaltodate,
						  );

			$usr_result = $this->usermodel->downloaddetailedsles($searchdata);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the  data..</div>');	
								 redirect("user/startsales");
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There was no data found for that range.. Try again</div>');
								
								 redirect("user/startsales");
							}
	
  }
	
		
			
		public function downloadsummarysles() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

		
		 			   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  
		 $fromdate = $this->input->post("fromdate");
			 $todate = $this->input->post("todate");
			
			 
			 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		  
			 $branchid = $this->input->post("branchid");
		
		    $searchdata = array(
                         'branchid' => $branchid,
						 'fromdate' => $finalfromdate,
                          'todate' => $finaltodate,
						  );

			$usr_result = $this->usermodel->downloadsummarysles($searchdata);

													
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the  data..</div>');	
								 redirect("user/startsales");
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There was no Data found.. Try again</div>');
								
								 redirect("user/startsales");
							}
	
  }
		
		
		
		
		public function downloadloggsbydate() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."downloadedloggs.csv";
		 $fromdate = $this->input->post("fromdate");
			 $todate = $this->input->post("todate");
								
							
								      //  $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";
	
 									

        $query = "SELECT  people.firstname,timedone,actiondone,ip FROM activityloggs  INNER JOIN people on activityloggs.userid =people.id   WHERE timedone BETWEEN '$fromdate'  and '$todate' ORDER BY activityloggs.id desc";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function downloadloggs() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."downloadedloggs.csv";
		
								
							
								      //  $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";
	
 									

        $query = "SELECT  people.firstname,timedone,actiondone,ip FROM activityloggs  INNER JOIN people on activityloggs.userid =people.id   ORDER BY activityloggs.id desc";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
		
		
	
	   public function downloadmpesacontacts() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."MPESA_CONTACTS.csv";
		
								
							
									
 									

        $query = "SELECT  sender_number as Phone,lastname,firstname,exactime FROM sms_in where   amount >0 and sender_number !=''  GROUP BY sender_number ORDER BY id desc";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

	
	
	
  }
		
			public function uploadcategoryproducts()
        {

          if(isset($_POST["btn_uploadcategoryproducts"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
		
		
					   	if($companyid==2){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload bulk /group contacts/products because you have note subcribe to unlimited/premium account. You are still using test account . You can contact us through :0780655987 or info@robisearch.com for full/unlimited (premium) account setup to enjoy more Services</div>');
							
								 redirect($view);
								 return false;
								 
		}
			
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 

					  $new_date=	date('Y-m-d');
						    $data = array(
                              
                               'id' => $emapData[0],
                                 'name' => $emapData[1],
 							
 									'description' => $emapData[2],
									'status' => $emapData[3],
									'maincategory' => $emapData[4],
									'companyid' =>$companyid,
									'userid' => $userid ,
										
 									
                                );
										    $data3 = array(
                              
                               'database' => $emapData[0],
                                 'user' => $emapData[1],
 							
 									'password' => $emapData[2],
									'status' => "active",
									'companyid' =>$companyid,
									'userid' => $userid ,
								'createdat' => $new_date ,

 									
                                );
                       
						                       //	$usr_result = $this->usermodel->uploadbackup($data);

                    	$usr_result = $this->usermodel->uploadallcategoryproduct($data);
  
						 

                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded product category!</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products category might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }
		
		
		public function uploadcategoryproducts__()
        {

          if(isset($_POST["btn_uploadcategoryproducts"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
		
		
					   	if($companyid==2){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload bulk /group contacts/products because you have note subcribe to unlimited/premium account. You are still using test account . You can contact us through :0780655987 or info@robisearch.com for full/unlimited (premium) account setup to enjoy more Services</div>');
							
								 redirect($view);
								 return false;
								 
		}
			
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 

					  $new_date=	date('Y-m-d');
						    $data = array(
                              
                               
                                 'country' => $emapData[0],
 							
 									'currency' => $emapData[1],
									'code' => $emapData[2],
									'symbol' => $emapData[3],
								
										
 									
                                );
										
						                       //	$usr_result = $this->usermodel->uploadbackup($data);
								$usr_result = $this->usermodel->add($data,'allcurrencies');

  
						 

                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded product category!</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products category might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }
		
		
		
		
			
public function uploadproductlistchild()
        {

          if(isset($_POST["btn_uploadproductlist"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		$view = $this->input->post("view");
			 $type = $this->input->post("type");
	 $source = $this->input->post("source");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				  $mybuyingprice ="";
						$mybranchid=$emapData['F']; 
						$mycode=$emapData['B'];   						
					 if($mybranchid=="Main")
						   {
							   
							$mainstock = $this->usermodel->populateallarray('products','code', $mycode);
							$mybuyingprice=(double)$mainstock[0]['buyingprice']*(double)$emapData['C'];
 
						   }else{
							   
						 $mainstock = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $mybranchid);
						$mybuyingprice=(double)$mainstock[0]['buyingprice']*(double)$emapData['C'];

							   
							}
	if($source=="System"){
		$mybuyingprice=$mybuyingprice;
		
	}else{
		$mybuyingprice=$emapData['D'];
		
	}
	
	
							
								

                            $mydata = array(
                              
								

								       'code' => $emapData['A'],
                                 'uom' => $emapData['B'],
 							
 									'qty' => $emapData['C'],
									 'brice' => $mybuyingprice,
 							
 									'price' => $emapData['C'],
									'branch' => $emapData['F'],
									
									
									
									
									'status' => $type,

									'createdate' => $new_date,
									'userid' => $userid,
 									'companyid' => $companyid,
 									'branch' => $branchid,
 									
                                );
                    
					//$usr_result = $this->usermodel->add($data,'uomproducts');

						         $usr_result = $this->usermodel->uploadCHILD($mydata);
	
	
	
	
	
	
	   $i++;
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded child products !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> New child  data was not uploaded..Check the format and try again.Try again</div>');
								
								redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }

					
					
				
				
public function uploadproductlistchildOLD()
        {

          if(isset($_POST["btn_uploadproductlist"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		
		
		
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		
		
		
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
		
		

		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						
						  $new_date=	date('Y-m-d');
						    $data = array(
                              
                               'code' => $emapData[1],
                                 'uom' => $emapData[2],
 							
 									'qty' => $emapData[3],
									 'brice' => $emapData[4],
 							
 									'price' => $emapData[5],
									'branch' => $emapData[6],
									
									'status' => $type,

									'createdate' => $new_date,
									'userid' => $userid,
 									'companyid' => $companyid,
 									'branch' => $branchid,
										
 									
                                );
                       
						   
                    	//$usr_result = $this->usermodel->uploadallproductlistchild($data,$type);
  						$usr_result = $this->usermodel->add($data,'uomproducts');

						 

                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded sub products !</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }
		
		
		
		
public function uploadfollowups()
        {

          if(isset($_POST["btn_uploadfollowups"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		
		
		
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		
		
		
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
		
		

		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
									 $nextstep = $emapData[11];
		 $followup=$this->usermodel->populateallarray('deals','nextstep', $nextstep);


			$followupid=$followup[0]['id'];	
			
			
				// $confirmdeal = $this->usermodel->populatealldataarray('followups','finalid', $nextstep,'followupid', $followupid);


						  $new_date=	date('Y-m-d');
						    $data = array(
                              

                             	'id' => $emapData[0],
                                 'followupid' => $followupid,
								 'userid' => $emapData[2],
								 'status' => $emapData[3],
                                 'companyid' => $emapData[4],
								 'nextdate' => $emapData[5],
								 'feedback' => $emapData[6],
                                 'recommendation' => $emapData[7],
								 'challanges' => $emapData[8],
								 'level' => $emapData[9],
                                 'branchid' => $emapData[10],
								 'finalid' => $emapData[11],
								 
								  'dateposted' => $emapData[12],
								 
								 
									
 									
                                );
                       
						   
                    	$usr_result = $this->usermodel->uploadalldeals($data,$nextstep);
  
						 

                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded sub products !</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }
		
		
		
		
		
		
	
      		
public function uploaddeals()
        {

          if(isset($_POST["btn_uploaddeals"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		
		
		
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		
		
		
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
		
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $phone = $emapData['A'];
			
				if($phone!=""){
				
				
					  $BUSINESS = $emapData["B"];
								 
									 $finalsalesid = $userid.time();
  $CORRECTDATA= explode("-",$BUSINESS);
								  $FINALBUSINESS = ($CORRECTDATA[0]);
								   $contactname = trim($CORRECTDATA[1]);
								   
								   
								     $BUSINESSfeeback= explode("-",$emapData["D"]);
									  $allsteps = trim($BUSINESSfeeback[0]);

									  $comments = trim($BUSINESSfeeback[1]);

						  	         $new_date = date('Y-m-d H:i:s');
									 
									 
					$checknumber  = $this->usermodel->populatealldatanoarray('deals','contact', $phone,'companyid',$companyid );
		
		
						if(!is_array($checknumber)) {


						  	    $data[] = array(
                              
                               'owner' => $FINALBUSINESS,
								 'title' => $emapData["C"],
								 'contact' => $emapData["A"],
                                 'type' => "Cold call",
								 'nextstep' => $finalsalesid,
								 'contactname' => $contactname,
                                 'amount' => 0,
								 'fromdate' => $emapData["E"],
								 'todate' => $emapData["F"],
                                 'probability' => "High",
								 'expectedrevenue' => 0,
								 
								  'stage' => "new",
								 'status' => "active",
                                 'comments' => $comments,
								 'userid' => $userid,

								 'dateposted' => $new_date,
								 'companyid' => $companyid,
                                 'allsteps' => $allsteps,
								 'dealowner' => $userid,
								  'branchid' => $branchid,
 									
 									
                                );
						  
					 }	  
						
						
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('deals', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
					 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded sub products !</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
		
		
		
		
public function uploadproductlist_old()
        {

          if(isset($_POST["btn_uploadproductlist"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
		
		
					   	if($companyid==2){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload bulk /group contacts/products because you have note subcribe to unlimited/premium account. You are still using test account . You can contact us through :0780655987 or info@robisearch.com for full/unlimited (premium) account setup to enjoy more Services</div>');
							
								 redirect($view);
								 return false;
								 
		}
			
		
		
		
		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						
						  $new_date=	date('Y-m-d');
						    $data = array(
                              
                               'code' => $emapData[0],
                                 'name' => $emapData[1],
 							
 									'description' => $emapData[2],
									'qty' => $emapData[3],
									'buyingprice' => $emapData[4],
									'sellingprice' => $emapData[5],
									'promoprice' => $emapData[6],
									'wholesaleprice' => $emapData[6],
									'reorderevel' => $emapData[7],
									'category' => $emapData[8],
									
									'supplier' => $emapData[9],
									'userid' => $userid,
 									'companyid' => $companyid,
 									'branch' => $emapData[10],
										
 									
                                );
                       
						   
                    	$usr_result = $this->usermodel->uploadallproductlist($data);
  
						 

                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded product data!</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Products might have been added since they already exist or No data was saved.Try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }
		
		
		
		
		

		
		public function uploadproductlist()
        {

        if(isset($_POST["btn_uploadproductlist"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		     $view = $this->input->post("view");
			 $type = $this->input->post("type");
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						 $code = $emapData['A'];
			
				if($code!=""){
				
				 if($emapData['M']!=""){
						  $producttype=$emapData['M'];
					 }else{
						 
						 		 $producttype="Inventory";

					 }
					   if($emapData['N']!=""){
						  $orderamount=$emapData['N'];
					 }else{
						 
						 		 $orderamount="mainitem";

					 }
					 
					  if($emapData['O']!=""){
						  $vattype=$emapData['O'];
					 }else{
						 
						 		 $vattype="VATABLE";
					 }
					 
					   if($emapData['P']!=""){
						  $vatrate=$emapData['P'];
					 }else{
						 
						 		 $vatrate="16";

					 }
					 
					 	   if($emapData['Q']!=""){
						  $reorderquantity=$emapData['Q'];
					 }else{
						 
						 		 $reorderquantity="0";

					 }
					 
				
					$credit = $emapData['E'];
					
					
						  $new_date=	date('Y-m-d');
						  
						  
						  	    $data[] = array(
                              
                               'code' => $emapData['A'],
                                 'name' => $emapData['B'],
 							
 									'description' => $emapData['C'],
									'qty' => $emapData['D'],
									'buyingprice' => $emapData['E'],
									'sellingprice' => $emapData['F'],
									'wholesaleprice' => $emapData['G'],
									'reorderevel' => $emapData['H'],
									'category' => $emapData['I'],
									'supplier' => $emapData['J'],
										'branch' => $emapData['K'],
											'store' => $emapData['L'],
												'hscode' => $emapData['R'],
									'itemclassification' => $emapData['S'],
									'country' => $emapData['T'],
									'itemtype' => $emapData['U'],
									'packagingunit' => $emapData['V'],
									'salesunit' => $emapData['W'],
									'itemstatus' => $emapData['X'],
									'itemtax' => $emapData['Y'],
									'expdate' => $emapData['z'],
												
												
												
												
												
												
											'orderamount' => $orderamount,
								'producttype' => $producttype,	

					 
									'tax_included' => $vatrate,
									'vattype' => $vattype,
									'reorderquantity' => $reorderquantity,	 

									'userid' => $userid,
 									'companyid' => $companyid,
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
       }              	               
              
			  $usr_result =$this->db->insert_batch('productlist', $data); 



        if($this->db->affected_rows() > 0)
	{
			
						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded products !</div>');
								
								 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Products were not uploaded.Try again</div>');
						 redirect($view);
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	
public function uploadpurchases()
        {

          if(isset($_POST["btn_uploadpurchases"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
	         $finaltime = date('Y-m-d H:i:s');

		   $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
				  $dateposted = date('Y-m-d H:i:s');

				     $view = $this->input->post("view");

		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						
						
						
								 $invoice_number=($emapData[0]);
								 $mycode=($emapData[1]);
								 $branch=($emapData[6]);
								  $compare=($emapData[5]);
								$buyingprice=($emapData[3]);
							$oldqty=($emapData[2]);
							$mybranch=($emapData[4]);
														$tax=($emapData[7]);

						
							$confirminvoice= $this->usermodel->populateall('purchaseorder','invoice',$invoice_number);
	
								
								
						


   if($confirminvoice !=false){
	   
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Error!</strong> This invoice number ('.$invoice_number.') does not exist. Kindly create it first in the system then upload the purchases.</div>');
								
									// redirect($view);
   
	   
	   	if( $mybranch=="store"){
											 $myproducts = $this->usermodel->populateallarray('products','code', $mycode);

				}else{
										 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);
	
				}

	   
	   
$mybuyingprice=$myproducts[0]['buyingprice'];
		$mysellingprice=$myproducts[0]['sellingprice'];
		$availableqty=$myproducts[0]['qty'];
		

		
		
						 
						if(($buyingprice!=$mybuyingprice)&& ($compare=="yes")) {
					$myfinalybuyingprice=($mybuyingprice+$buyingprice)/2;
					//$averageprice=((($mybuyingprice*$availableqty)+($buyingprice*$oldqty))/($availableqty+$oldqty));
					//$finalybuyingprice= $this->MyformatMoney($averageprice, true);

					$finalybuyingprice= $this->MyformatMoney($myfinalybuyingprice, true);

						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
	
						$finalqty=$availableqty+$oldqty;
  

	  
						
						$newqtyDATA=array(		
						
										'qty'=>$finalqty,
										 'buyingprice' => $finalybuyingprice, 
										);
			
					
						$to=null;
						 	if( $mybranch=="store"){
								$to="Main";
							}else{
								$to=$branch;

							}
						
						
						  $new_date=	date('Y-m-d');
						  	$mydata=array(		
			'userid'=>$userid,
			
				'item_id'=>$mycode,
			'total'=>$oldqty,
		  	'invoice_number'=>$invoice_number,
			
						'companyid'=>$companyid,
'description'=>"",
'type'=>$to,
			'date'=>$dateposted,
			'supplier' => 'multiple',		  
		  
		    'buyingprice' => $finalybuyingprice, 
			     'stockfrom' => 'supplier',		  
		  
		    'stockto' => $to, 

						    'tax' => $tax, 

			
			
			
								);
                       
						   
                    			if( $mybranch=="store"){
					$usr_result = $this->usermodel->updatedata($newqtyDATA,'products','code',$mycode);
								$usr_result = $this->usermodel->add($mydata,'newstock');

				}else{
		$usr_result = $this->usermodel->updatedatabytwo($newqtyDATA,'productlist','code',$mycode,'branch',$branch);
									$usr_result = $this->usermodel->add($mydata,'newstock');

					
				}
			
						
  
						 

                     }
					   }
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully uploaded the new purchases !</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Error!</strong> Purchase was not uploaded. Check the order of columns and try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }

		
		
				
	
public function uploadlpo()
        {

          if(isset($_POST["btn_uploadpurchases"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
	         $finaltime = date('Y-m-d H:i:s');

		   $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
				  $dateposted = date('Y-m-d H:i:s');

				     $view = $this->input->post("view");

		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						
						
						
								 $invoice_number=($emapData[0]);
								 $mycode=($emapData[1]);
								 $branch=($emapData[6]);
								  $compare=($emapData[5]);
								$buyingprice=($emapData[3]);
							$oldqty=($emapData[2]);
							$mybranch=($emapData[4]);
							$tax=($emapData[7]);
						
							$confirminvoice= $this->usermodel->populateall('purchaseorder','invoice',$invoice_number);
	
								
								
						


   if($confirminvoice !=false){
	   
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Error!</strong> This invoice number ('.$invoice_number.') does not exist. Kindly create it first in the system then upload the purchases.</div>');
								
									// redirect($view);
   
	   
	   	if( $mybranch=="store"){
											 $myproducts = $this->usermodel->populateallarray('products','code', $mycode);

				}else{
										 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);
	
				}

	   
	   
$mybuyingprice=$myproducts[0]['buyingprice'];
		$mysellingprice=$myproducts[0]['sellingprice'];
		$availableqty=$myproducts[0]['qty'];
		

		
		
						 
						if(($buyingprice!=$mybuyingprice)&& ($compare=="yes")) {
					$myfinalybuyingprice=($mybuyingprice+$buyingprice)/2;
					//$averageprice=((($mybuyingprice*$availableqty)+($buyingprice*$oldqty))/($availableqty+$oldqty));
					//$finalybuyingprice= $this->MyformatMoney($averageprice, true);

					$finalybuyingprice= $this->MyformatMoney($myfinalybuyingprice, true);

						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
	
						$finalqty=$availableqty+$oldqty;
  

	  
						
						$newqtyDATA=array(		
						
										'qty'=>$finalqty,
										 'buyingprice' => $finalybuyingprice, 
										);
			
					
						$to=null;
						 	if( $mybranch=="store"){
								$to="Main";
							}else{
								$to=$branch;

							}
						
						
						  $new_date=	date('Y-m-d');
						  	$mydata=array(		
			'userid'=>$userid,
			
				'item_id'=>$mycode,
			'qty'=>$oldqty,
		  	'invoice'=>$invoice_number,
			//'invoice_number'=>$invoice_number,
						'companyid'=>$companyid,
'description'=>"",
'type'=>$to,
			'date'=>$dateposted,
			'supplier' => 'multiple',		  
		  			'status' => 'PO',		  

		    'buyingprice' => $finalybuyingprice, 
			     'stockfrom' => 'supplier',		  
		  
		    'stockto' => $to, 
  
		    'tax' => $tax, 
				
			
			
			
								);
                       
						   
                    			if( $mybranch=="store"){
					$usr_result = $this->usermodel->updatedata($newqtyDATA,'products','code',$mycode);
								$usr_result = $this->usermodel->add($mydata,'newstock');

				}else{
		$usr_result = $this->usermodel->updatedatabytwo($newqtyDATA,'productlist','code',$mycode,'branch',$branch);
									$usr_result = $this->usermodel->add($mydata,'newstock');

					
				}
			
						
  
						 

                     }
					   }
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully uploaded the new purchases !</div>');
								
									 redirect($view);
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Error!</strong> Purchase was not uploaded. Check the order of columns and try again</div>');
								
									 redirect($view);
							}

                  }
            }
        }

		
		
	
    public function LookupReturnsales(){  
        $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->returnlookup($keyword, $companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->invoice,										
                                        'value' => $row->invoice,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	 public function purchaselookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",										
                                        'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	 public function getitmclassificationcodes(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->getitmclassificationcodes($keyword,$companyid,"itemclassification"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->itm_class_code,
										'label' => $row->itm_class_code."-".$row->name,	
                                        'value' => $row->itm_class_code.":=".$row->name,  
										
                                        //'value' => $row->itm_class_code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewproducts',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	 public function getcountryoforigin(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"nation"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description,	
                                        'value' => $row->code.":=".$row->name,  
										
                                        //'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	 public function getpackagingunits(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"packagingcodes"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description,	
                                        'value' => $row->code.":=".$row->name,  
										
                                        //'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    
	
	 }
	
	
		 public function getitemtypes(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"itemtypecodes"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description,	
                                        'value' => $row->code.":=".$row->name,  
										
                                       // 'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
	
	
	 public function getitemtax(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"taxcodes"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->tax_code,
										'label' => $row->name."-".$row->rate_code2,	
                                        'value' => $row->tax_code.":=".$row->name,  
										
                                       // 'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
		 public function getitemStatus(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"itemstatuscodes"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description,	
                                        'value' => $row->code.":=".$row->name,  
										
                                       // 'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
	
	
		 public function getsalesunit(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"quantitycodes"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description,	
                                        'value' => $row->code.":=".$row->name,  
										
                                       // 'value' => $row->code,  
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
	
	
	
		
		 public function itemscodeslookup2(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->itemscodeslookup($keyword,$companyid,"products"); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->depreciation,										
                                        //'value' => $row->id, 
                                        'value' => $row->code.":=".$row->name." ".$row->depreciation,  

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		 public function newdealslookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->newdealslookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->contact."-".$row->owner."-".$row->contactname."(".$row->	title.")",										
                                        //'value' => $row->id, 
                                        'value' => $row->contact.":=".$row->owner." ".$row->contactname,  

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	public function newcategories(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->newcategories($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->name,										
                                        //'value' => $row->id, 
                                        'value' => $row->name,  

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
		 public function newdealsfeedbacklookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->newdealsfeedbacklookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->name."-".$row->description,										
                                        //'value' => $row->id, 
                                        'value' => $row->name,

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
		 public function newfollowup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->newfollowup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->contact."-".$row->owner."-".$row->contactname."(".$row->	title.")",										
                                        //'value' => $row->id, 
                                        'value' => $row->contact.":=".$row->owner." ".$row->contactname,  

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	 public function customerlookup(){  
	 
	 
	 
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));
    $addpeople=$this->usermodel->populatuserpermissionsdataarray('members','add',$userid);




		
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->returnuserlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
			
			
			if( $addpeople==true){
			  $data['message'][] = array(   
                                        'id'=>$row->id,
										
										
										'label' => $row->company."-".$row->firstname."-".$row->lastname."(".$row->	phone."/=)",
										
                                        //'value' => $row->id, 
                                        'value' => $row->id.":=".$row->company." ".$row->firstname,  

										
                                       
                                     );	
				
				
				
			}else{
				
			  $data['message'][] = array(   
                                        'id'=>$row->id,
										
										
										//'label' => $row->company."-".$row->firstname."-".$row->lastname."(".$row->	phone."/=)",
										'label' => $row->company."-".$row->firstname."-".$row->lastname."",										
										
                                        //'value' => $row->id, 
                                        'value' => $row->id.":=".$row->company." ".$row->firstname,  

										
                                       
                                     );	
				
			}
                //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	 public function glaccountlookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->glaccountlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->accountname." ".$row->number,										
                                        //'value' => $row->id, 
                                        'value' => $row->number.":=".$row->accountname, 

										
                                       
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
		public function Projectlookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->Projectlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->name."-".$row->description."-".$row->invoice."",										
                                       // 'value' => $row->id,  
                                       'value' => $row->id.":=".$row->name." ".$row->description,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
		
	public function customerAttendancelookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->allcustomerlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->idno."-".$row->firstname."-".$row->idnumber."(".$row->	phone."/=)",										
                                       // 'value' => $row->id,  
                                       'value' => $row->idno.":=".$row->firstname." ".$row->surname,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
 
  public function getpaymentformembers() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];




			$mycustomer=$this->usermodel->Getmembernumber($phone);
			$customer=$mycustomer[0]['balance'];
$updatedbalance=(-1*$customer);	








//
 if($mycustomer!=false){
	 
	 $accountdetails= $mycustomer[0]['id'].":=".$mycustomer[0]['company']." ".$mycustomer[0]['firstname'].",Bal ".$updatedbalance;


  $data['salesid']=$salesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong> The balance for '.$mycustomer[0]['firstname'].' is ' .$updatedbalance.' No: '.$mycustomer[0]['address_1'].'  </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'?customer='.$accountdetails);	

	 
 }else{
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That User/Member with('.$phone.') does not exist in the system or belong to different branch..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
  
  

	}
 
 
 
 
 
 
 
	
	
	
	
	
	
	
			
	public function allcustomerlookupCustomeronly(){  
           $session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->allcustomerlookupCustomeronly($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->company."-".$row->firstname."-".$row->idno." ".$row->phone."/="."Bal:".$row->balance.")",										
                                       // 'value' => $row->id,  
                                       'value' => $row->id.":=".$row->company." ".$row->firstname.",Bal ".$row->balance,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
		
	public function customerSaleslookup(){  
           $session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->allcustomerlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->company."-".$row->firstname."-".$row->idno." ".$row->phone."/="."PTS:".$row->savedpoints.")",										
                                       // 'value' => $row->id,  
                                       'value' => $row->id.":=".$row->company." ".$row->firstname,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	public function SupplierSaleslookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
		//
        $query = $this->usermodel->allsupplierlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->company."-".$row->firstname."-".$row->idno."(".$row->	phone."/=)",										
                                       // 'value' => $row->id,  
                                       'value' => $row->id.":=".$row->company." ".$row->firstname,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	public function customerPhonelookup(){  
           $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->allcustomerlookup($keyword,$companyid); //Search DB  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->id,
										'label' => $row->firstname."-".$row->company."-".$row->idno."(".$row->	phone."/=)",										
                                       // 'value' => $row->id,  
                                       'value' => $row->phone,  

                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('startsales',$data); //Load html view of search results  
        }  
    } 
	












//
//
//
//




  public function branchlookupstocktaking(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->branchlookupstocktaking($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	





    public function branchlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->branchlookupddd($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	 public function buyinglookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookup($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(".$row->buyingprice."/= STOCK:".$row->qty.")",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
   

    public function lookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->branchlookpurchase($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	


    public function lookupquotation(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->lookupquotation($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==true){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	




    public function lookup_productsbranch(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('productlist','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('productlist','dontshowstock',$userid);

		 
		 
		 
		 
		  	     // $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	   // $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->branchlookpurchase($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==false){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==false){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	







    public function lookup_productsbranchItemsonly(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('productlist','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('productlist','dontshowstock',$userid);

		 
		 
		 
		 
		  	     // $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);
	   // $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('sales','dontshowstock',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
       // $query = $this->usermodel->branchlookup($keyword,$branchid);  
		       // $query = $this->usermodel->branchlookup($keyword,$branchid); 
		        $query = $this->usermodel->branchlookpurchase($keyword,$branchid);  
				

        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
             

 if( $dontshowstock==true){
	 
	  if( $viewbuyingprice==false){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice.",Wh=".$row->wholesaleprice."; BP=".$row->buyingprice.")",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice."; ;)",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  


		}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 }else{
	 
	 
	 
							
 if( $viewbuyingprice==false){

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice. "; Wh=".$row->wholesaleprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; Wh=".$row->wholesaleprice.";  STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  


		}


 }














            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	





   public function lookup2(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookup($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/= STOCK:".$row->qty.")",										
										'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.")",										
										 'value' => $row->code.":=".$row->name,  

                                       // 'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	 public function branchlookupmpesa(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];


     $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
	
if($restricttill=="yes"){
	      $query = $this->usermodel->branchlookupmpesaperbranch($keyword,$companyid,$branchid);  
       //$query = $this->usermodel->branchlookupmpesa($keyword,$companyid);  


}else{
       $query = $this->usermodel->branchlookupmpesa($keyword,$companyid);  

}
   
		
		
		
		
		
		
		
		///
		if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,

										'label' => $row->firstname."-".$row->firstname."-".$row->amount."-".$row->code."-".$row->sender_number,										

                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
		
	 public function branchlookupmpesadebts(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->branchlookupmpesa($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->sender_number,
										
										'label' => $row->sender_number."-".$row->amount."-".$row->firstname."-".$row->lastname."-".$row->code,										

                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
    public function wholesalebranchlookup(){  
        $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $viewbuyingprice=$this->usermodel->populatuserpermissionsdataarray('sales','viewbuyingprice',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        //$query = $this->usermodel->branchlookup($keyword,$branchid);  
       		        $query = $this->usermodel->branchlookupddd($keyword,$branchid);  

	   if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
			
			

							
 if( $viewbuyingprice==true){
			
   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name." ".$row->description."(Wh=".$row->wholesaleprice."; SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										

                                        'value' => $row->code.":=".$row->name,  
                                        '' 
                                     );  //Add a row to array  


				
							
	 
		 	
		}else{

   $data['message'][] = array(   
                                        'id'=>$row->code,
										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",		
										'label' => $row->code."-".$row->name." ".$row->description."(Wh=".$row->wholesaleprice."; SP=".$row->sellingprice."; STOCK=".$row->qty.":".$row->store.")",										
										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  


		}
			
			
			
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewwholesales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
    public function wholesalelookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookup($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description."(".$row->wholesaleprice."/=)",										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	public function productlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $dontshowbuyingprice=$this->usermodel->populatuserpermissionsdataarray('products','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('products','dontshowstock',$userid);

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookup($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            { 



if(($dontshowbuyingprice==true) && ($dontshowstock==FALSE)){
	

		 $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : STOCK=".$row->qty.":".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	

	
	
}ELSE if(($dontshowbuyingprice==true) && ($dontshowstock==true)){

		   $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==FALSE)){
	 

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==true)){
	
		

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
	
}




















			
              
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	public function productlookupdispatch(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $dontshowbuyingprice=$this->usermodel->populatuserpermissionsdataarray('products','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('products','dontshowstock',$userid);
$frombranch = $this->input->post('frombranch',TRUE);

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookupdispatch($keyword,$companyid,$frombranch); 
		
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            { 



if(($dontshowbuyingprice==true) && ($dontshowstock==FALSE)){
	

		 $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : STOCK=".$row->qty.":".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	

	
	
}ELSE if(($dontshowbuyingprice==true) && ($dontshowstock==true)){

		   $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==FALSE)){
	 

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==true)){
	
		

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
	
}




















			
              
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	public function productlookupdispatchto(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $dontshowbuyingprice=$this->usermodel->populatuserpermissionsdataarray('products','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('products','dontshowstock',$userid);
$toproduct = $this->input->post('toproduct',TRUE);

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookupdispatch($keyword,$companyid,$toproduct);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            { 



if(($dontshowbuyingprice==true) && ($dontshowstock==FALSE)){
	

		 $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : STOCK=".$row->qty.":".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	

	
	
}ELSE if(($dontshowbuyingprice==true) && ($dontshowstock==true)){

		   $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==FALSE)){
	 

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==true)){
	
		

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
	
}




















			
              
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	public function assetlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->assetlookup($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description."(BP=".$row->buyingprice."; Current value=".$row->assetvalue.":Location= ".$row->store.")",										

										//'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",										
                                        'value' => $row->code,
										 'value' => $row->code.":=".$row->name,  

                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	public function productlistlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   $dontshowbuyingprice=$this->usermodel->populatuserpermissionsdataarray('productlist','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('productlist','dontshowstock',$userid);

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
		//
				        $query = $this->usermodel->branchlookupddd($keyword,$branchid);  

       // $query = $this->usermodel->lookuplist($keyword,$companyid,$branchid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {



if(($dontshowbuyingprice==true) && ($dontshowstock==FALSE)){
	

		 $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : STOCK=".$row->qty.":".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	

	
	
}ELSE if(($dontshowbuyingprice==true) && ($dontshowstock==true)){

		   $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==FALSE)){
	 

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==true)){
	
		

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
	
}








				
             
            }  
        }  
		
		
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	
	
	
	
	
	public function productstocklistlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   $dontshowbuyingprice=$this->usermodel->populatuserpermissionsdataarray('productlist','viewbprice',$userid);
	    $dontshowstock=$this->usermodel->populatuserpermissionsdataarray('productlist','dontshowstock',$userid);

        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
		//
				        $query = $this->usermodel->branchlookupdddStocklist($keyword,$branchid);  

       // $query = $this->usermodel->lookuplist($keyword,$companyid,$branchid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {



if(($dontshowbuyingprice==true) && ($dontshowstock==FALSE)){
	

		 $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : STOCK=".$row->qty.":".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	

	
	
}ELSE if(($dontshowbuyingprice==true) && ($dontshowstock==true)){

		   $data['message'][] = array(   
    'id'=>$row->code,
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==FALSE)){
	 

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice."; STOCK=".$row->qty.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
}ELSE if(($dontshowbuyingprice==false) && ($dontshowstock==true)){
	
		

	  $data['message'][] = array(   
    'id'=>$row->code,
	'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice."; BP=".$row->buyingprice.":".$row->store.")",										
	//'label' => $row->code."-".$row->name."-".$row->description."(SP=".$row->sellingprice." : ".$row->store.")",										
	'value' => $row->code.":=".$row->name,
	); 
	
	
	
	
}








				
             
            }  
        }  
		
		
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewsales',$data); //Load html view of search results  
        }  
    } 
	
	
	
	
	
	public function storeproductlookup(){  
       $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
        $keyword = trim($this->input->post('term'));  
        $data['response'] = 'false'; //Set default response  
        $query = $this->usermodel->lookupstore($keyword,$companyid);  
        if( ! empty($query) )  
        {  
            $data['response'] = 'true'; //Set response  
            $data['message'] = array(); //Create array  
            foreach( $query as $row )  
            {  
                $data['message'][] = array(   
                                        'id'=>$row->code,
										'label' => $row->code."-".$row->name."-".$row->description."(".$row->sellingprice."/=)",										
                                        'value' => $row->code,  
                                        '' 
                                     );  //Add a row to array  
            }  
        }  
        if('IS_AJAX')  
        {  
            echo json_encode($data); //echo json string if ajax request  
        }  
        else 
        {  
            $this->load->view('viewlowstore',$data); //Load html view of search results  
        }  
    } 
		public function viewexpenses()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewexpenses');
				    $wiewinvoices=$this->usermodel->populatuserpermissionsdataarray('incomeexpenses','wiewinvoices',$userid);

			
							
							
				 if( $wiewinvoices==true){
												$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Expense','id >',0);
 
				 }else{
												$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Expense','branchid',$branchid);
 
				 }

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);

 if( $wiewinvoices==true){
 		        $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Expense','id >',0);

				 }else{
					 		        $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Expense','branchid',$branchid);

 
				 }





	//$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','status','active');
       // $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','status','active');


//
         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewexpenses',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	public function viewexpensesbyref()
	{ 
	
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$invoice=$_GET['randomitemidentifier'];
		
		
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewexpenses');
				
							$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','companyid',$companyid,'invoice',$invoice);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        //$data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','companyid',$companyid,'invoice',$invoice);
		$data['viewexpenses']= $this->usermodel->populateall('expenses','invoice',$invoice);


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewexpenses',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	
	
	public function viewpurchasesbyref()
	{ 
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$invoice=$_GET['randomitemidentifier'];
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewpurchases');

			
					$config['total_rows'] = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'invoice',$invoice);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
		 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','companyid',$companyid,'invoice',$invoice);


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewpurchases',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function viewrequest()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewrequest');
				
							$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','userid',$userid,'type',"Request");

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        $data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','userid',$userid,'type',"Request");;


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewrequest',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
		public function viewloan()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewrequest');
				
							$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','userid',$userid,'type',"Advance");

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        $data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','userid',$userid,'type',"Advance");;


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewloan',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	public function viewrequestpending()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewrequestpending');
				
							$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','controller',$userid,'status',"Submitted");

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        $data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','controller',$userid,'status',"Submitted");


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewrequest',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function viewrequestallocation()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/viewrequestallocation');
				
							$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','companyid',$companyid,'status',"Approved");

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        $data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','companyid',$companyid,'status',"Approved");


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewrequest',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	public function paybill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="BILL-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/paybill');
											$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','balance <>',0);


		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','balance <>',0);

         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/paybill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function allpaybill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="BILL-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/allpaybill');
											$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','id > ',0);


		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','id >',0);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allpaybill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	public function receivebill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="BILL-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/addbill');
											$config['total_rows'] = $this->usermodel->count_allwheredata('expenses','companyid',$companyid,'type','Bill');


		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewexpenses"] = $this->usermodel->displayalldata($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill');

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/receivebill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	public function viewallpostedsales()
	{ $session_data = $this->session->userdata('logged_in');

		  $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
			          $this->load->view("template/headerpagemin");

		 
		 
		
		$this->load->view("template/tableheader");
						$data['viewsale']= $this->usermodel->populateall('commission','companyid',$companyid);
						$data['member']= $this->usermodel->populateallarray('people','companyid',$companyid);

	

				$this->load->view('userdata/viewallpostedsales',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function payments()
	{ $session_data = $this->session->userdata('logged_in');

		  $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		 
		 
		 
		 
		 
		 
		 
		
		$this->load->view("template/tableheader");
						$data['viewsale']= $this->usermodel->populateall('commission','userid',$userid);
						$data['member']= $this->usermodel->populateallarray('people','id',$userid);

	

				$this->load->view('userdata/payments',$data);
		$this->load->view("template/footerpage");
	}
	
	
			public function viewdealsfeedback()
	{
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewfeedback']= $this->usermodel->populateall('dealsfeedback','companyid',$companyid);

	

				$this->load->view('userdata/viewdealsfeedback',$data);
		$this->load->view("template/footerpage");
	}
	
	
				public function incompletesales()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['salesreport']= $this->usermodel->populateall('sales_orderraw','companyid',$companyid);

			$data['user']="all";
			$data['group']="all";

				$this->load->view('userdata/viewincompletesales',$data);
		$this->load->view("template/footerpage");
	}
			public function viewbranch()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbranch']= $this->usermodel->populateall('branch','companyid',$companyid);

	

				$this->load->view('userdata/viewbranch',$data);
		$this->load->view("template/footerpage");
	}
	
	
			public function viewroles()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbranch']= $this->usermodel->populateall('roles','companyid',$companyid);

	

				$this->load->view('userdata/viewroles',$data);
		$this->load->view("template/footerpage");
	}
	
			public function viewprojets()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbranch']= $this->usermodel->populateall('projects','companyid',$companyid);

	

				$this->load->view('userdata/viewprojets',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
			public function viewallrequistions()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewbudget']= $this->usermodel->populateall('requisition','companyid',$companyid);

	

				$this->load->view('userdata/viewrequistions',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
			public function viewagentscustomers()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['customer']= $this->usermodel->populateall('customer','companyid',$companyid);

	

				$this->load->view('userdata/viewagentscustomers',$data);
		$this->load->view("template/footerpage");
	}
			public function viewmessage()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewmessage']= $this->usermodel->populateall('message','companyid',$companyid);

	

			$this->load->view('userdata/viewmessage',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
		public function viewcurrency()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewcurrency']= $this->usermodel->populateall('currency','companyid',$companyid);

						$data['allcurrencies']= $this->usermodel->populateall('nation','id > ',0);


			$this->load->view('userdata/viewcurrency',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function allcurrency()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewcurrency']= $this->usermodel->populateall('nation','id >',0);

	

			$this->load->view('userdata/allcurrency',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewetimscodelist()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetimscodelist',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
		
		public function viewetimsnotices()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetimsnotices',$data);
		$this->load->view("template/footerpage");
	}
	
		
	
		
		public function viewetimsbranches()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetimsbranches',$data);
		$this->load->view("template/footerpage");
	}
	
			public function viewetimsinsurance()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetimsinsurance',$data);
		$this->load->view("template/footerpage");
	}
	
		
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
		public function viewetimsitemclassification()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetimsitemclassification',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewetiminitialize()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetiminitialize',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewetims()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetims',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
			public function viewttill()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('tills','companyid',$companyid);

	

			$this->load->view('userdata/viewttill',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
			public function viewtables()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('tables','companyid',$companyid);

	

			$this->load->view('userdata/viewtables',$data);
		$this->load->view("template/footerpage");
	}
	
				public function viewclubs()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('clubs','companyid',$companyid);

	

			$this->load->view('userdata/viewclubs',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
				public function assignclubs()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('assignclubs','companyid',$companyid);

	

			$this->load->view('userdata/assignclubs',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
		public function assignservices()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('assignservices','companyid',$companyid);

	

			$this->load->view('userdata/assignservices',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
			public function viewservices()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['viewtables']= $this->usermodel->populateall('services','companyid',$companyid);

	

			$this->load->view('userdata/viewservices',$data);
		$this->load->view("template/footerpage");
	}
	
	 function fiscalyear()
	{ 
	
	
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['fiscalyear']= $this->usermodel->populateall('fiscalyear','companyid',$companyid);

	

			$this->load->view('userdata/fiscalyear',$data);
		$this->load->view("template/footerpage");
	}
	
	 function glfiscalyear()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['glfiscalyear']= $this->usermodel->populateall('glfiscalyear','companyid',$companyid);

	

			$this->load->view('userdata/glfiscalyear',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	 function customerfiscalyear()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
					$data['customerfiscalyear']= $this->usermodel->populateall('customerfiscalyear','companyid',$companyid);

	

			$this->load->view('userdata/customerfiscalyear',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	public function displayreport()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   $mydate=date('Y-m-d');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/displayreport');
				
				$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales_order','companyid',$companyid,'dateposted',$mydate);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
		
			        $data["startsales"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales_order','companyid',$companyid,'dateposted',$mydate);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/displayreport',$data);
				
		//$this->load->view("template/footerpage");
	
	}
	
	
	
	
			public function startsales()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   $mydate=date('Y-m-d');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/startsales');
						 // $data["total_rows"]=false;

				//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales_order','companyid',$companyid,'dateposted',$mydate);
			$config['total_rowsetims'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'etimsstatus',"3",'id >',0);

			  $data["total_rows"]=$config['total_rowsetims'];
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		  $data["startsales"]=false;
		
			       // $data["startsales"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales_order','companyid',$companyid,'dateposted',$mydate);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		//$data["total_rows"] =false;
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/startsales',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
		public function home()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewcategory'] = $this->usermodel->populatecategory($userid);

				$this->load->view('userdata/home',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
		public function viewnewbusinessrequests()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['viewnewbusinessrequests'] = $this->usermodel->populateall('computers','companyid', $companyid);


				$this->load->view('userdata/viewnewbusinessrequests',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewnewbusinessrequestsetims()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['viewnewbusinessrequests'] = $this->usermodel->populateall('etimsactivations','companyid', $companyid);


				$this->load->view('userdata/viewnewbusinessrequestsetims',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	public function receivesmscodeetims()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	 
	       $randomitemidentifier = $_GET['randomitemidentifier'];
	  $contact = $_GET['contact'];
		  $code = $_GET['code'];

	  $branch = $_GET['branch'];

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
							$this->load->view("template/headerpagemin");

	
$data['randomitemidentifier'] = $randomitemidentifier;
$data['contact'] = $contact;
$data['code'] = $code;
$data['branch'] = $branch;
	
	
				$this->load->view('userdata/smsotpetims',$data);
		$this->load->view("template/footerpage");
	}
	}

	
	
	
	
	
		public function viewcategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewcategory'] = $this->usermodel->populatecategory($companyid);

				$this->load->view('userdata/viewcategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
		public function viewrenewalrequests()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['viewrenewalrequests'] = $this->usermodel->populateall('renewals','companyid', $companyid);


				$this->load->view('userdata/viewrenewalrequests',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewbulkdispatch122()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		//$this->load->view("template/tableheader");
	
	$data['bulkdispatch']= $this->usermodel->populatealldatawhere('bulkdispatch','id','desc','companyid',$companyid);

				$this->load->view('userdata/viewbulkdispatch',$data);
		$this->load->view("template/footerpage");
	}
	
	 
 public function viewbulkdispatch()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $mylastrecord=0;
	
				
				$config['base_url'] = base_url('Systemusers/viewbulkdispatch');
							$config['total_rows'] = $this->usermodel->count_allwhere('bulkdispatch','companyid',$companyid);
		$config['per_page'] = '40';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		        $data["bulkdispatch"] = $this->usermodel->displayall($config["per_page"], $page,'bulkdispatch','companyid',$companyid);

         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewbulkdispatch',$data);
				
	//	$this->load->view("template/footerpage");
	
	}
 
 
 
 	
	
 public function searchalldispatch()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallpayment';
		$config['total_rows'] = $this->usermodel->searchalldispatch_count($searchterm);

		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
				$data['bulkdispatch'] = $this->usermodel->searchalldispatch($searchterm,$limit);

		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewbulkdispatch',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
 
 
 
	
	public function viewmaincategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewproductcategory']= $this->usermodel->populatealldatawhere('maincategory','id','ASC','companyid',$companyid);

				$this->load->view('userdata/viewmaincategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
  public function updatecheckout()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
		         $exactime = date('Y-m-d H:i:s');

 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $idno = $this->input->post("idno");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $comment = $this->input->post("comment");
			  $status = $this->input->post("status");

		     	  $checkoutime = $this->input->post("checkoutime");
			  $checkindate = $this->input->post("date");
		
				
			  		  $this->form_validation->set_rules("idno", "Id Number", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/allattendance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatecheckin') == "checkin")
					   {
						   
						   
		$myfromdate =strtotime(date($checkindate));

					 
		$todate = strtotime(date($checkoutime));
		
			
				$timediffrence= round(( $todate-$myfromdate) / 3600,1);
				
				
							   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			//'userid'=>$userid,
			'timediffrence'=>$timediffrence,
			
		  	'comment'=>$comment,
			 	'checkoutime'=>$checkoutime,
					

			//'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->updatedata($data,'attendance','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the check-out time..</div>');	
							redirect('user/allattendance');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Attendance was not updated. Try again</div>');
								
								 redirect('user/allattendance');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	

	
	
  public function updatemainproductcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
		         $exactime = date('Y-m-d H:i:s');

 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $status = $this->input->post("status");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmaincategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatemaincategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						'status'=>$status,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->updatedata($data,'maincategory','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								$mycustomer=$this->usermodel->populateallarray('people','id', $userid);


			$myname=$mycustomer[0]['firstname'];

		 $actiondone=$myname ." Updated item with id ". $mycategoryid." from  maincategory table at ".$exactime;
								   $mydata = array(
									
									  'userid' => $userid,
									  		'ip' => $this->input->ip_address(),		
																		  	  'companyid' => $companyid,

									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
								 			  	 $this->usermodel->add($mydata,'activityloggs');
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the  main product category..</div>');	
							redirect('user/viewmaincategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> product main Category  was not Updated.. Try again</div>');
								
								 redirect('user/viewmaincategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updateJE()
    {
										$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $credit = $this->input->post("credit");
		  $debit = $this->input->post("debit");    
		    		  $branch = $this->input->post("branch");   
					

		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $balance = $this->input->post("balance");   

		   				  		  $confirm = $this->input->post("confirm");   

				  		  $invoice = $this->input->post("invoice");   
				  		  $journaldate = $this->input->post("journaldate");  
		  		  $myid = $this->input->post("myid");   

  

    $supplier = $this->input->post("supplier");   

    $type = $this->input->post("type");   
  $transactioncode = $this->input->post("transactioncode"); 
				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  
								
								
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    								 redirect($view);

		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_journalentry') == "je")
					   {
									
								
												$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
						'confirm'=>$confirm,

			'balance'=>$balance,

			'crateddate'=>$journaldate,
			'credit' => $credit,		  
		  'debit' => $debit,    
			  'transactioncode' => $transactioncode,   

		  'description' => $description,   
		 'code' => $invoice, 
		 'supplier' => $supplier,   
		 
		 'type' => $type, 
 'branch' => $branch,  		 

			
			    //'companyid' => $companyid,  
				  

				
			
			
			
								);
							
								$usr_result = $this->usermodel->updatedata($data,'debitcredit','id',$myid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the  data..</div>');	
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data was not Updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
	  public function updatebillpayment()
    {
		
			$session_data = $this->session->userdata('logged_in');

   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $payment = $this->input->post("payment");
		 		 $billid = $this->input->post("billid");
		 		 $code = $this->input->post("code");

		   	  $description = $this->input->post("description");
			  		   			   	  $invoice = $this->input->post("invoice");
 
		   	  $paymentmethodes = $this->input->post("bankid");

		    		   	  $bankid = $this->input->post("bankid");

				    		   	  $paiddate = $this->input->post("paiddate");

				
			  		  $this->form_validation->set_rules("payment", "Payment", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/paybill', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_paymybill') == "bill")
					   {
						   
						   
						   
						   
					
						   
						   
						   
						   
						   
						    
	 
						 $currentbalance = $this->usermodel->populateallarray('expenses','id', $billid);

	 $mybalance=$currentbalance[0]['balance'];
$mypayment=$currentbalance[0]['paid'];	

$supplier=$currentbalance[0]['supplier'];
					   
	$myorignalamount=$currentbalance[0]['amount'];						   
						 
						$mystatus=""; 
						
						   
						   						$myfinalbalance= $myorignalamount-($mypayment);

						$finalbalance= $myorignalamount-($mypayment+ $payment);
						$finalpaymant=($mypayment+ $payment);
						   
						    if ($payment>$myfinalbalance)
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Payment was not posted!</strong> The  amount('.$payment.') you are trying to pay is higher than the pending balance('.$myfinalbalance.'). Try again.</div>');

						  
							 redirect('user/paybill');						   
						   return false;
						   }
						   if($finalbalance<=0){
							   
							 	$mystatus="closed"; 
						   }else{
							   $mystatus="active"; 
						   }
						   			$billdata=array(		
			'userid'=>$userid,
			
				'amount'=>$payment,
				'name'=>"bill",
		  	'remarks'=>$description,
			 	'companyid'=>$companyid,
						'invoice'=>$invoice,
						'transactioncode'=>$code,

			'paiddate'=>$dateposted,
					'balance'=>$finalbalance,
								'paymentmethodes'=>$paymentmethodes,

								);
												$updatedata=array(		
			
				'paid'=>$finalpaymant,
			
		 						'supplier'=>$supplier,

			 	
						'status'=>$mystatus,
				'updatedby'=>$userid,
			'companyid'=>$companyid,
			'updatedat'=>$dateposted,
				'balance'=>$finalbalance,
			
								);
							$usr_result = $this->usermodel->add($billdata,'collection');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									
								
								
								
								
								
								 							$usr_result = $this->usermodel->updatedata($updatedata,'expenses','id',$billid);
															
										
													
								
								
															
														
															
$debitdata=array( 'userid'=>$userid,'account'=>2130,'debit'=>$payment,'description'=>$description, 'type'=>"Bills Paid",'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier,'transactioncode'=>$code);


$creditdata=array( 'userid'=>$userid,'account'=>$bankid,'credit'=>$payment,'description'=>$description, 'type'=>"Bills Paid", 'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier,'transactioncode'=>$code);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');				
															
															

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully done the payment for the selected bill..</div>');	
							redirect('user/paybill');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not made. Try again</div>');
								
								 redirect('user/paybill');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
	
	
	
		
 
	  public function editsupplierpayment()
    {
		
			$session_data = $this->session->userdata('logged_in');

   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted =  $this->input->post("paiddate");

		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $payment = $this->input->post("amount");
		   	  $mycode = $this->input->post("transactioncode");

		   	  $description = $this->input->post("remarks");
			  		   			   	  $invoice = $this->input->post("invoice");
 
		   	  $paymentmethodes = $this->input->post("bankid");
			
		    		   	  $billid = $this->input->post("id");

		    		   	  $bankid = $this->input->post("bankid");
		    		   	  $paiddate = $this->input->post("paiddate");

				    		   	  $balance = $this->input->post("balance");

				$finalcustomerbalance=0;
			  		  $this->form_validation->set_rules("id", "Payment details", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewpurchases', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_editpaymentsdone') == "myedit")
					   {
						  
						 	$billdata=array(		
			'userid'=>$userid,
											'name'=>"paid",

				'amount'=>$payment,
			
		  	'remarks'=>$description,
			 	'companyid'=>$companyid,
						'invoice'=>$invoice,
	'transactioncode'=>$mycode,
			'paiddate'=>$dateposted,
					'balance'=>$balance,
								'paymentmethodes'=>$paymentmethodes,
								

								);
						$usr_result = $this->usermodel->updatedata($billdata,'collection','id',$billid);
		
								//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  the payment for the selected supplier..</div>');	
							redirect('user/viewpaidsuppliers?randomitemidentifier='.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not updated. Try again</div>');
								
								 redirect('user/viewpaidsuppliers?randomitemidentifier='.$invoice);
							}
						  
						  
					   }
					   
					   
					   
					   
		}
	
	
	}
	
	
	
	
	
	
	
	
	
 
	  public function editcustomerpayment()
    {
		
			$session_data = $this->session->userdata('logged_in');

   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted =  $this->input->post("paiddate");

		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $payment = $this->input->post("amount");
		   	  $mycode = $this->input->post("transactioncode");

		   	  $description = $this->input->post("remarks");
			  		   			   	  $invoice = $this->input->post("invoice");
 
		   	  $paymentmethodes = $this->input->post("bankid");
			
		    		   	  $billid = $this->input->post("id");

		    		   	  $bankid = $this->input->post("bankid");
		    		   	  $paiddate = $this->input->post("paiddate");
 	  $name = $this->input->post("name");
				    		   	  $balance = $this->input->post("balance");

				$finalcustomerbalance=0;
			  		  $this->form_validation->set_rules("id", "Payment details", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewpurchases', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_editcustomerpayment') == "myedit")
					   {
						  
						 	$billdata=array(		
			'userid'=>$userid,
											

				'amount'=>$payment,
			
		  	'remarks'=>$description,
			 	'companyid'=>$companyid,
						'invoice'=>$invoice,
	'transactioncode'=>$mycode,
			'paiddate'=>$dateposted,
					'balance'=>$balance,
								'paymentmethodes'=>$paymentmethodes,
									'name'=>$name,

								);
						$usr_result = $this->usermodel->updatedata($billdata,'collection','id',$billid);
		
								//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  the payment for the selected supplier..</div>');	
							redirect('user/viewbalance?invoice='.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not updated. Try again</div>');
								
								 redirect('user/viewbalance?invoice='.$invoice);
							}
						  
						  
					   }
					   
					   
					   
					   
		}
	
	
	}
	
	
	
	
	
	
	
	
	
 
	  public function updatesupplierpayment()
    {
		
			$session_data = $this->session->userdata('logged_in');

   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
						 // $dateposted =  $this->input->post("paiddate");
$myfinalbalance=  (float) 0.00;
$payment=  (float) 0.00;

		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $payment = $this->input->post("payment");
		 		 $billid = $this->input->post("billid");
		   	  $mycode = $this->input->post("mycode");
		   	  $tocurrencyamount = $this->input->post("tocurrencyamount");

		   	  $description = $this->input->post("description");
			  		   			   	  $invoice = $this->input->post("invoice");
 
		   	  $paymentmethodes = $this->input->post("bankid");
			

		    		   	  $bankid = $this->input->post("bankid");
		    		   	  $paiddate = $this->input->post("paiddate");
						   $frotime = $this->input->post("frotime");


 $currency = $this->input->post("currency");
$tocurrency = $this->input->post("tocurrency");






						  
	  	   $paiddate=$paiddate." ".$frotime;
		

				    		   	  $paymenttype = $this->input->post("paymenttype");

				$finalcustomerbalance=0;
			  		  $this->form_validation->set_rules("payment", "Payment", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewpurchases', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_paypurchases') == "purchase")
					   {
					if($mycode !=""){
						 $confimcode = $this->usermodel->populateallarray('collection','transactioncode', $mycode);

if($confimcode !=false){
	   	$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Payment  was not posted!</strong> This transaction / Ref No/ Cheque Number has been used.:('.$mycode.'). Try again.</div>');

						  
							redirect('user/viewpurchases');						   
						  return false;
	
}
					}



		  
						 
						   
						    if($paymenttype=="Cancel"){
						   
				
						   
					
						 $currentbalance = $this->usermodel->populateallarray('purchaseorder','id', $billid);

	//$mystatus=$currentbalance[0]['status'];
		$supplier=$currentbalance[0]['supplier'];
	 $mybalance=$currentbalance[0]['balance'];
$mypayment=$currentbalance[0]['paid'];						   
	$myorignalamount=$currentbalance[0]['amount'];	

		$mybranch=$currentbalance[0]['branchid'];
								$amountdata=array(		
												//'amount'=>$finalamount,
													);
								








	
						 
						$mystatus=""; 
						
						   
						   						$myfinalbalance= $myorignalamount+($mypayment);

						$finalbalance= $myorignalamount+($mypayment-$payment);
						$finalpaymant=($mypayment- $payment);
						   
						    if ($payment>$myfinalbalance)
						   {
							   	// $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 // <strong>Payment reversal was not posted!</strong> The  amount('.$payment.') you are trying to cancel is higher than the pending balance('.$myfinalbalance.'). Try again.</div>');

						  
							// redirect('user/viewpurchases');						   
						   //return false;
						   }
						   
						   if($currentbalance[0]['status']=="p.o"){
							   
							   $mystatus=$currentbalance[0]['transactionstatus'];
						   }else{
						   if($finalbalance <=0){
							   
							 	$mystatus="closed"; 
						   }else{
							   $mystatus="active"; 
						   }
						   }

							$billdata=array(		
			'userid'=>$userid,
											'name'=>"paid",
	'branchid'=>$mybranch,
				'amount'=>-$payment,
					  	'supplier'=>$supplier,

		  	'remarks'=>$description,
			 	'companyid'=>$companyid,
						'invoice'=>$invoice,
	'transactioncode'=>$mycode,
			'paiddate'=>$paiddate,
				'createdate'=>$dateposted,
					'balance'=>$finalbalance,
								'paymentmethodes'=>$paymentmethodes,

								);
												$updatedata=array(		
			
				'paid'=>$finalpaymant,
			
		 'paymentmethodes'=>$paymentmethodes,

						//'transactionstatus'=>$mystatus,
				'updatedid'=>$userid,
			'companyid'=>$companyid,
			'updateddate'=>$dateposted,
				'balance'=>$finalbalance,

			
								);
							$usr_result = $this->usermodel->add($billdata,'collection');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 							$usr_result = $this->usermodel->updatedata($updatedata,'purchaseorder','id',$billid);
															
							
															
$debitdata=array( 'userid'=>$userid,'account'=>$bankid,'debit'=>$payment,'description'=>$description,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);


$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$payment,'description'=>$description,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');				
															
															

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Cancelled  the payment for the selected supplier..</div>');	
							redirect('user/viewpurchases');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not Cancelled. Try again</div>');
								
								 redirect('user/viewpurchases');
							}
						   
							}else{

								
						$currencydiffrence=0;
					
					
						 $currentbalance = $this->usermodel->populateallarray('purchaseorder','id', $billid);

	 $mybalance=$currentbalance[0]['balance'];
$mypayment=$currentbalance[0]['paid'];						   
	$myorignalamount=$currentbalance[0]['amount'];
$myorignalamountvat=$currentbalance[0]['vat'];
		 $mybranch=$currentbalance[0]['branchid'];
		
		
	$supplier=$currentbalance[0]['supplier'];
	$people = $this->usermodel->populateallarray('people','id',$supplier);
									$supplierbalance=$people[0]["supplierbalance"];
									$peopleid=$people[0]["id"];
	
	
	
	
	
	


								
					

if($paymenttype=="Payment-Withhold"){
	
	$payment=$this->formatMoney((($payment/100)*$myorignalamountvat), true);

}

				


	
						 
						$mystatus=""; 
						
						$myfinalbalance= (float)$myorignalamount-((float)$mypayment);

						$finalbalance= (float)$myorignalamount-((float)$mypayment+ (float)$payment);
						$finalpaymant=((float)$mypayment+ (float)$payment);
						  
					
						   
						   
						
						   
						   	   
						   if($currentbalance[0]['status']=="p.o"){
							   
							   $mystatus=$currentbalance[0]['transactionstatus'];
						   }else{
						   if($finalbalance<=0){
							   
							 	$mystatus="closed"; 
						   }else{
							   $mystatus="active"; 
						   }
						   }
						   
						   
						   			$billdata=array(		
			'userid'=>$userid,
			
				'amount'=>$payment,
				'transactioncode'=>$mycode,
	'branchid'=>$mybranch,
		  	'remarks'=>$description,
			 	'companyid'=>$companyid,
						'invoice'=>$invoice,
												'supplier'=>$supplier,

								'name'=>"paid",
	'paiddate'=>$paiddate,
				'createdate'=>$dateposted,
			
					'balance'=>$finalbalance,
								'paymentmethodes'=>$paymentmethodes,

								);
												$updatedata=array(		
			
				'paid'=>$finalpaymant,
			
		 
			 	
						//'transactionstatus'=>$mystatus,
				'updatedid'=>$userid,
			'companyid'=>$companyid,
			'updateddate'=>$dateposted,
				'balance'=>$finalbalance,
			
								);
							$usr_result = $this->usermodel->add($billdata,'collection');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
								
									if($finalbalance > 0){
										$finalcustomerbalance=$supplierbalance-$payment;
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
				'lastbalancedate'=>$dateposted,
								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
									}
								
								
								
								
								
								
								
								 $this->usermodel->updatedata($updatedata,'purchaseorder','id',$billid);
															
									
															
$debitdata=array( 'userid'=>$userid,'account'=>2130,'debit'=>$payment,'description'=>$description,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);
$creditdata=array( 'userid'=>$userid,'account'=>$bankid,'credit'=>$payment,'description'=>$description,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);


			
							
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');				
															
							

	if(($tocurrencyamount !=0) && ($tocurrency !="")){
	$mycreditdata1=array( 'userid'=>$userid,'account'=>$bankid,'credit'=>$tocurrencyamount,'description'=>$description,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);

	$usr_result = $this->usermodel->add($mycreditdata1,'debitcredit');

		
		
		
						if($tocurrencyamount > $payment){
						$currencydiffrence=$tocurrencyamount-$payment;	
					$debitdata1=array( 'userid'=>$userid,'account'=>4001,'debit'=>$currencydiffrence,'description'=>$description."-".$tocurrency,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment",'transactioncode'=>$mycode,'supplier'=>$supplier);


			
							
			$this->usermodel->add($debitdata1,'debitcredit');				
									
		

						
						}else{
					$currencydiffrence=$payment-$tocurrencyamount;	
	
		$mycreditdata3=array( 'userid'=>$userid,'account'=>4001,'credit'=>$currencydiffrence,'description'=>$description."-".$tocurrency,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "supplier payment ",'transactioncode'=>$mycode,'supplier'=>$supplier);

	 $this->usermodel->add($mycreditdata3,'debitcredit');

		
	
	
	
						}
						}else{
							

	$usr_result = $this->usermodel->add($creditdata,'debitcredit');
					
							
							
							
						}
					


							

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully done the payment for the selected supplier..</div>');	
							redirect('user/viewpurchases');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not made. Try again</div>');
								
								 redirect('user/viewpurchases');
							}
					   }
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
  public function addmainproductcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmaincategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addmainproductcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'maincategory');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Main Product Category..</div>');	
							redirect('user/viewmaincategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product Main Category was not added.. Try again</div>');
								
								 redirect('user/viewmaincategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
		public function viewmainstockreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $type = $this->input->post("type");
	  $orderamount = $this->input->post("orderamount");

	  	   $branchname = $this->input->post("branchname");

	


				
	
	if($type=="download"){
				  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."MAINTOCK.csv";
        $query = "SELECT code,name,description,qty,	buyingprice,	sellingprice, wholesaleprice	,reorderevel,category,supplier,store as drawer FROM products  order by  category  asc  ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
		      $this->load->view("template/headerpagemin");

		        		$data['branchname']= $branchname;

			        		$data['viewproducts']= $this->usermodel->populatealldatawherestock('products','category','ASC','companyid',$companyid,$orderamount);

	

	
				$this->load->view('userdata/viewmainproductstock',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	

		public function downlodchildprodutcs()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	 
				
	

				  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Production Items Branch". $branchid .".xlsx";
        $query = "SELECT code,uom,qty,	brice,	brice, branch FROM uomproducts  order by  id  asc  ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

	

	
				$this->load->view('userdata/viewproductlist',$data);
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	public function openbranchstock()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");
	  $shift = $this->input->post("shift");

	  $postedtime = $this->input->post("postedtime");

	  $startdate =trim($this->input->post("startdate"));
	  $maincategory =trim($this->input->post("maincategory"));

  $mybranch="";
				
	
		      $this->load->view("template/headerpagemin");

		 if ($this->input->post('openstock') == "open")
					   {
						   
						   				

						//$students = $this->adminusermodel->populatestudentsponsor('gov');
		   //populatealldatanoarraythree($table,$where, $value,$where1, $value1,$where2, $value2)
		   
		   if($branchid=="Main"){
			  				 $myproducts = $this->usermodel->MainstoreStockOpening('products','products.status <>', 'inactive','products.id > ', 0,'products.companyid', $companyid,'maincategory',$maincategory);			   

		   }else{
			   
			   	    if($branchid=="all"){
			  				 $myproducts = $this->usermodel->BranchStockOpening('productlist','productlist.status <>', 'inactive','productlist.branch >', 0,'productlist.companyid', $companyid,'maincategory',$maincategory);			   

				}else{
			  				 $myproducts = $this->usermodel->BranchStockOpening('productlist','productlist.status <>', 'inactive','productlist.branch', $branchid,'productlist.companyid', $companyid,'maincategory',$maincategory);			   
	
				}
			   
			   
 
		   }  
		   
		   

		   
		   
		   $data =array();
if(is_array($myproducts)) {

   foreach($myproducts as $row)
   {



	   if($branchid=="Main"){
  $mybranch="Main";
		   }else{
     $mybranch=trim($row->branch);

		   }  
		   


		   
	   



   $bycode=trim($row->code);
   	   	$confirmstock = $this->usermodel->populatealldatarrayfour('stock','code',$bycode,'branchid',$mybranch,'startdate',$startdate,'shift',$shift);
	
if($confirmstock==FALSE ){
	

$sellingprice=$row->sellingprice;
  $categoryid=$row->category;
   $open=$row->qty;
	$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 
 //$data = array();
 	$data[]=array(		
			'code'=>$bycode,
			'branchid'=>$mybranch,
		  	'startdate'=>$startdate,
		
						'type'=>$maincategoryid,
						'shift'=>$shift,

			'userid'=>$userid,
			'companyid'=>$companyid,
			'open'=>$open,
				'price'=>$sellingprice,
					'postedtime'=>$postedtime,
								);
 //	$usr_result = $this->usermodel->add($data,'stock');
   
	}
}


  //if(is_array($data)) {


//$usr_result =$this->db->insert_batch('stock', $data); 

if(!empty($data)){
   //$usr_result =$this->db->insert_batch('customerfiscalyear', $data); 
$usr_result =$this->db->insert_batch('stock', $data); 

}else{
 $usr_result =false;
 
 
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date and branch.Try again</div>');
								
												redirect('user/viewopeningstock');	
	false;
	
}



        if($this->db->affected_rows() > 0)
	{
		

								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully opened stock..</div>');	
										
													redirect('user/viewopeningstock');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date and branch.Try again</div>');
								
												redirect('user/viewopeningstock');	
	
							}
							
						
							
							
							
							
							
							
} else {
    //echo   "No student";
	
}
						   
						   
					   }else{
						   
						  redirect("user/viewopeningstock") ;
					   }
	
					   
	
	}
	
	
	public function starttakingbranchstock()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");

	  $postedtime = $this->input->post("postedtime");

	  $startdate =trim($this->input->post("startdate"));
	  $orderamount =trim($this->input->post("orderamount"));
	  $producttype =trim($this->input->post("producttype"));
	  $category =trim($this->input->post("category"));
	  $productstatus =trim($this->input->post("productstatus"));


					  $type ="";
			$mybranch =$branchid;
	
		      $this->load->view("template/headerpagemin");

		 if ($this->input->post('startstock') == "start")
					   {
					
 /*
	   if($branchid=="Main Store"){
			   
			   			      	   	$confirmstock = $this->usermodel->populatealldatarraythreestocktaking('stocktaking','code', $bycode,'type', 'Main Store','startdate', $startdate);

		   }else{
			    $mybranch=trim($row->branch);
	
			   			      	   	$confirmstock = $this->usermodel->populatealldatarraythreestocktaking('stocktaking','code', $bycode,'branchid', $mybranch,'startdate', $startdate);


   
		   }
	
	
	

	
if($confirmstock==FALSE ){
	
	}else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again</div>');
								
												redirect('user/viewtocktaking');	
		
	}


*/





					
						   				

						//$students = $this->adminusermodel->populatestudentsponsor('gov');
		   //populatealldatanoarraythree($table,$where, $value,$where1, $value1,$where2, $value2)
		   
		
		   
		   if($branchid=="Main"){
			     $type ="Main";
			   				 $myproducts = $this->usermodel->populatealldatanoarrayfourconfirmProducts('products','status <>', 'inactive','producttype <>', "Service",'companyid', $companyid,'orderamount', $orderamount, $producttype, $category);			   

		   }else{
							 $myproducts = $this->usermodel->populatealldatanoarrayfourconfirmProducts('productlist','status <>', 'inactive','branch', $branchid,'producttype <>', "Service",'orderamount', $orderamount, $producttype, $category);			   
   	     $type ="branch";
		   }
		   
		 
		   
		   
		   
		   
if(is_array($myproducts)) {
$data = array();
$updateArray = array();

   foreach($myproducts as $row)
   {

   $bycode=trim($row->code);
     $categoryid=trim($row->category);
	 $maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 
	


   $open=$row->qty;
	   $myid=$row->id;

 
 	$data[]=array(		
			'code'=>$bycode,
			'branchid'=>$mybranch,
		  	'startdate'=>$startdate,
			'type'=>$type,
			'userid'=>$userid,
			'companyid'=>$companyid,
			'open'=>$open,
				
					'postedtime'=>$postedtime,
										'maincategory'=>$maincategoryid,

								);
 	//$usr_result = $this->usermodel->add($data,'stocktaking');
   	 $updateArray[]=array(	
			'id'=>$myid,
		
			'status'=>$productstatus,
		  

								);	

}

$usr_result =$this->db->insert_batch('stocktaking', $data); 



        if($this->db->affected_rows() > 0)
	{
				if($productstatus=="inactive"){

   
		   if($branchid=="Main"){
			   		$this->db->update_batch('products',$updateArray, 'id');


		   }else{
			   		$this->db->update_batch('productlist',$updateArray, 'id');

		   }
		   

				}					
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully started stock-taking..</div>');	
										
													redirect('user/viewtocktaking');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again</div>');
								
												redirect('user/viewtocktaking');	
	
							
							
							}
} else {
   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There is no inventory stock available for stock tacking.Try again</div>');
								
												redirect('user/viewtocktaking');	
	
							
	
}
						   
						   
					   }else{
						   
						  redirect("user/viewtocktaking") ;
					   }
	
					   
	
	}
	
	
	
	public function closebranchstock()
	{ $session_data = $this->session->userdata('logged_in');
				  $new_date=date("Y-m-d H:i");

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");
	  $maincategory = $this->input->post("maincategory");

	  $postedtime = $this->input->post("postedtime");

	  $startdate =trim($this->input->post("startdate"));
  $closedate =trim($this->input->post("closedate"));
  $type =trim($this->input->post("type"));
$ttaddded=0;
				
	
		      $this->load->view("template/headerpagemin");

		 if ($this->input->post('closestock') == "close")
					   {
						   
						   				
	   
		   if($branchid=="Main"){
				 $myproducts = $this->usermodel->CloseStockOpening('stock','closedate', "",'branchid', "Main",'startdate', $startdate,'maincategory', $maincategory);			   

		   }else{
 
 
			if($branchid=="all"){
				 $myproducts = $this->usermodel->CloseStockOpening('stock','closedate', "",'branchid <>',"Main",'startdate', $startdate,'maincategory', $maincategory);			   

				}else{
				 $myproducts = $this->usermodel->CloseStockOpening('stock','closedate', "",'branchid', $branchid,'startdate', $startdate,'maincategory', $maincategory);			   
	
				}
 
 
 
 
 
		   }  
		   
		   











if(is_array($myproducts)) {

   foreach($myproducts as $row)
   {

   $bycode=trim($row->code);
    $mybranch=trim($row->branchid);
	 $mypostedtime=trim($row->postedtime);
	 	 $myadded=trim($row->added);

	  $mystartdate=trim($row->startdate);
	  $finalstartdate=$mystartdate." ".$mypostedtime;
	  $finalclosetime= $closedate." ".$postedtime;
	  $stockid=$row->id;
	    $price=$row->price;
		   $openstock=$row->open;
		   $mytotal=$row->total;
		     $oldbalance=$row->balance;
			 
//
			 
   	   	$addedstock = $this->usermodel->populatealldatarraythreebydate('newstock','item_id', $bycode,'type', $mybranch,'date', $finalstartdate, $finalclosetime);
 $totaladded=$addedstock[0]['total'];



		$totalsold=0;
 
 	   	   	$soldstock = $this->usermodel->populatealldatarraythreebydatesolditems('sales_order','code', $bycode,'branch', $mybranch,'date', $finalstartdate, $finalclosetime);

  $totalqty=$soldstock[0]['qty'];
		$finalbalance=0;
 $buyingprice=$soldstock[0]['bprice'];

 
if($type=="Manual"){
	
			$ttaddded=$totaladded;
	$finalbalance=$oldbalance;

		$totalsold=(((double)$openstock+$ttaddded)-(double)$row->balance);
//$totalsold=$totalqty;

}else if($type=="BothManual"){
		$finalbalance=$oldbalance;

		$ttaddded=$myadded;
	$totalsold=(((double)$openstock+(double)$ttaddded)-(double)$row->balance);

}else{
$totalsold=$totalqty;

	
	
 
if($totaladded==null){
	
	$ttaddded=0.00;
}else{
	$ttaddded=$totaladded;
}
	


}

//echo $addedstock[0]['stockto'];
//echo "<br>".$addedstock[0]['item_id'];
//echo "<br>".$ttaddded;
//exit;

$myclosingtotal=(double)$openstock+(double)$ttaddded;
$totalamount=(double)$price*(double)$totalsold;
$balance=(double)$myclosingtotal-(double)$totalsold;
	$mymyclosingtotal=(double)$openstock+(double)$ttaddded;

$mybalance=(double)$mymyclosingtotal-(double)$totalsold;
$profit=((double)$price-(double)$buyingprice)*(double)$totalsold;
$profit= $this->MyformatMoney($profit, true);

	$finalbalance=$mybalance;

if(($ttaddded < 0)&& ($addedstock[0]['stockto'] =="Automatic Production adjustment")){
//$ttaddded= (-1* $ttaddded)	;
	
}

 	$updatedata=array(		
		'added'=>$ttaddded,
			'sold'=>$totalsold,
	'updatedby'=>$userid,
	'closedate'=>$finalclosetime,
	'total'=>$myclosingtotal,
	'totalamount'=>$totalamount,
	'balance'=>$finalbalance,
		'bprice'=>$buyingprice,
//'profit'=>$profit,
								);
 	//$usr_result = $this->usermodel->add($data,'stock');
   							$usr_result = $this->usermodel->updatedata($updatedata,'stock','id',$stockid);

	
}
if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully closed the stock..</div>');	
										
													redirect('user/viewopeningstock');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again</div>');
								
												redirect('user/viewopeningstock');	
	
							}
} else {
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>No stock closed since there was no change that ocurred in the stock.Try again</div>');
								
	redirect('user/viewopeningstock');	
	
}
						   
						   
					   }else{
						   
						  redirect("user/viewopeningstock") ;
					   }
	
					   
	
	}
	
	
	
	
		public function openbranchstock1()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");

	  $postedtime = $this->input->post("postedtime");

	  $startdate = $this->input->post("startdate");

				


				
	
		      $this->load->view("template/headerpagemin");

		        		//$data['viewproducts']= $this->usermodel->populateall('products','companyid',$companyid);

			        		$data['viewproducts']= $this->usermodel->populatealldatawhere('productlist','status','ASC','companyid',$companyid);

	

	
				$this->load->view('userdata/viewmainproductstock',$data);
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	public function downloadstocktaking()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");

	  
		  $new_date=date("Y-m-d H:i");		

  $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."StockShit.csv";
		
		
		
		
		
		
		
		
		
		
			



			
	 if($branchid=="Main Store"){
				


      
        $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else if($branchid=="all"){
				


      
        $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate'  and and  stocktaking.type ='branch'  and  stocktaking.companyid='$companyid'  ORDER BY products.category ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
        $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and stocktaking.companyid='$companyid'  and stocktaking.branchid='$branchid'   ORDER BY products.category ASC ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);	
		
		
	}
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	public function downloadstock()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $branchid = $this->input->post("branchid");
	  $closedate = $this->input->post("closedate");
	  $department = $this->input->post("department");

	  
		  $new_date=date("Y-m-d H:i");		

  $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."StockList.csv";
				
	
	
	if(($branchid=="all")&& ($department=="all")){
        $query = "SELECT stock.code,name,open,added,	total,sold,balance,	price,	totalamount	,startdate,closedate FROM stock INNER JOIN products on  stock.code= products.code WHERE closedate ='$closedate' and stock.companyid='$companyid' ORDER BY products.category ASC ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);
	} else if(($branchid=="all")&& ($department!="all")){
        $query = "SELECT stock.code,name,open,added,	total,sold,balance,	price,	totalamount	,startdate,closedate FROM stock INNER JOIN products on  stock.code= products.code WHERE closedate ='$closedate' and stock.companyid='$companyid' and stock.type ='$department' ORDER BY products.category ASC ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);
	}else if(($branchid!="all")&& ($department=="all")){
//$this->db->select(" * from  stock where   date BETWEEN '$fromdate'  and '$todate' and companyid='$companyid'");
        $query = "SELECT stock.code,name,open,added,	total,sold,balance,	price,	totalamount	,startdate,closedate FROM stock INNER JOIN products on  stock.code= products.code WHERE closedate ='$closedate' and stock.companyid='$companyid' and stock.branchid ='$branchid'  ORDER BY products.category ASC ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);
	}else{
        $query = "SELECT stock.code,name,open,added,	total,sold,balance,	price,	totalamount	,startdate,closedate FROM stock INNER JOIN products on  stock.code= products.code WHERE closedate ='$closedate' and stock.companyid='$companyid' and stock.branchid ='$branchid'  and stock.type ='$department'  ORDER BY products.category ASC ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);
}
	
	
	
	
	
	}
	
	
	
	
	
	
		public function viewstockreportbydate()
	{
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $branchname = $this->input->post("branchname");
	  $type = $this->input->post("type");
	  $orderamount = $this->input->post("orderamount");

	  	  $supplier = $this->input->post("supplier");
	  	  $vattype = $this->input->post("vattype");

	  	  $category = $this->input->post("category");
			$producttype = $this->input->post("producttype");
	  	  $maincategory = $this->input->post("maincategory");

 $fromdate = $this->input->post("fromdate");

	  	  $frotime = $this->input->post("frotime");
			$todate = $this->input->post("todate");
	  	  $totime = $this->input->post("totime");


$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;



				
			  $this->load->view("template/headerpagemin");


//

$data['viewproducts']= $this->usermodel->viewproductvaluemain($category,$orderamount,$companyid,$supplier,$branchname,$type,$producttype,$maincategory,$vattype,"all","all");
 $data['branchname']=$branchname;
 $data['page']=1;
 $data['links']=1;
  	$data['branchname']=$branchname;

 	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;



  $data['total_rows']=count((array)$data['viewproducts']);
if($branchname =="Main"){
	
	
	
			$this->load->view('userdata/viewmainproductstockbydate',$data);



}else{
		
	
			$this->load->view('userdata/viewproductstockbydate',$data);



}

		$this->load->view("template/footerpage");	
				
				
				
				
	
	
	}
	
	
	
	
		public function viewstockreport()
	{
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $branchname = $this->input->post("branchname");
	  $type = $this->input->post("type");
	  $orderamount = $this->input->post("orderamount");

	  	  $supplier = $this->input->post("supplier");
	  	  $vattype = $this->input->post("vattype");

	  	  $category = $this->input->post("category");
			$producttype = $this->input->post("producttype");
	  	  $maincategory = $this->input->post("maincategory");
	  	  $limit = $this->input->post("limit");
	  	  $display = $this->input->post("display");
	  	  $is_serialized = $this->input->post("is_serialized");


				
			  $this->load->view("template/headerpagemin");


$data['viewproducts']= $this->usermodel->viewproductvaluemain($category,$orderamount,$companyid,$supplier,$branchname,$type,$producttype,$maincategory,$vattype,$limit,$is_serialized);


//$data['viewproducts']= $this->usermodel->viewproductvaluemain($category,$orderamount,$companyid,$supplier,$branchname,$type,$producttype,$maincategory,$vattype,$limit);
 
 		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

  $data['display']=$display;
 $data['branchname']=$branchname;
 $data['page']=1;
 $data['links']=1;
  $data['total_rows']=count((array)$data['viewproducts']);
if(($branchname=="Mainothers")||($branchname =="Main")){
	if($type=="detailed"){
			$this->load->view('userdata/viewproducts',$data);

	}else if($type=="stock"){
			$this->load->view('userdata/viewproductsstock',$data);

	}else{
			$this->load->view('userdata/viewmainproductstock',$data);

	}

}else{
		if($type=="detailed"){
			
	$this->load->view('userdata/viewproductlist',$data);
	}else if($type=="stock"){
			$this->load->view('userdata/viewproductstockonly',$data);

	
	}else{
			$this->load->view('userdata/viewproductstock',$data);

	}

}

		$this->load->view("template/footerpage");	
				
				
				
				
	
	
	}
	
	
	
	
		public function viewserialkreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $branchname = $this->input->post("branchname");
	  $type = $this->input->post("type");
	 

	  
				


				
	
	if($type=="download"){
				  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."SERIALIZED ITEMS.csv";
		if( $branchname =="all"){
 	$this->db->select("serial,otherserial,code,name,description, qty,	buyingprice,	sellingprice	,status,branch,createdate FROM serials WHERE companyid='$companyid' ");

		}else{
			 	$this->db->select("serial,otherserial,code,name,description, qty,	buyingprice,	sellingprice	,status,branch ,createdate FROM serials WHERE branch='$branchname' and companyid='$companyid' ");

			
		}


	 $this->db->order_by('id','asc');

$bioquery = $this -> db -> get();
if($bioquery->num_rows()>0){

   $data = $this->dbutil->csv_from_result($bioquery, $delimiter, $newline);

        force_download($filename, $data);   


}else{

  return false;
}


     

		
	}else{
		      $this->load->view("template/headerpagemin");

	
	

	
				$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	
	}
	
	
	public function viewsalesmovementreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	 // $totime="23:59:59";
	 
	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $maincategory = $this->input->post("maincategory");
			  	  $category = $this->input->post("category");


		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	$user="NA";
	$data['user']=$user;
	$data['group']="yes";
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="DETAILED DAILY SALES FAST/SLOW MOVING PRODUCTS REPORT";
		$data['salesreport'] = $this->usermodel->viewsalesmovementreport($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname,$category);

						//$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);

		
		
				$this->load->view('userdata/viewsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
		public function getsalesbycategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	 
	  $fromdate = $_GET['fromdate'];

	  $todate = $_GET['todate'];
	  
		  	  $branchname = $_GET['branchid'];
	  $group = $_GET['group'];

	  	  $category = $_GET['category'];
				$this->load->view("template/headerpagemin");


		$this->load->view("template/tableheader");

		

	  
	   $finalfromdate=$fromdate;
	  	 $finaltodate=$todate;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
		  $data['reporttype']="SALES BY CATEGORY  REPORT";

	$allusers="all";
	$user="NA";
	$data['user']=$user;
		$data['group']=$group;
		$data['salesreport'] = $this->usermodel->viewproductsalesbycategory($finalfromdate,$finaltodate,$companyid,$category,$branchname,$group);


		
		
				$this->load->view('userdata/viewsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
			public function viewtotalsalesreportcurrency()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  	  $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");

	  $fromdate = $this->input->post("fromdate");
	  	   $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $download = $this->input->post("download");
	  $currency = $this->input->post("currency");

				$this->load->view("template/headerpagemin");
			  


		$this->load->view("template/tableheader");

		

	  
	   $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
		  $data['reporttype']="TOTAL CURRENCY SALES  REPORT ";

	$allusers="all";
	$user="NA";
	
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['salesreport'] = $this->usermodel->viewtotalsalescurrencyreport($finalfromdate,$finaltodate,$companyid,$branchname,$download,$currency);

		
		
				$this->load->view('userdata/viewtotalsalesreportcurrency',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
			public function viewtotalsalesreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  	  $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");

	  $fromdate = $this->input->post("fromdate");
	  	   $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $download = $this->input->post("download");

				$this->load->view("template/headerpagemin");
			  


		$this->load->view("template/tableheader");

		
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	  
	   $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
		  $data['reporttype']="TOTAL SALES  REPORT";

	$allusers="all";
	$user="NA";
	

		$data['salesreport'] = $this->usermodel->viewtotalsalesreport($finalfromdate,$finaltodate,$companyid,$branchname,$download);

		
		
				$this->load->view('userdata/viewtotalsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewsalesreport()
	{ $session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  	  $frotime = $this->usermodel->allterms_handler($this->input->post("frotime",TRUE),'collections');
	  	  $totime = $this->usermodel->allterms_handler($this->input->post("totime",TRUE),'totime');

	  $fromdate = $this->usermodel->allterms_handler($this->input->post("fromdate"),'fromdate',TRUE);
	  	  $branchname = $this->usermodel->allterms_handler($this->input->post("branchname",TRUE),'branchname');

	  $todate = $this->usermodel->allterms_handler($this->input->post("todate",TRUE),'todate');
	  $type = $this->usermodel->allterms_handler($this->input->post("type",TRUE),'type');
	$this->load->view("template/headerpagemin");
	$maincategory = $this->usermodel->allterms_handler($this->input->post("maincategory",TRUE),"maincategory");
	 $group = $this->usermodel->allterms_handler($this->input->post("group",TRUE),"group");
	$vatype = $this->usermodel->allterms_handler($this->input->post("vatype",TRUE),"vatype");
	$returned = $this->usermodel->allterms_handler($this->input->post("returned",TRUE),"returned");



 
	   $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
		  $data['reporttype']="DETAILED(Item based) DAILY SALES  REPORT";

	$allusers="all";
	$user="NA";
	$data['user']=$user;
		$data['group']=$group;

						//$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);
	$config['base_url'] = base_url('Systemusers/viewsalesreport');
			$config['total_rows'] = $this->usermodel->Countallviewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$allusers,$maincategory,$branchname,$group,$vatype);
		$data['alltotals'] = $this->usermodel->Gettallviewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$allusers,$maincategory,$branchname,$group,$vatype);
		//$this->load->view("template/tableheader");
	//$config['alltotals'] =$config['total_rows'];
	//echo count($data['alltotals'] );
//exit;
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($config["per_page"], $page,$finalfromdate,$finaltodate,$type,$companyid,$allusers,$maincategory,$branchname,$group,$vatype);

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			//$this->load->view('userdata/viewsalesreportmain',$data);
				//	$this->load->view('userdata/viewsalesreport',$data);
if($returned=="yes"){
			$data['salesreturnedreport'] = $this->usermodel->viewsalesreportreturned($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);
	$config['total_rows1']=count((array)$data['salesreturnedreport'] );
	
}else{
				$data['salesreturnedreport'] =false;

		$config['total_rows1']=0;

}
if($group=="yes"){

					$this->load->view('userdata/viewsalesreportmainsummary',$data);

}else{
				$this->load->view('userdata/viewsalesreportmain',$data);

	
}
		
		$this->load->view("template/footerpage");
	}
	
	
			public function viewsmstemplate()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
				$data['viewtemplate'] = $this->usermodel->populateall('smstemplate', 'companyid',$companyid);

		
		
		
		
				$this->load->view('userdata/viewsmstemplate',$data);
		$this->load->view("template/footerpage");
	}
	
  
  public function addsmstemplate()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "SMS Title", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsmstemplate', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsmstemplate') == "smstemplate")
					   {
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'smstemplate');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  SMS Template.</div>');	
							redirect('user/viewsmstemplate');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS Template  was not added.. Try again</div>');
								
								 redirect('user/viewsmstemplate');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
	public function viewalerts()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
			
				
		 

$mytotal_amount = $this->usermodel->countamount($userid);

	$total_amount=$mytotal_amount[0]['totalsms'];			
				
				$config['base_url'] = base_url('Systemusers/viewalerts');

		$config['total_rows'] = $this->usermodel->count_allwhere('alerts','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
			
        $data["viewsms"] = $this->usermodel->displayall($config["per_page"], $page,'alerts','companyid',$companyid);
			$data['total_sms'] = $this->usermodel->countAlerts($userid); 

				
				
         $this->load->view("template/headerpagemin");
		 
				$data['receiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);
				$data['mycategory'] = $this->usermodel->populateall('category', 'companyid',$companyid);

			
		
	//$data['mycategory'] = $this->usermodel->populatecategory($userid);
			
		$data["total_rows"] =$config['total_rows'];
		$data["total_amount"] =$total_amount;
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewalerts',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
  
  
   public function updatealerts()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $groupname = trim($this->input->post("groupname"));

		 		 $contact = trim($this->input->post("contact"));
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $mymessage = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 			 		 		 $deliverystatus = trim($this->input->post("deliverystatus"));

			 		 		 $duedate = trim($this->input->post("duedate"));

							 		 		 $name = trim($this->input->post("name"));

											 		 		 $duetime = trim($this->input->post("duetime"));

															 		 		 $type = trim($this->input->post("type"));

			
			 
		
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewalerts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatsmsalerts') == "sms")

					   {
				$data=array(		
			'userid'=>$userid,
							'groupname'=>$groupname,

				'contact'=>$contact,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
			
						'deliverystatus'=>$deliverystatus,

			'duedate'=>$duedate,
			'duetime'=>$duetime,
			'name'=>$name,
			'type'=>$type,

			
			
			
			
				
			
								);
						   
						   														$usr_result = $this->usermodel->updatedata($data,'alerts','id',$mycategoryid);


																				
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created a new alert ..</div>');	
							redirect('user/viewalerts');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Alert   was not created.. Try again</div>');
								
								 redirect('user/viewalerts');
							}
						   
						   
						   
						   
					   
					   }  
					   else
					   {
							redirect('login');
					   }
					   
					   
		}
		
		}
  
  
  
  
    public function addalert()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $groupname = trim($this->input->post("groupname"));

		 		 $contact = trim($this->input->post("contact"));

		   	  $mymessage = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 		 		 $duedate = trim($this->input->post("duedate"));

							 		 		 $name = trim($this->input->post("name"));

											 		 		 $duetime = trim($this->input->post("duetime"));

															 		 		 $type = trim($this->input->post("type"));

			
			 
		
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewalerts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addalert') == "sms")

					   {
				$data=array(		
			'userid'=>$userid,
							'groupname'=>$groupname,

				'contact'=>$contact,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
			
			
			'duedate'=>$duedate,
			'duetime'=>$duetime,
			'name'=>$name,
			'type'=>$type,

			
			
			
			
				
			
								);
						   
						   
						   	$usr_result = $this->usermodel->add($data,'alerts');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created a new alert ..</div>');	
							redirect('user/viewalerts');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Alert   was not created.. Try again</div>');
								
								 redirect('user/viewalerts');
							}
						   
						   
						   
						   
					   
					   }  
					   else
					   {
							redirect('login');
					   }
					   
					   
		}
		
		}
  
  
  
	
	
 
  public function updateSmstemplate()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 $status = $this->input->post("status");

		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "SMS Title", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsmstemplate', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatesmstemplate') == "smstemplate")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
							'status'=>$status,

			
								);
														$usr_result = $this->usermodel->updatedata($data,'smstemplate','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the sms template..</div>');	
							redirect('user/viewsmstemplate');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> sms template  was not Updated.. Try again</div>');
								
								 redirect('user/viewsmstemplate');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
	
		public function viewsalesreportreturned()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	 // $totime="23:59:59";
	 
	  
	  $user = $this->input->post("user");

	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $maincategory = $this->input->post("maincategory");

  $group = $this->input->post("group");

	
		  		$data['group']=  $group;
		$this->load->view("template/tableheader");
		$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="DETAILED DAILY SALES RETURNED  ITEMS/PRODUCTS REPORT";

		$data['salesreport'] = $this->usermodel->viewsalesreportreturnedNow($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname,$user);

						//$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);
$user="NA";
	$data['user']=$user;
		$data['alltotals'] =0;
			$data['links'] =0;
				$data['total_rows'] =count((array)$data['salesreport']);
				$this->load->view('userdata/viewsalesreportreturned',$data);
		$this->load->view("template/footerpage");
	}
	
		public function viewsalesreportsuspended()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	 // $totime="23:59:59";
	 
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $maincategory = $this->input->post("maincategory");

  $group = $this->input->post("group");

	
		  		$data['group']=  $group;
		$this->load->view("template/tableheader");
		$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	$user="NA";
	$data['user']=$user;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="DETAILED DAILY SALES SUSPENDED  ITEMS/PRODUCTS REPORT";

		$data['salesreport'] = $this->usermodel->viewsalesreportsuspended($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);

						//$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);

		
		
				$this->load->view('userdata/viewsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
		public function viewgroupsalesreport()
	{ $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	 // $totime="23:59:59";
	  // $frotime = $this->input->post("frotime");
	  	  //$totime = $this->input->post("totime");
	 
	 
	  //$fromdate = $this->input->post("fromdate",TRUE);
	 // $todate = $this->input->post("todate",TRUE);
	 // $type = $this->input->post("type",TRUE);
	  //$branch = $this->input->post("branchname",TRUE);
	 // $display = $this->input->post("display",TRUE);
  //$paymentstatus = $this->input->post("paymentstatus",TRUE);
   // $download = $this->input->post("download",);
	
    //$saletypes = $this->input->post("saletypes");

		$group="";

		$totime = trim($this->usermodel->allterms_handler($this->input->get_post('totime', TRUE),'totime'));
				$frotime = trim($this->usermodel->allterms_handler($this->input->get_post('frotime', TRUE),'frotime'));
		
		$fromdate = ($this->usermodel->allterms_handler($this->input->get_post('fromdate', TRUE),'fromdate'));

		$todate = trim($this->usermodel->allterms_handler($this->input->get_post('todate', TRUE),'todate'));
		$type = trim($this->usermodel->allterms_handler($this->input->get_post('type', TRUE),'type'));






		$branch = trim($this->usermodel->allterms_handler($this->input->get_post('branchname', TRUE),'branchname'));
		$mygroup = trim($this->usermodel->allterms_handler($this->input->get_post('group', TRUE),'group'));


		$display = ($this->usermodel->allterms_handler($this->input->get_post('display', TRUE),'display'));
		
			 $paymentstatus = ($this->usermodel->allterms_handler($this->input->get_post('paymentstatus', TRUE),'paymentstatus'));

			$user = trim($this->usermodel->allterms_handler($this->input->get_post('user', TRUE),'user'));

	 
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));
				$saletypes = trim($this->usermodel->allterms_handler($this->input->get_post('saletypes', TRUE),'saletypes'));
				$collections = trim($this->usermodel->allterms_handler($this->input->get_post('collections', TRUE),'collections'));
				$etimsstatus = trim($this->usermodel->allterms_handler($this->input->get_post('etimsstatus', TRUE),'etimsstatus'));

			$group=$mygroup;
		
		
		
		
		
		
		
		
		
		//$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

			
				$config['base_url'] = base_url('Systemusers/viewgroupsalesreport');
		$config['total_rows'] = $this->usermodel->count_allsales("sales",$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$etimsstatus);
			
		
			
			$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";


$this->pagination->initialize($config);
	$data["salesreport"]  = $this->usermodel->viewgroupsalesreport($config["per_page"], $page,$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$etimsstatus);
	$data["alltotals"]  = $this->usermodel->viewgroupsalesreportTOTAL($config["per_page"], $page,$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$etimsstatus);

         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");
		//$data['searchterm'] = $searchterm;
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
$allgroup="";
				        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


if($collections=="yes"){
$allgroup="yes";	
	
}else{
$allgroup=$mygroup;	
	
}

	$data['allcollections'] = $this->usermodel->populatecollectionsales($finalfromdate,$finaltodate,$companyid,"payment",$branch,$allgroup,$download);
			$data['paidpurchase'] = $this->usermodel->populatecollectionbytype($finalfromdate,$finaltodate,$companyid,"paid",$branch,$allgroup,$download);
	
				$data['paidbills'] = $this->usermodel->populatecollectionbytype($finalfromdate,$finaltodate,$companyid,"bill",$branch,$allgroup,$download);



$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="SUMMARY DAILY SALES REPORT";

$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['type']=$type;
	$data['companyid']=$companyid;

	$data['display']=$display;
		$data['group']=$group;
		$data['collections']=$collections;

		$data['branch']=$branch;


		if(($display=="no")||($display=="summary")){
				///	$data['viewexpenses'] = false;

		$data['viewexpenses'] = $this->usermodel->populateexpense($finalfromdate,$finaltodate,$companyid,$branch,$allgroup);
										//$this->load->view('userdata/viewbranch2',$data);
									///	$this->load->view('userdata/viewgroupsalesreportmain',$data);


		if($display=="summary"){
			
					$this->load->view('userdata/viewgroupsalesreportmainsummary',$data);

			
		}else{
		$this->load->view('userdata/viewgroupsalesreportmain',$data);
	
			
		}


		}else{
			
			
					$data['oursales'] = $this->usermodel->getesalesbyproductbydepartment($finalfromdate,$finaltodate,$companyid,$branch);

		
		
		
		//$data['oursales'] = $this->usermodel->getesalesbydepartment($finalfromdate,$finaltodate,$companyid,$branch);
				$data['sales'] = $this->usermodel->getesalesbyproduct($finalfromdate,$finaltodate,$companyid,$branch);

		$data['viewexpenses'] = $this->usermodel->populateexpenseMAIN($finalfromdate,$finaltodate,$companyid,$group);
										$this->load->view('userdata/zreport',$data);

			
		}


				//$this->load->view('userdata/viewgroupreceiptreport',$data);
		$this->load->view("template/footerpage");
	}
	
		
		
		public function viewgroupsalesreportcategory()
	{ $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	 // $totime="23:59:59";
	  // $frotime = $this->input->post("frotime");
	  	  //
		   $mytable = $this->input->post("mytable");

	  $suppliers = explode(':=',$this->input->post("customer"));

 
  $customer = htmlspecialchars(trim($suppliers[0]));
	 
	  //$fromdate = $this->input->post("fromdate",TRUE);
	 // $todate = $this->input->post("todate",TRUE);
	 // $type = $this->input->post("type",TRUE);
	  //$branch = $this->input->post("branchname",TRUE);
	 // $display = $this->input->post("display",TRUE);
  //$paymentstatus = $this->input->post("paymentstatus",TRUE);
   // $download = $this->input->post("download",);
	
    //$saletypes = $this->input->post("saletypes");

		$group="";

		$totime = trim($this->usermodel->allterms_handler($this->input->get_post('totime', TRUE),'totime'));
				$frotime = trim($this->usermodel->allterms_handler($this->input->get_post('frotime', TRUE),'frotime'));
		
		$fromdate = ($this->usermodel->allterms_handler($this->input->get_post('fromdate', TRUE),'fromdate'));

		$todate = trim($this->usermodel->allterms_handler($this->input->get_post('todate', TRUE),'todate'));
		$type = trim($this->usermodel->allterms_handler($this->input->get_post('type', TRUE),'type'));
	//	$mytable = trim($this->usermodel->allterms_handler($this->input->get_post('mytable', TRUE),'mytable'));






		$branch = trim($this->usermodel->allterms_handler($this->input->get_post('branchname', TRUE),'branchname'));
		$mygroup = trim($this->usermodel->allterms_handler($this->input->get_post('group', TRUE),'group'));


		$display = ($this->usermodel->allterms_handler($this->input->get_post('display', TRUE),'display'));
		
			 $paymentstatus = ($this->usermodel->allterms_handler($this->input->get_post('paymentstatus', TRUE),'paymentstatus'));

			$user = trim($this->usermodel->allterms_handler($this->input->get_post('user', TRUE),'user'));

	 
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));
				$saletypes = trim($this->usermodel->allterms_handler($this->input->get_post('saletypes', TRUE),'saletypes'));
				$collections = trim($this->usermodel->allterms_handler($this->input->get_post('collections', TRUE),'collections'));

			$group=$mygroup;
		
		
		
		
		
		
		
		
		
		//$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

			
		$config['base_url'] = base_url('Systemusers/viewgroupsalesreport');
		$config['total_rows'] = $this->usermodel->count_allsalesCategory("sales",$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$mytable,$customer);
			
		
			
			$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";


$this->pagination->initialize($config);
	$data["salesreport"]  = $this->usermodel->viewgroupsalesreportCategory($config["per_page"], $page,$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$mytable,$customer,$display);
	$data["alltotals"]  = $this->usermodel->viewgroupsalesreportTOTALCATEGORY($config["per_page"], $page,$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user,$mytable,$customer);


         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");
		//$data['searchterm'] = $searchterm;
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
$allgroup="";
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

					$data['report']="yes";

if($collections=="yes"){
$allgroup="yes";	
	
}else{
$allgroup=$mygroup;	
	
}

	$data['allcollections'] = false;
	
			$data['paidpurchase'] = false;
	
				$data['paidbills'] =false;




$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="SUMMARY DAILY SALES REPORT";

$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['type']=$type;
	$data['companyid']=$companyid;
	$data['user']=$user;

	$data['display']=$display;
		$data['group']=$group;
		$data['collections']=$collections;

		$data['branch']=$branch;


		
					$data['viewexpenses'] = false;

		//$data['viewexpenses'] = $this->usermodel->populateexpense($finalfromdate,$finaltodate,$companyid,$branch,$allgroup);
										//$this->load->view('userdata/viewbranch2',$data);
if($display=="summary"){
			$this->load->view('userdata/dailysalessummary',$data);

}else{
											$this->load->view('userdata/viewgroupreceiptreportcategory',$data);

}
		


				//$this->load->view('userdata/viewgroupreceiptreport',$data);
		$this->load->view("template/footerpage");
	}
	
		
		
		
		
		
		
		public function collections()
	{ $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


		$allgroup="";

		$totime = trim($this->usermodel->allterms_handler($this->input->get_post('totime', TRUE),'totime'));
				$frotime = trim($this->usermodel->allterms_handler($this->input->get_post('frotime', TRUE),'frotime'));
		
		$fromdate = ($this->usermodel->allterms_handler($this->input->get_post('fromdate', TRUE),'fromdate'));

		$todate = trim($this->usermodel->allterms_handler($this->input->get_post('todate', TRUE),'todate'));
		$category = trim($this->usermodel->allterms_handler($this->input->get_post('category', TRUE),'type'));

		$branch = trim($this->usermodel->allterms_handler($this->input->get_post('branchname', TRUE),'branchname'));
		$mygroup = trim($this->usermodel->allterms_handler($this->input->get_post('group', TRUE),'group'));


		


	 
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));

			$allgroup=$mygroup;
		
		
		
		
		
						$this->load->view("template/headerpagemin");

		
		
		//$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	if($category =="payment"){
				$data['allcollections'] = $this->usermodel->populatecollectionbytype($finalfromdate,$finaltodate,$companyid,"payment",$branch,$allgroup,$download);

		$data['reporttype']="PAYMENTS RECEIVED ";

	} else if ($category =="paid"){
					$data['allcollections'] = $this->usermodel->populatecollectionbytype($finalfromdate,$finaltodate,$companyid,"paid",$branch,$allgroup,$download);

				$data['reporttype']="PURCHASES PAID ";
	}	if($category =="bill"){
						$data['allcollections'] = $this->usermodel->populatecollectionbytype($finalfromdate,$finaltodate,$companyid,"bill",$branch,$allgroup,$download);

		$data['reporttype']="BILLS PAID ";
	}
	
	



/*


		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

				$config['base_url'] = base_url('Systemusers/viewgroupsalesreport');
		$config['total_rows'] = $this->usermodel->count_allsales("sales",$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user);
			
		
			
			$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";


$this->pagination->initialize($config);


         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");
		//$data['searchterm'] = $searchterm;
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
$allgroup="yes";

*/
	

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;

$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['category']=$category;
	$data['companyid']=$companyid;

		$data['group']=$allgroup;

		$data['branch']=$branch;




			$this->load->view('userdata/viewcollections',$data);
		$this->load->view("template/footerpage");
	}
	
		
		
		
		
		
		
		public function viewvatreport()
	{ 
	
	$session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	  //$totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  	  $vatrate = $this->input->post("vatrate");

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $category = $this->input->post("category");
	  $branch = $this->input->post("branchname");
 

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	//$data['type']=$type;
	$data['companyid']=$companyid;
	
				        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
	

	

	
				$data['EXEMPTED'] = $this->usermodel->getvatsales($finalfromdate,$finaltodate,$companyid,$branch,"EXEMPTED",$vatrate);
				$data['VATABLE'] = $this->usermodel->getvatsales($finalfromdate,$finaltodate,$companyid,$branch,"VATABLE",$vatrate);
				$data['ZERORATED'] = $this->usermodel->getvatsales($finalfromdate,$finaltodate,$companyid,$branch,"ZERO RATED",$vatrate);

								$data['VATABLEpurchases'] = $this->usermodel->getallvatpurchases($finalfromdate,$finaltodate,$companyid,$branch,$vatrate);


								$data['VATABLEexpenses'] = $this->usermodel->getallvatexpenses($finalfromdate,$finaltodate,$companyid,$branch,$vatrate);


		
		
			$this->load->view('userdata/vatreport',$data);
		$this->load->view("template/footerpage");
	}
	
		
		
		public function viewmoneyreceived()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $download = $this->input->post("download");


	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $view = $this->input->post("view");
	  $status = $this->input->post("status");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		//$frotime="00:00:00";
				//	$totime="23:59:59";
	  
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  	  	  $branchname = $this->input->post("branchname");

		  
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

	$data['finalfromdate']=$finalfromdate;
		$data['view']=$view;

	$data['finaltodate']=$finaltodate;
	
	$data['companyid']=$companyid;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="DETAILED MONEY RECEIVED REPORT";

			
		
				$data['mpesareport'] = $this->usermodel->getesalesbympesa($finalfromdate,$finaltodate,$status,$branchname,$download);



			$this->load->view('userdata/viewmoneyreceived',$data);
		$this->load->view("template/footerpage");
	}
		
		
		
		
			public function viewgroupsalesreportvat()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  $branchname = $this->input->post("branchname");
	  $display = $this->input->post("display");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['type']=$type;
	$data['companyid']=$companyid;
	
			$data['salesreport'] = $this->usermodel->viewgroupsalesreport($finalfromdate,$finaltodate,$type,$companyid,$branchname);
		$data['oursales'] = $this->usermodel->getesalesbydepartment($finalfromdate,$finaltodate,$companyid,$branchname);
				$data['sales'] = $this->usermodel->getesalesbyproduct($finalfromdate,$finaltodate,$companyid,$branchname);


		$data['viewexpenses'] = $this->usermodel->populateexpense($finalfromdate,$finaltodate,$companyid);

		if($display=="no"){
							$this->load->view('userdata/viewgroupsalesreportvat',$data);

			
		}else{
										$this->load->view('userdata/zreportvat',$data);

			
		}

				//$this->load->view('userdata/viewgroupsalesreportvat',$data);
		//$this->load->view("template/footerpage");
	}
	
		
		
		
		
		
		
		
		public function viewsalary()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $salaryyear = $this->input->post("salaryyear");
	  $slarymonth = $this->input->post("slarymonth");
		  $branchid = $this->input->post("branchid");
	  	  $category = $this->input->post("category");

	  	  $download = $this->input->post("download");
	  	  $bankname = $this->input->post("bankname");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	
	
		
		$data['salaryyear']=$salaryyear;
				$data['slarymonth']=$slarymonth;

		
	
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewemployee'] = $this->usermodel->viewsalary($slarymonth,$salaryyear,$companyid,$branchid,$download,$category,$bankname);
		//var_dump($data['salesreport']);
		//exit;
				$this->load->view('userdata/salaryhistory',$data);

		$this->load->view("template/footerpage");
		
	}
	
	
		
		public function getp9salary()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $category = $this->input->post("category");
  $salaryyear = $this->input->post("salaryyear");
	  $branchid = $this->input->post("branchid");
	  $user = $this->input->post("user");
	

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

			$data['user']=$user;

		$data['salaryyear']=$salaryyear;

		
	
				        		$data['people'] = $this->usermodel->populateallarray('people','id',$user);

			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

							
		
		if($category=="P9"){
					$data['viewemployee'] = $this->usermodel->viewsalaryp9($user,$salaryyear,$companyid,$branchid);

							$this->load->view('userdata/getp9salary',$data);

		}else{
					$data['viewemployee'] = $this->usermodel->viewsalarystatement($user,$salaryyear,$companyid,$branchid);

							$this->load->view('userdata/getpsalarystatement',$data);

			
		}
		

		$this->load->view("template/footerpage");
		
	}
	public function viewtaskassigned()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $year = $this->input->post("year");
	  $user = $this->input->post("user");
	
	  	  $period = $this->input->post("period");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	
	
		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['assigntask'] = $this->usermodel->viewtaskassignedreport($user,$year,$period,$companyid);
		$data['links']=1;
				$data['total_rows']=count((array)$data['assigntask']);

		//exit;
				$this->load->view('userdata/assigntask',$data);

		$this->load->view("template/footerpage");
		
	}
	
	
	
			public function assignedtasknow()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $exactdate = $this->input->post("exactdate");
	  $user = $this->input->post("user");
		  $period = $this->input->post("period");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	
	$data['mytask']  = $this->usermodel->populatealldatanoarraythreetask('assigntask', 'companyid',$companyid,'defaulttype','yes','employeeid',$user,$period);

		$data['user']=$user;
			$data['exactdate']=$exactdate;
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']=1;
				$data['total_rows']=count((array)$data['mytask']);

		//exit;
				$this->load->view('userdata/assignedtasknow',$data);

		$this->load->view("template/footerpage");
		
	}
	
	
	
		public function createnewpaymentgl()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 //$userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	 $data['branchid'] = $session_data['branchid'];
	 $mybranchid = $data['branchid'];
	 
	 
	  $invoice = $this->input->post("invoice");

	  $itemid = $this->input->post("itemid");
  $category = $this->input->post("category");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

					        		$collections= $this->usermodel->populateallarray('collection','id',$itemid);


					$paiddate=$collections[0]['paiddate'];
					$myinvoice=$collections[0]['invoice'];

					$amount=$collections[0]['amount'];
					$remarks=$collections[0]['remarks'];

					$userid=$collections[0]['userid'];

					$companyid=$collections[0]['companyid'];

					$bankname=$collections[0]['paymentmethodes'];
$type=$collections[0]['name'];


					$transactioncode=$collections[0]['transactioncode'];

	if($category=="payment"){
									$viewsales = $this->usermodel->populateallarray('sales', 'invoice',$invoice);
								
									     $mycustomer=$viewsales[0]['customer'];
										 $branchid=$viewsales[0]['branch'];
										 
										 
	}else{
		
		$viewsales = $this->usermodel->populateallarray('purchaseorder', 'invoice',$invoice);
								
									     $mycustomer=$viewsales[0]['supplier'];
										 $branchid=$viewsales[0]['branchid'];
		
		
		
	}
	








	if($category=="payment"){
								
								 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=>"payment",'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


$creditdata=array( 'userid'=>$userid,'account'=>1100,'credit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');

										 
	}else{

								 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'credit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=>"payment",'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


$creditdata=array( 'userid'=>$userid,'account'=>2130,'debit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');

		
		
	}
	














	 




	if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully passed new Updated GL on this payment.</div>');	
						redirect('user/viewbalance?invoice='.$invoice);	
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> A New GL was not passed. Try again</div>');
								
						redirect('user/viewbalance?invoice='.$invoice);	
							}	
							




		
	}
	
	
	
	
	
	
	
	
	
	
	
	
		
	public function viewtaskreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $fromdate = $this->input->post("fromdate");

	  $todate = $this->input->post("todate");
	  $user = $this->input->post("user");
		  	  $branchid = $this->input->post("branchid");
	  $type = $this->input->post("type");
	  	  $tasktype = $this->input->post("tasktype");

	  	  $period = $this->input->post("period");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

		

					$data['fromdate']=$fromdate;
			$data['todate']=$todate;
			$data['type']=$type;

			$data['period']=$period;
			
			$data['branchid']=$branchid;
			$data['user']=$user;
			$data['companyid']=$companyid;
			
			
			
			
			
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['dailytasks'] = $this->usermodel->viewtaskperformance($user,$fromdate,$todate,$period,$branchid,$companyid,$type,$tasktype);
		$data['links']=1;
				$data['total_rows']=count((array)$data['dailytasks']);

		//exit;
		if($type=="performance"){
				$this->load->view('userdata/viewtaskreport',$data);
	}else{
						$this->load->view('userdata/viewmydailyupdates',$data);

	}

		$this->load->view("template/footerpage");
		
	}
	
	
	public function viewmytaskreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 

	  $fromdate = $_GET['fromdate'];

	  $todate = $_GET['todate'];
	  $user = $_GET['user'];
		  	  $branchid = $_GET['branchid'];
	  $type = $_GET['type'];

	  	  $period = $_GET['period'];

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

		

					$data['fromdate']=$fromdate;
			$data['todate']=$todate;
			$data['type']=$type;

			$data['period']=$period;
			
			$data['branchid']=$branchid;
			$data['user']=$user;
			$data['companyid']=$companyid;
			
			
			
			
			
	
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['dailytasks'] = $this->usermodel->viewtaskperformance($user,$fromdate,$todate,$period,$branchid,$companyid,$type);
		$data['links']=1;
				$data['total_rows']=count((array)$data['dailytasks']);

		//exit;
		if($type=="performance"){
				$this->load->view('userdata/viewtaskreport',$data);
	}else{
						$this->load->view('userdata/viewmydailyupdates',$data);

	}

		$this->load->view("template/footerpage");
		
	}
	
	
		
		
	public function viewbudgetreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $byear = $this->input->post("byear");
	  $bmonth = $this->input->post("bmonth");
	
	  	  $download = $this->input->post("download");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	
	if($download=="yes"){
		
		
		
		
		  $new_date=date("Y-m-d H:i");		

		$delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Budget report.csv";
		
		   
if(($bmonth=="all")) {
  $query = "SELECT * from  budget where   month ='$bmonth' and year ='$salaryyear'  and companyid='$companyid'  ";
	

	}else{
  $query = "SELECT * from  budget where    year ='$byear'  and companyid='$companyid'  ";


}
		


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
		
		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewbudget'] = $this->usermodel->viewbudgetreport($bmonth,$byear,$companyid);
		$data['links']=1;
				$data['total_rows']=count((array)$data['viewbudget']);

		//exit;
				$this->load->view('userdata/viewbudget',$data);

		$this->load->view("template/footerpage");
		}
	}
	
	
		
		
	public function viewprojectbudgetreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $projectid = $this->input->post("projectid");
		  	  $code = $this->input->post("code");

	  	  $download = $this->input->post("download");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	
		$data['projectid']=$projectid;
		
		$projectname="";
		if($projectid!="all"){
			
			        		$myprojects= $this->usermodel->populateallarray('projects','id',$projectid);
$name=$myprojects[0]["name"];
				$projectname="Budget Report for ".$name;
		}else{
			
		
				$projectname="Budget Report for all the projects";
		}
								
				$data['projectname']=$projectname;			
		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewbudget'] = $this->usermodel->viewprojectbudgetreport($code,$projectid,$download,$companyid);
		$data['links']=1;
				$data['total_rows']=count((array)$data['viewbudget']);

		//exit;
				$this->load->view('userdata/viewmybudgetreport',$data);

		$this->load->view("template/footerpage");
		
	}
	
	
	public function viewdeductions()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $salaryyear = $this->input->post("salaryyear");
	  $slarymonth = $this->input->post("slarymonth");
  $branchid = $this->input->post("branchid");
	  	  $code = $this->input->post("code");
	  	  $download = $this->input->post("download");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['download'] =  $download;

		$data['salaryyear'] =  $salaryyear;
				$data['slarymonth'] =  $slarymonth;
						$data['code'] =  $code;
			        		$getaccountname = $this->usermodel->populateallarray('salarycharges','code',$code);
						$chargename=  $getaccountname[0]["name"];
						$data['chargename'] =  $chargename;
$category=  $getaccountname[0]["category"];
						$data['category'] =  $category;

	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewemployee'] = $this->usermodel->viewalldeductions($slarymonth,$salaryyear,$companyid,$code,$branchid,$download,$chargename);
		//var_dump($data['salesreport']);
		//exit;
		

		if($chargename=="NHIF"){
			
$this->load->view('userdata/nhif',$data);

			
		}else if($chargename=="NSSF"){
$this->load->view('userdata/nssf',$data);

			
		} else if($chargename=="PAYE"){
			
$this->load->view('userdata/allpaye',$data);

			
		}else{
			
							$this->load->view('userdata/deductionhistory',$data);

		}
		
		
		
		
		
		
		
		

		$this->load->view("template/footerpage");
		}
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		public function viewagingreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  
	  	  	  $reporttype = $this->input->post("reporttype");

	  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
				 
		$duration = $this->input->post("duration");
	 		$group = $this->input->post("group");

						$branchname = $this->input->post("branchname");
 
				 
	  
	  
	  
	  
	  
	   $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");

	  	  $download = $this->input->post("download");

	
		
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	 $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  
	   		 $currentdate = date('Y-m-d H:i:s');

if($reporttype!="all"){
	
$myfromdate=date('Y-m-d', strtotime($fromdate. ' - '.$duration.' days'));
	  
 $fromdate=$myfromdate." ".$totime;
	  $todate=$todate." ".$totime;


}else{
	
	  $fromdate=$fromdate." ".$frotime;
	  $todate=$todate." ".$totime;
	
}
	
// Add days to date and display it

	  
	  
	  
	  
	  

		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['salesreport'] = $this->usermodel->viewagingreport($fromdate,$todate,$companyid,$supplier,$reporttype,$duration,$branchname,$download,$group);
		//var_dump($data['salesreport']);
		//exit;
		
		if($reporttype!="all"){
				$finalfromdate=$fromdate;
	  	  $finaltodate=$todate;
	$user="NA";
	$data['user']=$user;
	$data['group']="yes";
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']=" </br>AGING SALES  REPORT FOR ALL CUSTOMERS ";
	
	
	$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


							$this->load->view('userdata/allinvoicesaging',$data);

			}else{
				
				$this->load->view('userdata/allinvoices',$data);

			}


		$this->load->view("template/footerpage");
		
	}
	
	
		
		
		
		
		
		
		
		
		
		
	public function viewinvoicereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
  	  $pending = $this->input->post("pending");
	  	  $salestype = $this->input->post("salestype");
	  
	  	  	  $PAYMENTDATE = $this->input->post("PAYMENTDATE");

	  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
				 
				  	  $searchtype = $this->input->post("searchtype");
	 
				 
				 
	  
	  
	  
	  
	  
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $vattype = $this->input->post("vattype");
	  	  $download = $this->input->post("download");
	  	  $bankname = $this->input->post("bankname");
	  	  $paymentmethodes = $this->input->post("paymentmethodes");
		  
		  
		  
		  	  $originalamount = $this->input->post("originalamount");
	  	  $transactioncode = $this->input->post("transactioncode");
		  
		  	$data['PAYMENTDATE'] =$PAYMENTDATE;
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
			  $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
					
   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;
		 	
		
  // $finalfromdate=$fromdate." ".$frotime;
	  //	 $finaltodate=$todate." ".$totime;
		 
	
	
	if($download=="yes"){
		
		
		
		
		  $new_date=date("Y-m-d H:i");		

		$delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Invoice.csv";
		
		   
if(($supplier=="all")) {
  $query = "SELECT * from  sales where   dateposted BETWEEN '$fromdate'  and '$todate' and companyid='$companyid'  and type='Invoice'";
	

	}else{
		  $query = "SELECT * from  sales where   dateposted BETWEEN '$fromdate'  and '$todate' and companyid='$companyid'  and type='Invoice' and customer='$supplier'";


}
		


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else if($download=="bulk"){
	
		$data['salesreport'] = $this->usermodel->viewinvoicereport($fromdate,$todate,$companyid,$supplier,$salestype,$pending,$searchtype,$download);
	$data['paymentmethodes']=$paymentmethodes;
	$entermpesacode=$this->usermodel->populatuserpermissionsdataarray('sales','entermpesacode',$userid);

	$data['bankname']=$bankname;
	//
	
		$data['originalamount']=$originalamount;

	$data['transactioncode']=$transactioncode;
	
	
	
	
			if(($supplier=="all") || ($salestype=="all") || ($pending=="all") || ($paymentmethodes=="") ){
			
				
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Transaction failed! You have not selected specific items . Makes sure you select all the required details then try again</div>');
								
								 redirect('user/allinvoices');
								 
								 return false;
			
			
		}
		
		
		if($paymentmethodes=="mpesa"){
			
			if($entermpesacode !=true){
	
	
	

				$mpesaresult = $this->usermodel->populateallarray('sms_in','code', $transactioncode);


if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
$myamount=$mpesaresult[0]['amount'];
					
					$data['originalamount']=$myamount;
		
					
					}else{
					
					$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That code does not exist.Try again</div>');
								
								 redirect('user/allinvoices');
								
								return false;
					
					
					}
			
		}
			}
			
			
			
			
			

		
		
		
	
					$this->load->view('userdata/bulkinvoicepayment',$data);

	}else{
		
		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['salesreport'] = $this->usermodel->viewinvoicereport($fromdate,$todate,$companyid,$supplier,$salestype,$pending,$searchtype,$download);
		//var_dump($data['salesreport']);
		//exit;
				$this->load->view('userdata/allinvoices',$data);

		$this->load->view("template/footerpage");
		}
	}
	
	
	
	
	
	
		public function viewexpenseitems()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	//  $supplier = $this->input->post("supplier");
	  
	  
	  
	  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
	  
	  
	  
	  
	  
	  	  $user = $this->input->post("user");

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $department = $this->input->post("department");

		  
		  	  
	  $mycode = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($mycode[0]));
	  
		  
		  			
 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  					  
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		  
		  
		  
		  
		  
		  
	  	  $download = $this->input->post("download");
	  	  $daterange = $this->input->post("daterange");
	  	  $itemtype = $this->input->post("itemtype");
		  	  $grouping = $this->input->post("grouping");

		  	  $branchid = $this->input->post("branchid");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

		$data['fromdate']=$fromdate;
			$data['todate']=$todate;
				$data['mybranchid']=$branchid;
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
				$data['viewexpense'] = $this->usermodel->viewitemexpensereport($fromdate,$todate,$companyid,$supplier,$itemtype,$daterange,$code,$grouping,$branchid,$department,$user);

		
		
		
		
				$this->load->view('userdata/viewexpenseitems',$data);
	

		
			        	
		$this->load->view("template/footerpage");
		
		
		}
	
	
	
	
	
	
	
   public function printsuppliercreditnote() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		
// $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);





		  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("newstock","companyid",$companyid,"itemstatus","returned","invoice_number",$invoiceid);













          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printsuppliercreditnote', $data);
		
	}
  }
  
  
	
	
	
	
	
	
	
	
	
   public function printsuppliercreditnotediscount() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		
// $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);





		  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("newstock","companyid",$companyid,"discount > ",0,"invoice_number",$invoiceid);













          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printsuppliercreditnotediscount', $data);
		
	}
  }
  
  
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function searchquotaion()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

	  
	  
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $status = $this->input->post("status");

	
		  	  $branchname = $this->input->post("branchname");

		  
		  		  	  $department = $this->input->post("department");

		  
		  
		  
		  
	  	  $preparedby = $this->input->post("preparedby");
	 

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

		$data['fromdate']=$fromdate;
			$data['todate']=$todate;
			
			$data['total_rows']=1;
				$data['links']="";
				
				
				$data['total_rows']=$branchid;
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
				$data['viewpurchases'] = $this->usermodel->searchquotaion($fromdate,$todate,$companyid,$preparedby,$branchname, $type,$status,$department);

		$data['total_rows']=count((array)$data['viewpurchases']);
		
		
		
				$this->load->view('userdata/allquatation',$data);
	

		
			        	
		$this->load->view("template/footerpage");
		
		
		}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewitembasedpurchasereport()
	{ 
	
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	//  $supplier = $this->input->post("supplier");
	  
	  
	  
	  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
	  
	  
	  
	  	  $batchno = $this->input->post("batchno");

	  
	  
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $code = $this->input->post("code");
	  	  $download = $this->input->post("download");
	  	  $daterange = $this->input->post("daterange");
	  	  $itemtype = $this->input->post("itemtype");
		  	  $grouping = $this->input->post("grouping");
		  	  $category = $this->input->post("category");
		  	  $branchname = $this->input->post("branchname");
		  	  $reporttype = $this->input->post("reporttype");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	  $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
		
   $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;
	

	
		$data['fromdate']=$fromdate;
				$data['todate']=$todate;
				$data['grouping']=$grouping;
				$data['supplier']=$supplier;

			
				$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewreceivings'] = $this->usermodel->viewitembasedpurchasereport($finalfromdate,$finaltodate,$companyid,$supplier,$itemtype,$daterange,$code,$grouping,$category,$branchname,$download,$reporttype,$batchno);
		

if($grouping=="yes"){
					$this->load->view('userdata/purchasereportgroup',$data);

}else{
				$this->load->view('userdata/purchasereport',$data);
	
}
		
			        	
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	public function viewitembasedpurchasereport2222222()
	{ 
	
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	//  $supplier = $this->input->post("supplier");
	  
	  
	  
	  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
	  
	  
	  
	  
	  
	  
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $code = $this->input->post("code");
	  	  $download = $this->input->post("download");
	  	  $daterange = $this->input->post("daterange");
	  	  $itemtype = $this->input->post("itemtype");
		  	  $grouping = $this->input->post("grouping");
		  	  $category = $this->input->post("category");
		  	  $branchname = $this->input->post("branchname");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	  $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
		
   $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;
	

	
		$data['fromdate']=$fromdate;
				$data['todate']=$todate;
				$data['grouping']=$grouping;
				$data['supplier']=$supplier;

			
				$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewreceivings'] = $this->usermodel->viewitembasedpurchasereport($finalfromdate,$finaltodate,$companyid,$supplier,$itemtype,$daterange,$code,$grouping,$category,$branchname,$download);
		

if($grouping=="yes"){
					$this->load->view('userdata/purchasereportgroup',$data);

}else{
				$this->load->view('userdata/purchasereport',$data);
	
}
		
			        	
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewagingpurchasereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  
	  
	  
			  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
			
	  
	  
	  
	  
	  


	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  	  $group = $this->input->post("group");

	  
	  $reporttype = $this->input->post("reporttype");
	  	  $download = $this->input->post("download");
	

	  
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	
	
	


					


								
$data['links'] = "";		
			
			
$data['groupdata'] = "na";
				$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewpurchases'] = $this->usermodel->viewagingpurchasereport($fromdate,$todate,$companyid,$supplier,$reporttype,$download,$group);
		
			$data['total_rows'] =count((array)$data['viewpurchases'] );
	

//
	
	
	if($group !="all"){
$this->load->view('userdata/viewallcreditors',$data);

	
	}else{
	$this->load->view('userdata/viewpurchases',$data);
	
	}
 			

			
			
	
	
			        	
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	public function searchacomplains()
	{ 
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $fromdate = $this->input->post("fromdate");
	  $type = $this->input->post("type");
	  	  $displaytype = $this->input->post("displaytype");


	  
	  $todate = $this->input->post("todate");
	  $subject = $this->input->post("subject");
		  $status = $this->input->post("status");

				$this->load->view("template/headerpagemin");
						  
			$data['links']="";
			
$data['closedate']=$todate;
$data['startdate']=$fromdate;
	$data['subject']=$subject;		
	
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
		


				
$data['todate']=$todate;
$data['fromdate']=$fromdate;
	$data['subject']=$subject;	
	
	
	

	
	$data['complain'] = $this->usermodel->viewsuggestionposted($fromdate,$todate,$subject,$type,$status,$companyid,$displaytype);

$data['total_rows'] =count((array)$data['complain']);
	
	
				$this->load->view('userdata/complain',$data);
	



		
		
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	public function viewpurchasereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  
	  
	  
			  $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
			
	  
	  
	  
	  	  	  $groupall = $this->input->post("groupall");

	  	  	  $transactioncode = $this->input->post("transactioncode");

	  
	  	  $bankname = $this->input->post("bankname");
	  	  $paymentstatus = $this->input->post("paymentstatus");

	  	  $originalamount = $this->input->post("originalamount");


	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $vattype = $this->input->post("vattype");
	  	  $download = $this->input->post("download");
	  	  $daterange = $this->input->post("daterange");
	  	  $payment = $this->input->post("payment");
		  	  	  $PAYMENTDATE = $this->input->post("PAYMENTDATE");

	  	  $group = $this->input->post("group");
	  	  $paymentfrotime = $this->input->post("paymentfrotime");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		
		   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
				  $PAYMENTDATE=$PAYMENTDATE." ".$paymentfrotime;
		
   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;
			  	  $branchname = $this->input->post("branchname");


	
		if(($payment=="yes") && ($supplier=="all")){
			
				
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Transaction cancelled! You have not selected specific supplier to pay.Try again</div>');
								
								 redirect('user/viewpurchases');
								 
								 return false;
			
			
		}
	if($download=="yes"){
		
		
		
		
		  $new_date=date("Y-m-d H:i");		

		$delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Purchase.csv";
		
		   
if(($supplier=="all")&&($vattype=="all")) {
	
	if($daterange=="yes"){
		
		
  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where   fromdate BETWEEN '$fromdate'  and '$todate' and purchaseorder.companyid='$companyid'  and purchaseorder.status='purchases'";

		}else{
		  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where    purchaseorder.companyid='$companyid'  and purchaseorder.status='purchases'";

		}
	
	
	} else if(($supplier=="all")&&($vattype!="all")) {

		  if($daterange=="yes"){
		  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where   fromdate BETWEEN '$fromdate'  and '$todate' and purchaseorder.companyid='$companyid' and  vattype='$vattype' and purchaseorder.status='purchases'";

		}else{
				  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where  purchaseorder.companyid='$companyid' and  vattype='$vattype' and purchaseorder.status='purchases'";

		}
		  
		  
		  
		  
		  
		  
	
	}else  if(($supplier!="all")&&($vattype=="all")) {
		
		if($daterange=="yes"){
			  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where   fromdate BETWEEN '$fromdate'  and '$todate' and purchaseorder.companyid='$companyid'  and supplier='$supplier'  and purchaseorder.status='purchases'";

		}else{
					  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where   purchaseorder.companyid='$companyid'  and supplier='$supplier'  and purchaseorder.status='purchases'";

		}

	}else{

			  
			  
			  if($daterange=="yes"){
			  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where   fromdate BETWEEN '$fromdate'  and '$todate' and purchaseorder.companyid='$companyid'  and supplier='$supplier' and vattype='$vattype' and purchaseorder.status='purchases'";

		}else{
					  $query = "SELECT pin, company,fromdate as invoicedate,ordernumber,description,amount,vat,taxable,EXEMPTED,ZERORATED from  purchaseorder INNER JOIN people ON purchaseorder.supplier=people.id where  purchaseorder.companyid='$companyid'  and supplier='$supplier' and vattype='$vattype' and purchaseorder.status='purchases'";

		}
}
		
       // $query = "SELECT purchases.code,name,open,added,	balance,branchid,startdate,closedate FROM purchases INNER JOIN people on  purchases.supplier= people.id WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
						$data['supplier'] = $supplier;
						$data['bankname'] = $bankname;						$data['PAYMENTDATE'] = $PAYMENTDATE;

												$data['transactioncode'] = $transactioncode;

							$data['group'] = $group;
														$data['originalamount'] = $originalamount;

					$groupdata="";
						if($group !="all"){
									$getgroup= $this->usermodel->populateallarray('category','id',$group);
								$groupname=$getgroup[0]['name'];
								$groupdata="</br>GROUP NAME:.".$groupname;
						}else{
															$groupdata="all";

							
						}
$data['groupdata'] = $groupdata;
				$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewpurchases'] = $this->usermodel->viewpurchasereport($fromdate,$todate,$companyid,$supplier,$vattype,$daterange,$group,$payment,$groupall,$branchname,$paymentstatus);
		
		
		
		
		if($payment=="yes"){
							$this->load->view('userdata/viewpurchasepayment',$data);

		}else{
			if($groupall=="yes"){
											$this->load->view('userdata/viewpurchasesreportgroupall',$data);

			}else{
										$this->load->view('userdata/viewpurchasesreport',$data);
	
			}

		}
			
			
	
	
			        	
		$this->load->view("template/footerpage");
		}
	}
	
	
	
	
	public function viewdeliveryreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $status = $this->input->post("status");
	  	  $download = $this->input->post("download");
	  	  $daterange = $this->input->post("daterange");
	  	  $datetype = $this->input->post("datetype");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	
	if($download=="yes"){
		
		  $new_date=date("Y-m-d H:i");		

		$delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Delivery report.csv";
		
		
		
		
			if(($supplier=="all")&&($status=="all")) {
if($daterange=="yes"){
$query = "SELECT  * from  delivery where   ordereddate BETWEEN '$fromdate'  and '$todate' and companyid='$companyid' ";
		}else{
			$query = "SELECT  * from  delivery where   companyid='$companyid' ";

		}
		
		
	} else if(($supplier=="all")&&($status!="all")) {
		
		
		
		
		if($daterange=="yes"){
$query = "SELECT  * from  delivery where   ordereddate BETWEEN '$fromdate'  and '$todate' and companyid='$companyid' and status='$status'";

		}else{
		$query = "SELECT  * from  delivery where  companyid='$companyid' and  status='$status'";

		}
		
	
	}else  if(($supplier!="all")&&($status=="all")) {
		
		if($daterange=="yes"){
$query = "SELECT  * from  delivery where   ordereddate BETWEEN '$fromdate'  and '$todate' and companyid='$companyid'  and supplier='$supplier' ";

		}else{
		$query = "SELECT  * from  delivery where   companyid='$companyid'  and supplier='$supplier'";

		}
		
	
	}else{

	if($daterange=="yes"){
$query = "SELECT  * from  delivery where   ordereddate BETWEEN '$fromdate'  and '$todate' and companyid='$companyid' and supplier='$supplier'  and status='$status' "; 

		}else{
		$query = "SELECT  * from  delivery where    companyid='$companyid' and supplier='$supplier'  and status='$status'"; 

		}
}

	



       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
		
	$total_rows=0;
							$data['datetype'] =$datetype;

				$data['datetype'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


	

		$data['delivery'] = $this->usermodel->viewdeliveryreport($fromdate,$todate,$companyid,$supplier,$status,$daterange,$datetype);
	$total_rows=count((array)$data['delivery'] );
$data['total_rows']=$total_rows;



				$this->load->view('userdata/recorddelivery',$data);
		
			        	
		$this->load->view("template/footerpage");
		}
	}
	
	
		
	public function viewsalesordereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	  	  $vattype = $this->input->post("vattype");
	  	  $download = $this->input->post("download");

	  	  $mytable = $this->input->post("mytable");

	  	  $branchname = $this->input->post("branchname");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	

		   
	
		

		
		
	
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['links']="";
		$data['viewpurchases'] = $this->usermodel->viewsalesrordereport($fromdate,$todate,$companyid,$supplier,$branchname,$mytable,$download);
		//var_dump($data['salesreport']);
		//exit;
	$data['total_rows']=count((array)$data['viewpurchases']);
				$this->load->view('userdata/salesorder',$data);
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
		public function displayexpiredproducts()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $tobranch = "";
	  
	  

	  
	  
	  
	  
	  
	  
	  $category = $this->input->post("category");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
		$data['supplier']=$supplier;
				$data['type']=$category;
				$data['links']="";
				$data['total_rows']="";


			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
		
		
		if($branchname =="Main"){
			$data['viewwarningproducts'] = $this->usermodel->displayexpiredproducts($fromdate,$todate,$companyid,$branchname);

				$this->load->view('userdata/viewwarningproducts',$data);
	
	}else{
				$data['viewproducts'] = $this->usermodel->displayexpiredproducts($fromdate,$todate,$companyid,$branchname);

				$this->load->view('userdata/viewlowstore',$data);

	}
	
		
		
		

		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function searchleaves()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
	  $tobranch = "";
	 
	  

	  
	  
	  
	  
	  	  
	  
	  $category = $this->input->post("category");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
		$data['supplier']=$supplier;
				$data['type']=$category;
				$data['links']="";
				$data['total_rows']="";



			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
		
		
		
			$data['report'] = $this->usermodel->searchforleaves($fromdate,$todate,$companyid,$branchname,$category);

				$this->load->view('userdata/viewotherleaves',$data);
	

		
		
		

		$this->load->view("template/footerpage");
	}
	
	
		public function viewincomingreportperproject()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  	  $frombranch = $this->input->post("branchname");
			  $project = $this->input->post("project");

	  $todate = $this->input->post("todate");
	  $tobranch = "";
	  
	  
	  
	  if($supplier !=""){
		 	  $tobranch = $supplier;
 
	  }else{
		  		 	  $tobranch = $project;

	  }
	  
	  
	  
	  
	  
	  
	  
	  
	  $category = $this->input->post("category");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
		$data['supplier']=$supplier;
				$data['type']=$category;


			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewincomingstock'] = $this->usermodel->viewincomingreportperproject($fromdate,$todate,$companyid,$frombranch,$tobranch,$category);
		

				$this->load->view('userdata/bulkprojectdispatch',$data);
		$this->load->view("template/footerpage");
	}
	
		public function viewlabourreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


	   $todate = $this->input->post("todate");
 $totime = $this->input->post("totime");
 $frotime = $this->input->post("frotime");
	  $fromdate = $this->input->post("fromdate");
	  	  $description = $this->input->post("description");

	   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;


	  

	   $month = $this->input->post("month");
	   $code = $this->input->post("code");


	   $supplier = $this->input->post("supplier");
	  	  $frombranch = "all";
		

	  $tobranch = $this->input->post("tobranch");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;

			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewlabour'] = $this->usermodel->viewlabourreport($fromdate,$todate,$companyid,$supplier,$frombranch,$month,$code,$description);
		

				$this->load->view('userdata/labourreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
		public function viewincomingreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  	  $frombranch = $this->input->post("branchname");
		
	  $todate = $this->input->post("todate");
	  $user = $this->input->post("user");

	  $tobranch = $this->input->post("tobranch");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;


		$data['supplier']=$supplier;

			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewincomingstock'] = $this->usermodel->viewincomingreport($fromdate,$todate,$companyid,$supplier,$frombranch,$tobranch,$user);
		

				$this->load->view('userdata/viewincomingstock',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
		public function viewpurchaseorderreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");
			  $supplier = $this->input->post("supplier");

	  $todate = $this->input->post("todate");

	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

		$data['links']="";

//
			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewpurchases'] = $this->usermodel->viewpurchaseorderreport($fromdate,$todate,$companyid,$branchname,$supplier);
				$data['total_rows']=count((array)$data['viewpurchases'] );

  $ordernumber=0;
  		 	$finalsalesid = $userid.time();

		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $format=$smsconfig[0]['website'];	
  $latest = $this->usermodel->populatelatestid('purchaseorder', 'id >',0);
  if($latest==FALSE){
	    $ordernumber=$ordernumber+1;
	  
  }else{
	  $mylatestid=$latest[0]['id']; 
	     $ordernumber= $mylatestid+1; 
  }
  

   $data['finalsalesid']=$finalsalesid;
    $data['ordernumber']=$format.$ordernumber;
  
  
				$this->load->view('userdata/allpurchaseorder',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewfarmreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	  $fromdate = $this->input->post("fromdate");
	  	  $frombranch = $this->input->post("branchname");
		
	  $todate = $this->input->post("todate");

	  $tobranch = $this->input->post("tobranch");
		  $one = $this->input->post("one");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
		$data['links']="";


			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewevents'] = $this->usermodel->viewfarmreport($fromdate,$todate,$companyid,$frombranch,$one);
				$data['total_rows']=count((array)$data['viewevents'] );

				$this->load->view('userdata/viewevents',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewincomingreportcategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $category = $this->input->post("category");
	  $fromdate = $this->input->post("fromdate");
	  	  $frombranch = $this->input->post("branchname");
		
	  $todate = $this->input->post("todate");

	  $tobranch = $this->input->post("tobranch");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
	$data['supplier']="all";
			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewincomingstock'] = $this->usermodel->viewincomingreportcategory($fromdate,$todate,$companyid,$category,$frombranch,$tobranch);
		

				$this->load->view('userdata/viewincomingstock',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function updatecustomerbalances()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00am";
	 // $totime="23:59:59pm";
	   //$type = $this->input->post("type");
	  $fromdate = $this->input->post("fromdate");
		
	  $todate = $this->input->post("todate");

	  $action = $this->input->post("action");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	$data['todate']=$todate;
		$data['todate']=$todate;

			$data['salesreport'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
if($action=="view"){
			$data['salesreport'] = $this->usermodel->updatecustomerbalances($fromdate,$todate,$companyid);
	$data['links']=1;
	$data['total_rows']=1;
}else{
	
			$salesreport = $this->usermodel->updatecustomerbalances($fromdate,$todate,$companyid);

						$totalbalance=0;
											$savedpoints=0;
$updateArray = array();


						 if(is_array($salesreport)) 

 {
	foreach ($salesreport as $salesreportrow){
			
	 $totalbalance=$salesreportrow->credit;
		
		
			 $myid = $salesreportrow->customer;
			 
			 
			 $updateArray[]=array(	
			'id'=>$myid,
		
			'balance'=>$totalbalance,
		  

								);	
			 
			 
 }

   	 $RESULT =	$this->db->update_batch('people',$updateArray, 'id');
 
 }
	
	        if($this->db->affected_rows() > 0)
	{
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated invoices</div>');
					
			
				redirect('user/allinvoices');	
	}else{
		

			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the balances..may be because nothing has changed so far.Try again </div>');
						redirect('user/allinvoices');
					
		
	}

	
	
	
}
		
		


				$this->load->view('userdata/allinvoices',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	  public function addwholesalereading()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:sa');
 		//$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	 		
			 $code = htmlspecialchars(trim($this->input->post("code")));
//$qty = $this->input->post("qty");
	  $discount = $this->input->post("discount");
	  $mode = $this->input->post("mode");		  
		  $type = $this->input->post("type");  
		  $start = $this->input->post("start");  

$qty=$this->MyformatMoney($start-$start,true);


		  $dateposted = $this->input->post("mydate");  



		  
		  		  $salestype = $this->input->post("salestype");    

		    
		      $invoice = $this->input->post("invoice"); 
				        $productname = $this->usermodel->geteproductbyid($code);
						
						  if ($productname ==false)
						   {
							  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">That product code doees not exist. Try again.</div>');
								
							redirect('user/openclose');						   
						   return false;
						   }
  $buyingprice=trim($productname[0]['buyingprice']); 
    // $sellingprice=trim($productname[0]['wholesaleprice']); 
	  $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 

	 
	  $newsellingprice=trim($productname[0]['sellingprice']); 
 $sellingprice=$newsellingprice-$discount;
	 
	 
	 
	 
  
    $finaldiscount= ($discount*$qty);
    $amount= ($sellingprice*$qty);
  
  

   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
							
							 
							 	 $finaltax=0;
							 
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								 $mytax=1+($tax_included/100); 
								 $vatable=($sellingprice/$mytax);
								 $myfinaltax=(($sellingprice-$vatable)*$qty);
								
								$finaltax= $this->formatMoney($myfinaltax, true);
								 
							 }
							 
							

				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/openclose ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsale') == "sale")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
			'start'=>$start,
			'close'=>0,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
			'mode' => $mode,		  
		  'type' => $type,    
		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $this->MyMoney($amount,true),
			   			      'bprice' => $buyingprice, 
					'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
			
			
			
								);
								
												$productdata=array(		
												'qty'=>$finalqty,
													);
								
								
							$usr_result = $this->usermodel->add($data,'sales_reading');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							 $this->usermodel->updateproduct($productdata,$code); 

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Sales Added </div>');	
							redirect('user/openclose');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not added.. Try again</div>');
								
								 redirect('user/openclose');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
  	public	function MyMoney($number, $fractional=false) {
						if ($fractional) {
							$number = sprintf('%.2f', $number);
						}
						while (true) {
							$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1$2', $number);
							if ($replaced != $number) {
								$number = $replaced;
							} else {
								break;
							}
						}
						return $number;
					}
 
	
				public function openclose()
	{ 
	$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $userid = $data['id'];
				
				$sale = $this->usermodel->populatealldataarraythree('sales_reading', 'userid',$userid,'status','new','salestype','wholesale');

			//$sale= $this->usermodel->getsales();
			
			$finalsalesid=0;
			 //$salesid=0;
 if($sale==FALSE){
	 	$finalsalesid = 'RS-'.$userid.rand(100, 900).time();

	   //$finalsalesid=$salesid + 1;
 }else{
	 //$salesid=$sale[0]['id']; 
  // $finalsalesid=$salesid + 1;	
$finalsalesid=$sale[0]['invoice'];  
 }
    

	
	//$finalsalesid = 'RS-'.rand(1000, 990000000).time();
	
		$data['salesid'] = $finalsalesid;
	$data['viewwholesales'] = $this->usermodel->getesales_reading($finalsalesid,$userid);
				$this->load->view('userdata/openclose',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	 public function editsalereading() {
 
   if (!$this->input->post('btn_editsales') == "sale"){
			
		
					   
      show_error('You dont have right to change this transaction! Contact Admin', 500);
    }
    else {
		
			$session_data = $this->session->userdata('logged_in');

				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		
		
		
		
							 $sprice = $this->input->post("sprice");
							 							 $date = $this->input->post("date");

							  $type = $this->input->post("type");
							  $start = $this->input->post("start");
							  $close = $this->input->post("close");
$latest=$this->MyformatMoney($close-$start,true);


		 		 $transactionid = $this->input->post("myid");
				 $myinvoice = $this->input->post("myinvoice");
$data['salesid'] = $myinvoice;
		$myproducts=$this->usermodel->getesoldreadingproduct($transactionid);
		$mycode=$myproducts[0]['code'];
		$oldqty=$myproducts[0]['qty'];
		if($close<$start){
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Closing Quantity can not be less than starting quantity. Try again.  </div>');
				redirect('user/openclose',$data);	
		
								
								return false;
		}
		
		if(($close<0) ||($close=="")) {
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong> Closing Quantity can not be less than 0 or null  </div>');
				redirect('user/openclose',$data);	
		
								return false;
		}
		
		if($close==""){
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong> Closing Quantity can not be null  </div>');
				redirect('user/openclose',$data);	
		
								return false;
		}
	
	

	
		
		// $mainproductname = $this->usermodel->geteproductlistbyid($mycode,$branchid);
			
			
			 $amount=(($sprice)* ($latest));

 //  $deductcode=$mainproductname[0]['orderamount']; 
 
   
   
   
   
   
   
		
   	$salesdata=array(		
												'qty'=>$latest,
													'start'=>$start,
														'close'=>$close,
														
											'amount' => $this->MyMoney($amount,true),
													'sprice'=>$sprice,
													'date'=>$date,

													);
	$usr_result = $this->usermodel->updatesalesreading($salesdata,$transactionid); 
										
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
								
						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully </div>');
								//redirect('user/viewsales',$data);
					
						
								
								redirect('user/openclose',$data);
									
							
							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not Updated  </div>');
				
		if($type=="ratail"){
									
							redirect('user/viewsales',$data);

								}else{
								redirect('user/openclose',$data);
									
								}				
							
							}
  
  
  
  
  
  
  
  
  
  
  
  }
	}
	
	
	
	 public function printreceiptsreading() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoicereading($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_readingReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreceiptopenclose', $data);
		
	}
  }
	
	
	
			public function viewsalesreportreading()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $maincategory = $this->input->post("maincategory");


		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	
	$data['fromdate']=$fromdate;
		$data['todate']=$todate;

	
		$data['salesreport'] = $this->usermodel->viewsalesreportreading($finalfromdate,$finaltodate,$type,$companyid,$maincategory);
				$data['viewexpenses'] = false;

		//$data['viewexpenses'] = $this->usermodel->populateexpense($finalfromdate,$finaltodate,$companyid);
		$data['products'] = false;

				$this->load->view('userdata/viewsalesreportexpense',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewgroupsalesreportreading()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['type']=$type;
	$data['companyid']=$companyid;
	
			$data['salesreport'] = $this->usermodel->viewgroupsalesreportreading($finalfromdate,$finaltodate,$type,$companyid);

				$this->load->view('userdata/viewgroupsalesreportreading',$data);

				//$this->load->view('userdata/viewgroupreceiptreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
 public function savesalesreading()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		  $salestype = $this->input->post("salestype");
		  		  $name = $this->input->post("name");

 	 		 $accountno = $this->input->post("accountno");

 	 		 $due = $this->input->post("due");

 $type = $this->input->post("type");
$customer = $this->input->post("customer");
	  $cash = $this->input->post("cash");
	  $total = $this->input->post("total");		  
	  	  $myview = $this->input->post("myview");		  
	  $discountedtotal = $this->input->post("discountedtotal");	
		    	  $maindiscount = $this->input->post("maindiscount");	

		      $invoice = $this->input->post("invoice"); 
			$finalbalance=0;
  $balance= ($total- $cash);
  if($cash>$total){
	  
	 $finalbalance=0; 
  }else{
	  	 $finalbalance=$balance; 

	  
  }
  
  
			  		  $this->form_validation->set_rules("cash", "Amount Paid ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/openclose', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_savesales') == "sales")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			'customer'=>$customer,
		  	'cash'=>$cash,
					  	'salestype'=>$salestype,
			   			   'cashier' => $accountno, 

			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
			'total' => $total,		  
		  'type' => $type,    
		     'invoice' => $invoice,  
		     'balance' => $finalbalance, 
			   'due_date' => $due, 
					   'maindiscount' => $maindiscount,   
							'name' => $name,  					   
		     'discountedtotal' => $discountedtotal, 

			
			
								);
							$usr_result = $this->usermodel->add($data,'salesreading');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$closedata=array(		
									'status'=>'printed',
											);
														$usr_result = $this->usermodel->updatedata($closedata,'sales_reading','invoice',$invoice);

								
								if($type!="Cash"){
									
									$updateddata=array(		
									'type'=>$type,
											);
						$usr_result = $this->usermodel->updatedata($updateddata,'sales_reading','invoice',$invoice);

								}
								
							
								  redirect("user/printreceiptsreading?invoice=". $invoice."");
	
							
							
							 

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not Completed.. Try again</div>');
								
								 redirect($myview);
							}
					   } else 	 	if ($this->input->post('btn_savesales') == "noreceipt")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			'customer'=>$customer,
		  	'cash'=>$cash,
					  	'salestype'=>$salestype,
			   			   'cashier' => $accountno, 
						'name' => $name,  
			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
			'total' => $total,		  
		  'type' => $type,    
		     'invoice' => $invoice,  
		     'balance' => $finalbalance, 
			   			   'due_date' => $due, 

				  'maindiscount' => $maindiscount,    
		     'discountedtotal' => $discountedtotal, 
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'salesreading');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								$closedata=array(		
									'status'=>'notprinted',
											);
														$usr_result = $this->usermodel->updatedata($closedata,'sales_reading','invoice',$invoice);

								
									if($type!="Cash"){
									
									$updateddata=array(		
									'type'=>$type,
											);
						$usr_result = $this->usermodel->updatedata($updateddata,'sales_reading','invoice',$invoice);

								}
								
								 
						 $this->session->set_flashdata('salestmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Completed the Sales..</div>');	
																			
						
														            redirect("user/openclose");
	
							
							 

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not Completed.. Try again</div>');
								
								 redirect($myview);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	
	
	
	public function updatecustomersupplierfiscalyear()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");

	  $dateposted = $this->input->post("dateposted");
			  $fiscalyear = $this->input->post("fiscalyear");

	  $openfiscalyear = $this->input->post("openfiscalyear");

	  $category = $this->input->post("category");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	//$data['todate']=$todate;
	//	$data['todate']=$todate;

			//$data['viewpurchases'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	

			 //  $getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$openfiscalyear);

		   $getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$fiscalyear);

     $startdate=$getfiscalyear[0]["startdate"];
		  	  $enddate=$getfiscalyear[0]["enddate"];	 
						   
	
	
		   $getcurrentfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$openfiscalyear);

     $currentstartdate=$getcurrentfiscalyear[0]["startdate"];
		  	  $currentenddate=$getcurrentfiscalyear[0]["enddate"];	 
	
	
	
	
	
	
	
	
	
			$viewpurchases = $this->usermodel->closefiscalyear($startdate,$enddate,$companyid,$branchid,$category);
			
	$customerbalance=0;
				$finalbalance=0;
				$supplierbalance=0;
											$savedpoints=0;
$updateArray = array();
$insertdata = array();
						 if(is_array($viewpurchases)) 

 {
	foreach ($viewpurchases as $salesreportrow){
		
			$totalbalance=$salesreportrow->balance;	
		 $supplierbalance=$salesreportrow->supplierbalance;	
	
		if($salesreportrow->category=="supplier"){
			
				$finalbalance=$salesreportrow->supplierbalance;
		}else{
			
							$finalbalance=$salesreportrow->balance;

		}
			 $myid = $salesreportrow->id;
		
		
		$previousbalance = $this->usermodel->populatealldatanorraythree('customerfiscalyear','number', $myid,'name',$fiscalyear,'companyid', $companyid);
		
		if($previousbalance !=false){
				 $balanaceid = $previousbalance[0]["id"];
			
				 
			 $updateArray[]=array(	
			'id'=>$balanaceid,
		
			'closing'=>$finalbalance,
		  	'enddate'=>$enddate,
			'status'=>"closed",
								);	
			
		}
		
		

				$currentbalance = $this->usermodel->populatealldatanorraythree('customerfiscalyear','number', $myid,'name',$openfiscalyear,'companyid', $companyid);

		if($currentbalance ==false){
 		
$insertdata[]=array(	
		'userid'=>$userid,
			
				'name'=>$openfiscalyear,
				'startdate'=>$currentstartdate,
							'enddate'=>$currentenddate,
							'number'=>$myid,

		'category'=>$salesreportrow->category,
															

		  	'status'=>"active",
				 'companyid'=>$companyid,
		'branchid'=>$branchid,
				 
			'createdate'=>$dateposted,
			'closing'=>"0.00",
			'opening'=>$finalbalance,

								);	
								
		}
   
}
			 
			 
			 
			 
 

if(!empty($insertdata)){
   $usr_result =$this->db->insert_batch('customerfiscalyear', $insertdata); 

}else{
 $usr_result =0;
	
}



if(!empty($updateArray)){
	 $usr_result=$this->db->update_batch('customerfiscalyear',$updateArray, 'id');

}else{
 $usr_result =0;
	
}





 
 }
	
	

	        if($usr_result > 0)
	{
		
		
	
		
		
		
		
		

			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated closing balances</div>');
					
			
				redirect('user/customerfiscalyear');	
	}else{
		

			$this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the balances. This could be because there is nothing that has changed so far on balances or the balances have been update already. Try again </div>');
						redirect('user/customerfiscalyear');
					
		
	}

	
	
	}
	
	

	
		public function updatesupplierbalances()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00am";
	 // $totime="23:59:59pm";
	   //$type = $this->input->post("type");
	  $fromdate = $this->input->post("fromdate");
		
	  $todate = $this->input->post("todate");

	  $action = $this->input->post("action");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	$data['todate']=$todate;
		$data['todate']=$todate;

			$data['viewpurchases'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
if($action=="view"){
			$data['viewpurchases'] = $this->usermodel->updatesupplierbalances($fromdate,$todate,$companyid);
	$data['links']=1;
	$data['total_rows']=1;
}else{
	
			$viewpurchases = $this->usermodel->updatesupplierbalances($fromdate,$todate,$companyid);

						$totalbalance=0;
											$savedpoints=0;
$updateArray = array();
						 if(is_array($viewpurchases)) 

 {
	foreach ($viewpurchases as $salesreportrow){
		 $ttamount=$salesreportrow->amount;	
		  $ttpaid=$salesreportrow->paid;	
	 $totalbalance=$ttamount -$ttpaid;
		
		
			 $myid = $salesreportrow->supplier;
			 
			 
			 $updateArray[]=array(	
			'id'=>$myid,
		
			'supplierbalance'=>$totalbalance,
		  

								);	
			 
			 
 }

  
   	 $RESULT =	$this->db->update_batch('people',$updateArray, 'id');
 
 }
	
	        if($this->db->affected_rows() > 0)
	{
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated invoices</div>');
					
			
				redirect('user/viewpurchases');	
	}else{
		

			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the balances.Try again </div>');
						redirect('user/viewpurchases');
					
		
	}

	
	
	
}
		
		


				$this->load->view('userdata/viewpurchases',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function updaterentalbalances()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00am";
	 // $totime="23:59:59pm";
	   //$type = $this->input->post("type");
	  $fromdate = $this->input->post("fromdate");
		
	  $todate = $this->input->post("todate");

	  $action = $this->input->post("action");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	$data['todate']=$todate;
		$data['todate']=$todate;

			$data['smsconfig'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
			$viewpurchases = $this->usermodel->updaterentalbalances($fromdate,$todate,$companyid);
						  $dateposted = date('Y-m-d H:i:s');

						$totalbalance=0;
		$updatebookings = array();
		$savedpoints=0;
$updateArray = array();
						 if(is_array($viewpurchases)) 

 {
	 

	foreach ($viewpurchases as $salesreportrow){
		 $salesreportrow->tenantid;
		
	$getdetails = $this->accomodationmodel->gethousedetailsbytenetid($salesreportrow->plotno,$salesreportrow->houseno,$salesreportrow->tenantid);
		if($getdetails !=false){
			  $ttamount=$salesreportrow->amount;	
		  $ttpaid=$salesreportrow->paid;	
	  $totalbalance=$ttamount -$ttpaid;
	//echo "<br>";
			 $myid = $salesreportrow->tenantid;
			 	  $booingid = $getdetails[0]["id"];
			//	echo "<br>";
			 
			 	 $updatebookings[]=array(	
			'id'=>$booingid,
			'totalamount'=>$totalbalance,
			'createdat'=>$dateposted,
		  

								);	
			 $updateArray[]=array(	
			'id'=>$myid,
		
			'supplierbalance'=>$totalbalance,
		  

								);	
		}
			 
			 
 }
 
 


      	 $RESULT =	$this->db->update_batch('bookroom',$updatebookings, 'id');

   	$this->db->update_batch('people',$updateArray, 'id');
 }
	
	        if($this->db->affected_rows() > 0)
	{
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated invoices</div>');
					
			
				redirect('admin/searchstatement');	
	}else{
		

			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the balances.Try again </div>');
						redirect('admin/searchstatement');
					
		
	}

	
	
	

		
		


				$this->load->view('userdata/viewpurchases',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	public function viewpoints()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00am";
	 // $totime="23:59:59pm";
	   $type = $this->input->post("type");
	  $fromdate = $this->input->post("fromdate");
		
	  $todate = $this->input->post("todate");

	  $action = $this->input->post("action");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	$data['todate']=$todate;
		$data['todate']=$todate;

			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
if($action=="view"){
			$data['viewloyality'] = $this->usermodel->viewpoints($fromdate,$todate,$companyid,$type);
	$data['links']=1;
	$data['total_rows']=1;
}else{
	
			$viewloyality = $this->usermodel->viewpoints($fromdate,$todate,$companyid);

						$savedcoins=0;
											$savedpoints=0;
$updateArray = array();
						 if(is_array($viewloyality)) 

 {
	foreach ($viewloyality as $viewloyalityrow){
			
	 $savedcoins=$viewloyalityrow->amount;
		 $savedpoints=$viewloyalityrow->value;		
		
			 $myid = $viewloyalityrow->cardnumber;
			 
			 
			 $updateArray[]=array(	
			'address_1'=>$myid,
		
			'savedcoins'=>$savedcoins,
			'savedpoints'=>$savedpoints,
		  

								);	
			 
			 
 }
  
   	 $RESULT =	$this->db->update_batch('people',$updateArray, 'address_1');
 
 }
	
	        if($this->db->affected_rows() > 0)
	{
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated points</div>');
					
			
				redirect('user/viewloyality');	
	}else{
		
		

			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the balances.Try again </div>');
						redirect('user/viewloyality');
					
		
	}

	
	
	
}
		

				$this->load->view('userdata/viewloyality',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
		public function viewopenclosereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");
		  $department = $this->input->post("department");
		  $stockstatus = $this->input->post("stockstatus");
		  $shift = $this->input->post("shift");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	$data['startdate']=$startdate;
		$data['closedate']=$closedate;
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewproducts'] = $this->usermodel->viewopenclosereport($startdate,$closedate,$companyid,$branchid,$department,$stockstatus,$shift);
		$data['total']=count((array)$data['viewproducts']);
		//exit;

				$this->load->view('userdata/viewopeningstockreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	public function enterallclosingstock()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	//
	   $startdate = $_GET['startdate'];
	     $branchid = $_GET['branchid'];
		   $department = $_GET['department'];
		   		   $method = $_GET['method'];
		   		   $action = $_GET['action'];


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	$data['startdate']=$startdate;
		$data['branchid']=$branchid;
				$data['department']=$department;
												$data['method']=$method;
														$data['action']=$action;

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewproducts'] = $this->usermodel->viewoclosereport($startdate,$companyid,$branchid,$department);
		//var_dump($data['salesreport']);
		//exit;
		if( $method=="bulk"){
							$this->load->view('userdata/viewopeningstockbulk',$data);

			
		}else{
			
							$this->load->view('userdata/viewclosingstock',$data);

		}

				
		$this->load->view("template/footerpage");
	}
	
		public function enterclosingstock()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
		  $department = $this->input->post("department");
		  $method = $this->input->post("method");

				$this->load->view("template/headerpagemin");
		
		//$this->load->view("template/tableheader");
			  $action = $this->input->post("action");
	$data['action']=$action;

	$data['startdate']=$startdate;
		$data['branchid']=$branchid;
				$data['department']=$department;
								$data['method']=$method;

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewproducts'] = $this->usermodel->viewoclosereport($startdate,$companyid,$branchid,$department);
		//var_dump($data['salesreport']);
		//exit;

							$this->load->view('userdata/viewopeningstockbulk',$data);

			
		
				//$this->load->view('userdata/viewclosingstock',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewdailycollectionreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	  // $frotime="00:00:00";
					//$totime="23:59:59";
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  $startdate=$startdate." ".$frotime;
	  	  $closedate=$closedate." ".$totime;
	
	
	$data['startdate']=$startdate;
		$data['closedate']=$closedate;
				$data['links']=null;
								$data['total_rows']=null;


		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['collections'] = $this->usermodel->viewdailycollectionreport($startdate,$closedate,$companyid,$branchid);
		

				$this->load->view('userdata/viewdailycollections',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
  	
	
		public function viewstocktakingreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");
		  $department = $this->input->post("department");
		  		  $orderamount = $this->input->post("orderamount");
		  		   $type = $this->input->post("type");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['department']=$department;
		$data['orderamount']=$orderamount;

	$data['branchid']=$branchid;
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
				
						
							
						if($type=="close"){
							
						$mystock = $this->usermodel->viewstocktakingreport($startdate,$companyid,$branchid,$department,$orderamount);
					
					
					
					
						 if(is_array($mystock)) 
			 
				
					
 {
	foreach ($mystock as $mystockrow){
			
			
			
			
			
			
			
			
			
			
	 $mycode=$mystockrow->code;
		 $mybranchid=$mystockrow->branchid;		
			$myqty=$mystockrow->added;
		 	$mytype=$mystockrow->type;
			 $myid = $mystockrow->id;
			 
				 
						   
					 if($branchid=="Main")
						   {
							   
							$mainstock = $this->usermodel->populateallarray('products','code', $mycode);

 
						   }else{
							   
						 $mainstock = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $mybranchid);


							   
							}
						$currentid=$mainstock[0]["id"];    
						 
				 

    
	
	
			


			
 
	
															 	$updateArray[] =array(	
																'id'=>$currentid,
															'qty'=>$myqty,
																);	

														   }
														   
														   
						 if($branchid=="Main"){
						   
							   $RESULT =	$this->db->update_batch('products',$updateArray, 'id');

						   }else{
							    $RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');



							   
							}

													///	$RESULT =	$this->db->update_batch('stocktaking',$updateArray, 'id');
  	
 }	   


	
				
							//check if username and password is correct
							if($RESULT > 0)
						{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully closed stock taking and updated main stock</div>');	
							redirect("user/viewtocktaking");
						}else {     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock was not closed/updated may be due to no available stock taken for the date indicated. Try again</div>');
							redirect("user/viewtocktaking");

					}
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
					
							
						}else 	if($type=="download"){
						$data['viewproducts'] = $this->usermodel->viewstocktakingreportMain($startdate,$companyid,$branchid,$department,$orderamount,$type);
	
	$data['startdate']=$startdate;
				$this->load->view('userdata/viewtocktakingreport',$data);
						
						
						}else{
							$data['viewproducts'] = $this->usermodel->viewstocktakingreportMain($startdate,$companyid,$branchid,$department,$orderamount,$type);
	
	$data['startdate']=$startdate;
				$this->load->view('userdata/viewtocktakingreport',$data);
							
						}
		
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewstocktakingreportserial()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");
		  $department = $this->input->post("department");
		  $type = $this->input->post("type");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['department']=$department;

	$data['branchid']=$branchid;

	$view="user/getviewstocktakingreportserial?branchid=". $branchid."&companyid=". $companyid."&closedate=". $closedate."&startdate=".$startdate."";

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
						

		$data['viewproducts'] = $this->usermodel->viewstocktakingreportserial($startdate,$companyid,$branchid);
		//var_dump($data['salesreport']);
		//exit;
	$data['startdate']=$startdate;
		$data['view']=$view;
				$this->load->view('userdata/viewtocktakingreportserial',$data);
		$this->load->view("template/footerpage");
	}
	
  
			public function searchallmembersslary()
	{
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Adminhome/searchallmembersslary';
		$config['total_rows'] = $this->usermodel->searchallsalary_record_count($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['viewemployee'] = $this->usermodel->searchallasalary($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");

	
		 $data["total_rows"] =$config['total_rows'];

		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/salaryhistory',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
	
  //
  public function resetmysalesall() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		$data['id'] = $session_data['id'];
		 $userid = $data['id'];
		 
		 
	 $view = trim($_GET['view']);
	   $salesid = trim($_GET['randomitemidentifier']);
	 $returnclearedsales  =$this->usermodel->populatuserpermissionsdataarray('viewreturnsales','returnclearedsales',$userid);
	
	   if($returnclearedsales==true){
		   
		   
	  
		   
		   	 $mysoldproducts = $this->usermodel->populatealldatanoarray('sales_orderraw','companyid', $companyid,'ordersales', 'printed');

	   }else{
		   
		  $mysoldproducts =false;  
		   
	   }
	     

		
	  	if(is_array($mysoldproducts)){
	 
	 
	 foreach ($mysoldproducts as $c){
		  $transactionid=$c->id;
		 	 $itemid=$c->code;
			  $totalqty=$c->qty;
			  			  $myserialname=$c->serial;

			  $branch=$c->branch;
		 //$myproducts=$this->usermodel->geteproductbyid($itemid);
		 
		  $myproducts = $this->usermodel->populatealldataarray('productlist','code', $itemid,'branch', $branch);

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
		
   $finalqty=($availableqty+$totalqty);
	
		 	 $this->usermodel->deletedata($transactionid,"id","sales_orderraw");

		 //$usr_result = $this->usermodel->deletedata($invoice_number,"invoice_number","newstock");
		 $productdata=array(		
												'qty'=>$finalqty,
													);
								
							//	$usr_result = 	 $this->usermodel->updateproduct($productdata,$mycode); 
		 								$usr_result = 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);
				if ($myserialname !="")
						   {
									$serialdata=array(		
						'status'=>"new",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$myserialname);

						   }
						   
		
		   $mystatus=$c->status;
	
	   $transactionid=$c->id; $itemid=$c->code;$totalqty=$c->qty;$mybranch=$c->branch;$mytotal=$c->amount;
		  $producttype=$c->producttype;
		

			 $mybprice=$c->bprice;
			  $correctqty=$c->qty;
			  $finalbprice=((double)$mybprice* (double)$correctqty);
			 
		$salesaccount=$c->salesaccount;
		  $costofgoodsold=$c->expenseaccount;
		   $inventoryaccount=$c->assetaccount;
	 
	   
	   
	      $myid=trim($c->id);
				
				
				
		$assetaccount=$c->assetaccount;
		$salesaccount=$c->salesaccount;
		$expenseaccount=$c->expenseaccount;
			$producttype=$c->producttype;	

			
				
				
				
				
				
		$code=$c->code;
		$myqty=$c->qty;
		$invoice=$c->invoice;
				$dateposted=$c->dateposted;
	 $ordersales=$c->ordersales;

	 $status=$c->status;
	 
	 
	 		$myinvoice=$c->myinvoice;

	 $branch=$c->branch;
		$sprice=$c->sprice;
	$salestype=$c->salestype;
	
	 $address=$c->address;
		$vattype=$c->vattype;
	$mytype=$c->type;
	 $myqty=$c->qty;

	$taxable=$c->taxable;
		$taxindicator=$c->taxindicator;
				$updatedby=$c->updatedby;

		 $uom=$c->uom;
		$bprice=$c->bprice;
	$taxable=$c->taxable;
	$amount=$c->amount;
	$tax=$c->tax;
	$discount=$c->discount;

	 $tax2=$c->tax2;
		$maincategory=$c->maincategory;
	$category=$c->category;
		$stockafter=$c->stockafter;
		 	$uomqty=$c->uomqty;
		 	$serial=$c->serial;

		 	$stockbefore=$c->stockbefore;

						   
						   
						   
				
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$c->userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);		   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
	 }
	 
	 
	 
	 
	 		
		$usr_result2 =$this->db->insert_batch('sales_ordercancelled', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
		
	 
	 
		}
	 

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								
									// $this->usermodel->updateproduct($productdata,$mycode); 
								
										 								 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);

								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Deleted successfully </div>');
								redirect($view);
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
					redirect($view);					
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }	
	
  
	
	
		public function viewstocktakingreporbranch()
	{ 
	
	$session_data = $this->session->userdata('logged_in');

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $branchid = $_GET['branchid'];
		 	$data['branchid']=$branchid;
			
			
			$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		   $startdate = $_GET['startdate'];
			   $department = $_GET['department'];

	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$data['startdate']=$startdate;

		$data['department']=$department;

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewproducts'] = $this->usermodel->viewstocktakingreport($startdate,$companyid,$branchid,$department);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewtocktakingreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewincomingstorereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	  $supplier = $this->input->post("supplier");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewincomingstock'] = $this->usermodel->viewincomingstorereport($fromdate,$todate,$companyid,$supplier);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewincomingstorereport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	 public function viewproductgroupsalesreportbycustomer()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        	  	  $branchname = $this->input->post("branchname");

		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	//  $totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
	   $view = $this->input->post("view");
	   	   $actiontype = $this->input->post("actiontype");

	   	   	    $searchtype = $this->input->post("searchtype");
	   	   	    $commissiontype = $this->input->post("commissiontype");

	   	   $group = $this->input->post("group");

	   	$users = explode(':=',$this->input->post("user"));

 
   $user = htmlspecialchars(trim($users[0]));
  

	   $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	
	 
	 
	 	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
	 
	 
	 
	 
	 
		
		$this->load->view("template/tableheader");
	
	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;

	        		//$data['allsales']= $this->usermodel->populateall('sales','customer',$user);


$data['finaltodate']=$finaltodate;
			
	$data['finalfromdate']=$finalfromdate;
	$data['allcollections']=0;		
	
		$data['type']=$type;		
								$data['viewexpenses'] = false;

			
				$data['group']=$group;	
		$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="SUMMARY DAILY SALES PER CUSTOMER  REPORT";

$data['links'] = null;
		$data['paidpurchase'] = null;

		$data['paidbills'] = null;

	 						$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	 						$data['viewreceipt'] = $this->usermodel->populateallarray('people','id',$user);

if($group=="no"){
	$data['salesreport'] = $this->usermodel->viewproductgroupsalesreportbycustomer($finalfromdate,$finaltodate,$type,$companyid,$user,$branchname,$group,$searchtype);
	$data['user']=$user;
	$data['myuser']= $user;
	
	if($actiontype=="print"){
				$this->load->view('userdata/printinvoiceitems',$data);

	}else{
				$this->load->view('userdata/viewsalesreport',$data);

	}
$data['total_rows'] =count((array)	$data['salesreport']);
	
}else{
	
	if($group=="summary"){
		
			$data['salesreport'] = $this->usermodel->viewproductgroupsalesreportbyagents($finalfromdate,$finaltodate,$type,$companyid,$user,$branchname,$group,$searchtype);
	

$data['total_rows'] =count((array)	$data['salesreport']);


					$data['paidpurchase'] = null;

		
		
					$data['report']="yes";
		
		
					$data['user']=$user;
		$data['finaltodate']=$todate;
$data['finalfromdate']=$fromdate;


 $myusers="";
				if( $user!="all"){
				$allusers=$this->usermodel->geteuser($user);
    $myusers=$allusers[0]['firstname'];
						 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR ".$myusers;

				}else{
					
					 $myusers="All Users";
					 $data['reporttype']="SUMMARY DAILY AGENTS SALES REPORT  ";
				}
				

	if( $branchname !="all"){
		
				$mybranch = $this->usermodel->populateallarray('branch','id',$branchname);
   $mybranchname=$mybranch[0]['name'];

						 $data['branchdata']=" ".$mybranchname;

				}else{
					
				
					 $data['branchdata']="All Branches/counters ";
				}












	$this->load->view("userdata/agentsalessummary",$data);

	}else{
		
	
	
	$data['salesreport'] = $this->usermodel->viewproductgroupsalesreportbycustomer($finalfromdate,$finaltodate,$type,$companyid,$user,$branchname,$group,$searchtype);
	

$data['total_rows'] =count((array)	$data['salesreport']);

if($view=="user/viewreturnsales"){
	
	$this->load->view('userdata/viewgroupreturnreport',$data);
}else {
	
	$this->load->view('userdata/viewgroupsalesreport',$data);
}
}
}


				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
   public function updatestock()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		 
		 	    $negativestockadjustment=$this->usermodel->populatuserpermissionsdataarray('products','negativestockadjustment',$userid);

		  	 $qty = trim($this->input->post("qty"));
			 		  	 $name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 			  $method = $this->input->post("method");

			 

		   	  $from = trim($this->input->post("from"));
			
			
					   	  $description = trim($this->input->post("description"));

					   	  

			
			
			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		
		 $this->load->view('userdata/viewproducts', $data);
  
			
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_addstock') == "stock")
					   {
						   
						  $updateArray = array(); 
						   
						   if($total<0){
						   
						  if( $negativestockadjustment==false){  
						  
						   							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not make  negative(-) stock adjustment. Try again.</div>');

				  

						  		if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}						  



						  return false;
						   
						   
						  }
						  }
						   
						   
						   
						   
						   
								
							$myproducts = $this->usermodel->populateallarray('products','code', $code);
$usr_result =false;
	 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
 $buyingprice=$myproducts[0]['buyingprice'];
  $sellingprice=$myproducts[0]['sellingprice'];
    $itemtype=trim($myproducts[0]['orderamount']); 
			  $inventorytype=trim($myproducts[0]['producttype']); 

   $finalqty=($availableqty+$total);
	 
							
								
								
											$stockdata=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$description,
				'stockfrom'=>$from,
				'stockto'=>'Main',
				'type'=>'Main',
	 	'branchid'=>$branchid,
'balance'=>$finalqty,
'item_id1'=>$availableqty,
		'buyingprice'=>$buyingprice,
																'sellingprice'=>$sellingprice,

	 
								);

								
								
						$productdata=array(		

						'qty'=>$finalqty,
						);		
								
								
								
								
									if($method=="Production"){
								
								
	  //if( ($inventorytype=="Inventory")&&($itemtype=="mainitem")){
		  if( ($inventorytype=="Inventory")){


	$uomproducts = $this->usermodel->populatealldatanoarrayfour('uomproducts','code', $code,'status',"child",'companyid',$companyid,'updatedate <>',"Inactive");

$mytotalcost=0;
		$finalmainqty=0;
				$finalbuyingprices=0;

	if(is_array($uomproducts)){
	

$insertstockdata = array();
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	//$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);
	$myproductlist = $this->usermodel->populatealldataarray('products','code', $uomcode,'companyid', $companyid);

	$finalmainqty=$myproductlist[0]['qty']+$total;
//$mytotal = $total*$c->brice;
$mytotal = $total*$c->qty;

$availableuomqty=$myproductlist[0]['qty'];

	$finalbuyingprices=	$finalbuyingprices+$c->brice;

 $myinventorytype=trim($myproductlist[0]['producttype']);
if(($availableuomqty < $mytotal) && ($myinventorytype !="Service")) {
				   							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not make  negative(-) stock adjustment. Try again.</div>');


		

						  		if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}						  
 return false;
						   	
	//
}
	$myid =$myproductlist[0]['id'];

	$mytotalcost=  $mytotalcost+ ( $c->qty * $myproductlist[0]['buyingprice']);
		//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);

	   $myfinalqty=($availableuomqty-$mytotal);
$myname=$myproductlist[0]['name'];
							
if($myinventorytype !="Service") {
	$updateArray[] =array(	
	'id'=>$myid,
	//'code'=>$code,

//'buyingprice'=>$finalbuyingprices,
	
'qty'=>$myfinalqty,
);	
}


	 $insertstockdata[]	=array(		
			'total'=>$mytotal,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$uomcode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				//'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Automatic Production adjustment',
				'type'=>$branchid,
				'balance'=>$myfinalqty,
				'item_id1'=>$availableuomqty,

				'description'=>$description,

								);
						
		

	
	}
		$buyingprice=$mytotalcost;

		

		$usr_result =$this->db->insert_batch('newstock', $insertstockdata); 
						//$this->db->update_batch('products',$updateArray, 'id'); 

						//$this->db->update_batch('productlist',$updateArray, 'id'); 


$myproductdata=array(		
	'buyingprice'=>$finalbuyingprices,

						'qty'=>$finalqty,
						);



							if($this->db->affected_rows() > 0)
						{
							
							
						if(!empty($updateArray)){

					$this->db->update_batch('products',$updateArray, 'id'); 

							 }								 
			//	$this->db->update_batch('productlist',$updateArray1, 'code'); 
		
			$dataproductlist=array(	
												
	'buyingprice'=>$finalbuyingprices,
				
				);
$this->usermodel->updatedata($dataproductlist,'productlist','code',$code);
	
						
						 $productlistdata	=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Main Automatic adjustment',
				'type'=>$branchid,
				'balance'=>($availableqty+$total),
				'item_id1'=>$availableqty,


								);
						
				//$this->usermodel->add($productlistdata,'newstock');

						

		
	
							
							}
	
								$usr_result = $this->usermodel->updatedata($myproductdata,'products','code',$code);

	
	
	
	}else{
		
$buyingprice=$buyingprice;

						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The product does not have any production item assigned to it  Try again.</div>');
						  
						  	
						  		if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}




							
									
	   return false;
		
	}
	
	
	


		



   }	
								



						}else{
							
													$usr_result = $this->usermodel->updatedata($productdata,'products','id',$productid);
	
						}
								
								
								
								
								
								
								
								
							
								

								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
							 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
        			
									
								
									
						$this->usermodel->add($stockdata,'newstock');
  	

					

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Updated the  product!</div>');
								if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}

								

								 
							}else{
						
							    

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
					if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
	
	
	
	
	
	
   public function updatestocklist()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("qty"));
			 		  	 $name = trim($this->input->post("name"));
		 	    $negativestockadjustment=$this->usermodel->populatuserpermissionsdataarray('products','negativestockadjustment',$userid);

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 
			 			  $branch = $this->input->post("branch");


		   	  $from = trim($this->input->post("from"));
			
					   	  $description = trim($this->input->post("description"));
			 			  $method = $this->input->post("method");

					   	  

			
			
			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		
		 $this->load->view('userdata/viewproducts', $data);
  
			
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_addstock') == "stock")
					   {
						   
						   
						      
						   
						   if( $total < 0){
						   
						  if( $negativestockadjustment==false){  
						  
						   							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not make  negative(-) stock adjustment. Try again.</div>');

						  

						  		if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}						  



						  return false;
						   
						   
						  }
						  }
						   
						   
						   
						   
						   
						   
						   
						   
						   
							$usr_result =false;	
							$myproducts = $this->usermodel->populateallarray('productlist','id', $productid);

	 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
	 $sellingprice=$myproducts[0]['sellingprice'];
 $buyingprice=$myproducts[0]['buyingprice'];
		  $hscode=$myproducts[0]['hscode'];

		 
		 
    $itemtype=trim($myproducts[0]['orderamount']); 
			  $inventorytype=trim($myproducts[0]['producttype']); 

		 
		 
		 
		 
		 
		 
   $finalqty=($availableqty+$total);
	 $productdata=array(		
						'qty'=>$finalqty,
						);
							
							
								
								
											$stockdata=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$description,
								'buyingprice'=>$buyingprice,
																'sellingprice'=>$sellingprice,

	 	'branchid'=>$branchid,

				'stockfrom'=>$from,
		    'stockto' => $branch, 
				'type'=>$branch,
						'balance'=>$finalqty,
							'item_id1'=>$availableqty,

								);
	
								
								

								
							 
							 
									if($method=="Production"){
								
								 // if( ($inventorytype=="Inventory")&&($itemtype=="mainitem")){

	  if($inventorytype=="Inventory"){


	$uomproducts = $this->usermodel->populatealldatanoarrayfour('uomproducts','code', $code,'status',"child",'companyid',$companyid,'updatedate <>',"Inactive");


	if(is_array($uomproducts)){
	$mytotalcost=0;
		$finalmainqty=0;

$insertstockdata = array();
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);
	//$myproductlist = $this->usermodel->populatealldataarray('products','code', $uomcode,'companyid', $companyid);

	$finalmainqty=$myproductlist[0]['qty']+$total;
$mytotal = $total*$c->qty;
$availableuomqty=$myproductlist[0]['qty'];
//
 $myproducttype=trim($myproductlist[0]['producttype']); 
	if($myproducttype !="Service"){
$restock=$mytotal-$availableuomqty;

if($availableuomqty < $mytotal){
				   							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not make  negative(-) stock adjustment. Product('.$uomcode.') has less quantities ('.$availableuomqty.' ). Try restock ('.$restock.' ) quantities fisrt.</div>');

						  

						  		if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}						  
 return false;
						   	
}
	}
	$myid =$myproductlist[0]['id'];

	$mytotalcost=  $mytotalcost+ ($c->qty * $myproductlist[0]['buyingprice']);
		//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);

	   $myfinalqty=($availableuomqty-$mytotal);
$myname=$myproductlist[0]['name'];
							
if($myproducttype!="Service"){
	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$myfinalqty,
);	

}
	 $insertstockdata[]	=array(		
			'total'=>$mytotal,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$uomcode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				//'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Automatic Production adjustment',
				'type'=>$branchid,
				'balance'=>$myfinalqty,
				'item_id1'=>$availableuomqty,
				'description'=>$description,


								);
						
		

	
	}
		$buyingprice=$mytotalcost;

		

									$usr_result =$this->db->insert_batch('newstock', $insertstockdata); 


							if($this->db->affected_rows() > 0)
						{
						//$this->db->update_batch('products',$updateArray, 'id'); 
				$this->db->update_batch('productlist',$updateArray, 'id'); 
						
						
						 $productlistdata	=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Automatic adjustment ',
				'type'=>$branchid,
				'balance'=>($availableqty+$total),
				'item_id1'=>$availableqty,


								);
						
				//$this->usermodel->add($productlistdata,'newstock');

						

		
	
							
							}
	

								$usr_result = $this->usermodel->updatedata($productdata,'productlist','id',$productid);

	
	
	}else{
		
$buyingprice=$buyingprice;

						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The product does not have any production item assigned to it  Try again.</div>');
						  
						  	
						  




							
					redirect($view);	
	   return false;
		
	}
	
	
	


		



   }	
								



						}else{
							
									$usr_result = $this->usermodel->updatedata($productdata,'productlist','id',$productid);

						}
								
								
							 
							 
							 
							 
							 
							 
							 
							 
							 
							 
							 

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
        			
									
								
									
						$this->usermodel->add($stockdata,'newstock');
  
						
								
								
								
								
								
								
						 
						   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];
						 $etimsstockio = trim($this->input->post("etimsstockio"));

							   if (($etims =="EnableEtims") && ($etimsstockio=="Yes")){

								
							   //if ($etims =="EnableEtims"){
								
														  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);

													      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
													redirect($view);	
						   

						   
						   return false;
						   }

$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
								   

  if($inventorytype !="Service"){

$this->SendStStockMaster($code,$finalqty);

//
	  $LATEST = $this->usermodel->last_record("newstock",$companyid,$userid);
	   	$finalid=$LATEST[0]["id"];
	 
		//echo$finalid=$latestid+1;
		

$this-> SendStStockIO($code,$qty,$finalid,0,"","","06");

  }
						   
 $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

									
								
		 }				
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								


						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Updated the  product!</div>');
								if($page!=0){
													redirect($view);	
													//redirect('user/viewproducts/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
					if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
	
   public function swapstock()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("qty"));
			 		  	 $newproduct = trim($this->input->post("newproduct"));

			 		  	 $name = trim($this->input->post("name"));
			 		  	 $tobranch = trim($this->input->post("tobranch"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 			  $myview = $this->input->post("myview");

			 			  $branch = $this->input->post("branch");


		   	  $from = trim($this->input->post("from"));
			
					   	  $description = trim($this->input->post("description"));

					   	  

			
			
			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		
		 $this->load->view('userdata/viewproducts', $data);
  
			
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_swaptock') == "swap")
					   {
								
								$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $newproduct,'branch', $branch);

							if($code==$newproduct){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You can not swap same products. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
					
					
								
					if($myproductlist==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This product code ('.$newproduct.')  does not exist or has been deactivated. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
					
										 $availableqty=$myproductlist[0]['qty'];

							if($availableqty < $qty){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  The available qty ('.$availableqty.')  is less than  ('.$qty.') which you want swap with. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
					
					
					
					
					
					
					$lastest = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

					
					
							if(($myproductlist[0]['sellingprice'])!=($lastest[0]['sellingprice'])){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  The product prices ('.$myproductlist[0]['sellingprice'].')  and this  ('.$lastest[0]['sellingprice'].') are not equal.You can only swap  items with same selling price. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
					
					
					
					
								
								
	
		 $availableqty=$myproductlist[0]['qty'];
   $finalqty=($availableqty-$qty);

   							
							
						//$mycurrentbalance=$finalqty;
						
						//$mypreviousbalance=$availableqty;
								
								$stockdata=array(		
		
								'status'=>"new",
								'code'=>$newproduct,


								);
	
							$usr_result = $this->usermodel->updatedata($stockdata,'sales_order','id',$productid);


								

								
							 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
        							$updatestockdata1=array(		
		
							
								'qty'=>$finalqty,


								);
	
					 $this->usermodel->updatedatabytwo($updatestockdata1,'productlist','code',$newproduct,'branch',$branch);
 $availableqty2=$lastest[0]['qty'];
   $finalqty2=($availableqty2+$qty);
        							$updatestockdata2=array(		
		
							
								'qty'=>$finalqty2,


								);
	
					 $this->usermodel->updatedatabytwo($updatestockdata2,'productlist','code',$code,'branch',$branch);


						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully swapped the  product, Please proceed to print a nother order! </div>');
						//redirect("user/searchinvoice?code=".$invoice."&view=user/viewsales");	
													//redirect($view.'/'.$page);	
													redirect($myview);	

return false;
								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Product was not swapped .. Try again</div>');
								
									if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
   public function movetock()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("qty"));
			 		  	 $newproduct = trim($this->input->post("newproduct"));

			 		  	 $name = trim($this->input->post("name"));
			 		  	 $tobranch = trim($this->input->post("tobranch"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 
			 			  $branch = $this->input->post("branch");


		   	  $from = trim($this->input->post("from"));
			
					   	  $description = trim($this->input->post("description"));

					   	  

			
			
			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		
		 $this->load->view('userdata/viewproducts', $data);
  
			
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_movestock') == "move")
					   {
								
								$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $newproduct,'branch', $tobranch);

								
					if($myproductlist==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This product code ('.$newproduct.')  does not exist or has been deactivated. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
			$child  = $this->usermodel->populatealldatanoarray('uomproducts','uom', $newproduct,'status',"child" );
		
		
if(is_array($child)) {

   foreach($child as $row)
   {
   $factor=trim($row->qty);
		
		
   }
		
   }
		
		
		
		
								$mytotal=0;
							if($total==0){
								$mytotal=$factor*$description;

							}else{

								$mytotal=$total;

							}								
								
								
								
								
	
		 $availableqty=$myproductlist[0]['qty'];
   $finalqty=($availableqty+$mytotal);

   								$myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

   	 $sellingprice=$myproducts[0]['sellingprice'];

   		 $mainavailableqty=$myproducts[0]['qty'];
   $finalmainqty=($mainavailableqty-$description);

							
						$mycurrentbalance=$finalqty;
						$mypreviousbalance=$availableqty;
								
											$stockdata=array(		
			'total'=>$mytotal,
			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$newproduct,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$description,
				'stockfrom'=>$from,
				'stockto'=>'Move',
				'type'=>$tobranch,
								'balance'=>$mycurrentbalance,
								'item_id1'=>$mypreviousbalance,
								'sellingprice'=>$sellingprice,


								);
	
								
							$usr_result =	$this->usermodel->add($stockdata,'newstock');

								

								
							 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
        											
  
						
								$productmaindata=array(		
						'qty'=>$finalmainqty,
						);
		
		
		
	 $productlistdata=array(		
						'qty'=>$finalqty,
						);
								
								//$this->usermodel->updateproductlist($productdata,$code,$branch); 
		
								// $this->usermodel->updatedata($productmaindata,'products','code',$code);


						
						$this->usermodel->updatedatabytwo($productmaindata,'productlist','code',$code,'branch',$branch);


					 $this->usermodel->updatedatabytwo($productlistdata,'productlist','code',$newproduct,'branch',$tobranch);



						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Updated the  product!</div>');
								if($page!=0){
													redirect($view);	
													//redirect('user/viewproducts/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
									if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
   public function movebulktock()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("total"));
			 			 		  
						 
						 
						 
						 
						 
						 
						 
					
					
 			$mynewproduct = explode(':=',$this->input->post("toproduct"));

 
  $newproduct = htmlspecialchars(trim($mynewproduct[0]));

						 
						 
			 		  	 $deduct = trim($this->input->post("deduct"));


			 		  	 $name = trim($this->input->post("name"));
			 		  	 $tobranch = trim($this->input->post("tobranch"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			
			 
 			$mycode = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($mycode[0]));

			 
			 
			 
			 
			 
			 
			 
			  $view = $this->input->post("view");
			 
			 			  $branch = $this->input->post("branch");


		   	  $from = trim($this->input->post("from"));
			
					   	  $invoice = trim($this->input->post("invoice"));

					   	  
	 
						 if( $qty < 0){
							 
							  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You can not dispatch negative quantity ('.$qty.') . Try again</div>');
								
													redirect($view);	
								 
								 return false;
							 
							 
							 }

			
			
			
		  $this->form_validation->set_rules("code", "code", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		
		 $this->load->view('userdata/bulkdispatch', $data);
  
			
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_movestock') == "stock")
					   {
								
				
			/*$child  = $this->usermodel->populatealldatanoarray('uomproducts','uom', $newproduct,'status',"child" );
		
		
if(is_array($child)) {

   foreach($child as $row)
   {
   $factor=trim($row->qty);
		
		
   }
		
   }
   
   
   
   */
   
   
   
   
   
   
   
		
		
		
		
								$mytotal=0;
							
								 $mytotal=$qty;

						//	 $mytotal=$factor*$qty;
			
								
						
	
	



						if ($from =="Main")
						   {
							$myproducts = $this->usermodel->populateallarray('products','code', $code);
   
							   
						   }else{
					$myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);


							   
							}

if ($tobranch=="Main")
						   {
							$myproductsTO = $this->usermodel->populateallarray('products','code', $newproduct);
   
							   
						   }else{
							$myproductsTO = $this->usermodel->populatealldataarray('productlist','code', $newproduct,'branch', $tobranch);


							   
							}






	if($myproductsTO==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This product code ('.$newproduct.')  does not exist or has been deactivated. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
			


	if($myproducts==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This product code ('.$code.')  does not exist or has been deactivated. Try again</div>');
								
													redirect($view);	
								 
								 return false;
					}
			

	 $availableqty=$myproductsTO[0]['qty'];
   $finalqty=($availableqty+$mytotal);

   	 $sellingprice=$myproducts[0]['sellingprice'];
   	 $buyingprice=$myproducts[0]['buyingprice'];

   		 $mainavailableqty=$myproducts[0]['qty'];
   $finalmainqty=($mainavailableqty-$deduct);
 $finalmainqtyTO=($myproductsTO[0]['qty']+$mytotal);
					
						$mycurrentbalance=$finalqty;
						$mypreviousbalance=$availableqty;
						
						
						
						
			
  	   if($deduct>$mainavailableqty ){
			     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> The available quantity ('.$mainavailableqty.') is less than what you want to dispatch('.$total.').  Try a gain a lower number or add more stock first.</div>');
						  redirect($view);
	   return false;
   }
  
  			
						
						
						
								
											$stockdata=array(		
						'invoice'=>$invoice,
			'total'=>$deduct,

			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$deduct,
				'stockfrom'=>$from,
				'stockto'=>'Move From',
				'type'=>$from,
					'branchid'=>$branchid,

								'balance'=>$finalmainqty,
								'item_id1'=>$myproducts[0]['qty'],
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,

								'frombefore'=>$myproducts[0]['qty'],
									'fromafter'=>$finalmainqty,
									
									
								);
	
								
							$usr_result =	$this->usermodel->add($stockdata,'newstock');

								
//
								
							 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
											$stocktodata=array(		
			'total'=>$mytotal,
						'invoice'=>$invoice,

			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$newproduct,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$deduct,
				'stockfrom'=>$from,
				'stockto'=>'Move',
				'type'=>$tobranch,
					'branchid'=>$branchid,

								'balance'=>$myproductsTO[0]['qty']+$mytotal,
								'item_id1'=>$myproductsTO[0]['qty'],
								'sellingprice'=>$myproductsTO[0]['sellingprice'],
								'buyingprice'=>$myproductsTO[0]['buyingprice'],
									'frombefore'=>$myproductsTO[0]['qty'],
									'fromafter'=>$myproductsTO[0]['qty']+$mytotal,


								);
	
								
							$usr_result =	$this->usermodel->add($stocktodata,'newstock');

        											
  
						
								$productmaindata=array(		
						'qty'=>$finalmainqty,
						);
		
		
		
	 $productlistdata=array(		
						'qty'=>$finalqty,
						);
						


						if ($from =="Main")
						   {
   $usr_result = $this->usermodel->updatedata($productmaindata,'products','code',$code);
  
						   }else{
						$this->usermodel->updatedatabytwo($productmaindata,'productlist','code',$code,'branch',$from);


							   
							}

						
	if ($tobranch =="Main")
						   {
   $usr_result = $this->usermodel->updatedata($productlistdata,'products','code',$code);
  
						   }else{
					 $this->usermodel->updatedatabytwo($productlistdata,'productlist','code',$newproduct,'branch',$tobranch);


							   
							}
						





						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Updated the  product!</div>');
								if($page!=0){
													redirect($view);	
													//redirect('user/viewproducts/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
									if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
		
	 public function viewproductsalesreportbycustomer()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  	  $branchname = $this->input->post("branchname");

	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	        		$data['allsales']= $this->usermodel->populateall('sales','customer',$user);


$data['finaltodate']=$finaltodate;
			
	$data['finalfromdate']=$finalfromdate;		
		$data['type']=$type;		
			
			
			
		//$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$user);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewsalesreportbycustomer1',$data);
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	public function viewproductgroupsalesreportbyuser()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  	  $branchname = $this->input->post("branchname");

	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
			$data['viewexpenses'] = $this->usermodel->populateexpense($finalfromdate,$finaltodate,$companyid);

		$data['salesreport'] = $this->usermodel->viewproductgroupsalesreportbyuser($finalfromdate,$finaltodate,$type,$companyid,$user,$branchname);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewgroupsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
 public function searchallpayment()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
$method = trim($this->usermodel->searchmethod_handler($this->input->get_post('method', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallpayment';
		$config['total_rows'] = $this->usermodel->search_record_payment($searchterm,$method);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['mpesareport'] = $this->usermodel->searchallreceivedmoney($searchterm,$method,$limit);
		
		//$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewprndingmoneyreceived',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewprndingmoneyreceived()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 	$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');
$restricttill=$smsconfig[0]["restricttill"];

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
					 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
	
		 }


		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		
		 
		 
		 
		 

		  	      $viewmpesamessages=$this->usermodel->populatuserpermissionsdataarray('cashiersales','viewmpesamessages',$userid);

		  	      $dontshowtotal=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dontshowtotal',$userid);
		
				$config['base_url'] = base_url('Systemusers/viewprndingmoneyreceived');
			
	//$config['total_rows'] = $this->usermodel->count_allwheredata('sms_in','used',2,'amount>',0);
 if( $viewmpesamessages==true){
 
 
 
 
if($restricttill=="yes"){
										$config['total_rows'] = $this->usermodel->count_allpendingmpesasalesbydate('sms_in',$finalstartdate, $finalendate,$branchid);

}else{
										$config['total_rows'] = $this->usermodel->count_allpendingmpesasalesbydate('sms_in',$finalstartdate, $finalendate,"all");


}
	

 
 
 
 
 }else{
										$config['total_rows'] = false;
 
 }

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		


 if( $viewmpesamessages==true){
	 
	 
	 
	 if($restricttill=="yes"){
			 			        $data["mpesareport"] = $this->usermodel->displayallmpesapendingsalesbydate($config["per_page"], $page,'sms_in',$finalstartdate, $finalendate,$branchid);

}else{
			 			        $data["mpesareport"] = $this->usermodel->displayallmpesapendingsalesbydate($config["per_page"], $page,'sms_in',$finalstartdate, $finalendate,"all");


}
	
	 
	 
	 
	 
	 
	 
 
 }else{
			 			        $data["mpesareport"] = false;
 
 }

			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewprndingmoneyreceived',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
		public function allinvoicesnow()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   	$data["title"] ="ALL INVOICES";
				
				$config['base_url'] = base_url('Systemusers/allinvoicesnow');
			
			
					$viewallcounters=$this->usermodel->populatuserpermissionsdataarray('cashiersales','viewallcounters',$userid);

 if( $viewallcounters==true){
			$config['total_rows'] = $this->usermodel->count_allcreditinvoice('sales','companyid',$companyid);
 }else{
	 
	 			$config['total_rows'] = $this->usermodel->count_allcreditinvoice('sales','branch',$branchid);

	 
 }

			
			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
		 if( $viewallcounters==true){
		 $data["salesreport"] = $this->usermodel->displayallcreditinvoice($config["per_page"], $page,'sales','companyid',$companyid);
 }else{
	 
	 
	 		 $data["salesreport"] = $this->usermodel->displayallcreditinvoice($config["per_page"], $page,'sales','branch',$branchid);

 }
		


			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	public function  allinvoices()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 	$data["title"] ="ALL DEBTORS";
				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
				$config['base_url'] = base_url('Systemusers/allinvoices');
			$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','branch',$branchid,'id >',0,'credit>',0);


			
			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
						$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $data["salesreport"] = $this->usermodel->displayalldatathreeinvoicesAll($config["per_page"], $page,'sales','branch',$branchid,'id >',0,'credit>',0);


			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		public function allinvoices_sssssss()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   	$data["title"] ="ALL INVOICES";
				
				$config['base_url'] = base_url('Systemusers/allinvoices');
			
			
					$viewallcounters=$this->usermodel->populatuserpermissionsdataarray('cashiersales','viewallcounters',$userid);

 if( $viewallcounters==true){
			$config['total_rows'] = $this->usermodel->count_allcreditinvoice('sales','companyid',$companyid);
 }else{
	 
	 			$config['total_rows'] = $this->usermodel->count_allcreditinvoice('sales','branch',$branchid);

	 
 }

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
		 if( $viewallcounters==true){
		 $data["salesreport"] = $this->usermodel->displayallcreditinvoice($config["per_page"], $page,'sales','companyid',$companyid);
 }else{
	 
	 
	 		 $data["salesreport"] = $this->usermodel->displayallcreditinvoice($config["per_page"], $page,'sales','branch',$branchid);

 }
		


			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function getinvoivebysupplier()
	{ 
		
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$customer=$_GET['randomitemidentifier'];
		
		
		
		
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	   	$data["title"] ="ALL INVOICES";
		
		

				
				$config['base_url'] = base_url('Systemusers/allinvoices');
			
			//$config['total_rows'] = $this->usermodel->count_allcreditinvoicebysupplier('sales','companyid',$companyid,'customer',$customer);


														$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'customer',$customer,'credit<>',0);


			
			
			
		$config['per_page'] = '1000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		// $data["salesreport"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'sales','companyid',$companyid,'customer',$customer,'id <>',0);

		 //$data["salesreport"] = $this->usermodel->displayallcreditinvoicebycustomer($config["per_page"], $page,'sales','customer',$customer,'credit<>',0);
		 $data["salesreport"] = $this->usermodel->displayalldatathreeinvoices($config["per_page"], $page,'sales','companyid',$companyid,'customer',$customer,'credit<>',0);

			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	public function getallinvoivebysupplier()
	{ 
		
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$customer=$_GET['randomitemidentifier'];
		
		
		
		
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	   	$data["title"] ="ALL INVOICES";
		
		

				
				$config['base_url'] = base_url('Systemusers/allinvoices');
			
		//	$config['total_rows'] = $this->usermodel->count_allcreditinvoicebysupplier('sales','companyid',$companyid,'customer',$customer);

			$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'customer',$customer,'id >',0);


			
			
			
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
			$data["salesreport"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'sales','companyid',$companyid,'customer',$customer,'id >',0);

		 //$data["salesreport"] = $this->usermodel->displayallcreditinvoicebycustomer($config["per_page"], $page,'sales','companyid',$companyid,'customer',$customer);
		 ///$data["salesreport"] = $this->usermodel->displayalldatathreeinvoices($config["per_page"], $page,'sales','companyid',$companyid,'customer',$customer,'balance <',0);

			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	
	
	public function getinvoivebyref()
	{ 
		
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$invoice=$_GET['randomitemidentifier'];
		
		
		
		
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	   	$data["title"] ="ALL INVOICES";
		
		

				
				$config['base_url'] = base_url('Systemusers/allinvoices');
			
			$config['total_rows'] = $this->usermodel->count_allcreditinvoicebysupplier('sales','companyid',$companyid,'invoice',$invoice);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
		
		
		// $data["salesreport"] = $this->usermodel->displayallcreditinvoicebycustomer($config["per_page"], $page,'sales','companyid',$companyid,'invoice',$invoice);
	   $data['salesreport'] = $this->usermodel->populatemyinvoicebycode($invoice,$companyid);


			
			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	public function allcreditors()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 	$data["title"] ="ALL DEBTORS";
				
				$config['base_url'] = base_url('Systemusers/allcreditors');
			$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'id >',0,'credit <>',0);


			
			
		$config['per_page'] = '1000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
						$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $data["salesreport"] = $this->usermodel->displayalldatathreeinvoicesAll($config["per_page"], $page,'sales','companyid',$companyid,'id >',0,'credit <> ',0);


			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allcreditors',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	public function alldefaulters()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				$data["title"] ="OVERDUE CREDITORS";
				$config['base_url'] = base_url('Systemusers/alldefaulters');
			
														$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'due_date <',$mydate,'balance <',0);


			
			
		$config['per_page'] = '50000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		 $data["salesreport"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'sales','companyid',$companyid,'due_date <',$mydate,'balance <',0);


			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allinvoices',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function incoicepayments()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 $usertype = $data['usertype'];	
	  	$data["title"] ="RECEIVE PAYMENTS";
				
				$config['base_url'] = base_url('Systemusers/incoicepayments');
			
														$config['total_rows'] = $this->usermodel->count_allwheredatathree('sales','companyid',$companyid,'branch',$branchid,'balance <',0);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		 $data["salesreport"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'sales','companyid',$companyid,'branch',$branchid,'balance <',0);


			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/incoicepayments',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function viewgsummaryreportbycategory()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	    $clearedby = "all";
  // echo$fromdate = date("Y-m-d H:i:s", strtotime($this->input->post("fromdate")));

		  $branchname = $this->input->post("branchname");
		  $maincategory = "all";
		    $type = $this->input->post("type");
		  $view = $this->input->post("view");

	 $todate = $this->input->post("todate");
	  
	  	   $group = $this->input->post("group");
		
  $category = $this->input->post("category");
	     //$frotime="00:00:00";
				//	$totime="23:59:59";
	  	    $display = $this->input->post("display");

	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		  
		  
		  
		  
		  
		  
		
		  
		  
		  
				   $paymentstatus = $this->input->post("type");	
				
				
			
				$config['base_url'] = base_url('Systemusers/mysales');
			
							$config['total_rows'] = $this->usermodel->count_allsalesbydategroup('sales','userid',$user,$fromdate, $todate,$branchname,$category,$paymentstatus,$group,$clearedby);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
					$data['viewexpenses'] =false;
					$data['allcollections'] ="";

		
		
		
		
					$data['paidpurchase'] = null;

		
		
					$data['report']="yes";
		
		
					$data['user']=$user;
		$data['finaltodate']=$todate;
$data['finalfromdate']=$fromdate;


 $myusers="";
				if( $category!="all"){
									$allcategory = $this->usermodel->populateallarray('category','id',$category);

		
    $mycategory=strtoupper($allcategory[0]['name']);
						 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR ".$mycategory;

				}else{
					
					 $myusers="All Users";
					 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR  ALL CATEGORIES  ";
				}
				

	if( $branchname!="all"){
		
				$mybranch = $this->usermodel->populateallarray('branch','id',$branchname);
   $mybranchname=$mybranch[0]['name'];

						 $data['branchdata']=" ".$mybranchname;

				}else{
					
				
					 $data['branchdata']="All Branches/counters ";
				}
				







   $data["configuration"] =$this->usermodel->populateallarray('smsconfig','id',$companyid);
 

   $data["salesreport"] = $this->usermodel->displayallsalesbydatecbycategory($config["per_page"], $page,'sales',$companyid,$user,$fromdate, $todate,$branchname,$category,$paymentstatus,$group,$type,"all");

			$data['allcollections'] = false;
$data['paidbills'] = false;
			

	

	
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
						$data["group"]=$group;

				if( $group=="yes"){
									$this->load->view("userdata/mysalessummary",$data);

				}else{
					
						$this->load->view('userdata/'.$view,$data);

				}
				
				
				

		$this->load->view("template/footerpage");
	
	}
	
	
		public function viewgsummaryreportbyuser()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  		  	      $dontshowtotal=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dontshowtotal',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  
	   	  $clearance = $this->input->post("clearance");
	   	  $branch = $this->input->post("branch");

  // echo$fromdate = date("Y-m-d H:i:s", strtotime($this->input->post("fromdate")));

		  $branchname = $this->input->post("branchname");
		  $maincategory = $this->input->post("maincategory");
		    $type = $this->input->post("type");
		  $view = $this->input->post("view");
	 $clearedby = $this->input->post("clearedby");

	 $todate = $this->input->post("todate");
	  
	  	  $group = $this->input->post("group");

	     //$frotime="00:00:00";
				//	$totime="23:59:59";
	  	    $display = $this->input->post("display");

	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  $fromdate=trim($fromdate." ".$frotime);
	  	  $todate=$todate." ".$totime;
		  
		  
		  
		    $dailysalesonly=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dailysalesonly',$userid);
	  $mycurrentdate = strtotime(date($fromdate));
	  	$finaldate = strtotime(date($todate));
			$secs = (double)$finaldate-(double)$mycurrentdate;
	  	$days = ($secs / 86400);
							 $finaldays=round($days,0);
						
						
						
						
		
	
		 if( $dailysalesonly==true){
			 	  
				  $fromdate1 = $this->input->post("fromdate1");
	      $frotime1 = $this->input->post("frotime1");			
						
		  
		  	  $fromdate1=trim($fromdate1." ".$frotime1);
	
			 
			    if($fromdate <  $fromdate1){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The date selected ('.$fromdate.') can not be earlier than date of today ('.$fromdate1.'). You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 
			 
			 
			 
			 
			 
							
						   if($finaldays > 2){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 

		 }
		  
		  
		  
				  $paymentstatus = $this->input->post("paymentstatus");	
				$config['base_url'] = base_url('Systemusers/mysales');
			
							$config['total_rows'] = $this->usermodel->count_allsalesbydategroup('sales','userid',$user,$fromdate, $todate,$branchname,$maincategory,$paymentstatus,$group,$clearedby);

			
			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
					$data['viewexpenses'] = $this->usermodel->populateexpense($fromdate,$todate,$companyid,$branchname,"yes");
					
																	//populateexpense($fromdate,$todate,$companyid,$branch,$group){
			
					
					
					$data['allcollections'] ="";


		
		
		
		
					$data['paidpurchase'] = null;

		
		
					$data['report']="yes";
		
		
					$data['user']=$user;
		$data['finaltodate']=$todate;
$data['finalfromdate']=$fromdate;
$data['clearedby']=$clearedby;


 $myusers="";
				if( $user!="all"){
				$allusers=$this->usermodel->geteuser($user);
    $myusers=$allusers[0]['firstname'];
						 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR ".$myusers;

				}else{
					
					 $myusers="All Users";
					 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR  ALL USERS  ";
				}
				

	if( $branchname!="all"){
		
				$mybranch = $this->usermodel->populateallarray('branch','id',$branchname);
   $mybranchname=$mybranch[0]['name'];

						 $data['branchdata']=" ".$mybranchname;

				}else{
					
				
					 $data['branchdata']="All Branches/counters ";
				}





   $data["configuration"] =$this->usermodel->populateallarray('smsconfig','id',$companyid);
 
 
 

   $data["salesreport"] = $this->usermodel->displayallsalesbydategroup($config["per_page"], $page,'sales',$companyid,$user,$fromdate, $todate,$branchname,$maincategory,$paymentstatus,$group,$type,$clearedby);

			$data['allcollections'] = $this->usermodel->populatecollection($fromdate,$todate,$companyid,$branchname,"yes");

			

	

	
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
		
		$data["branchdata"]=$branch;

			$data['configuration']  = $this->usermodel->populateallarray('smsconfig','id',$companyid);

				$data["group"]=$group;
				
				//
				if( $clearance=="Yes"){
			$this->load->view("userdata/clearsales",$data);

				}else{
				if(( $group=="yes")||( $group=="yesbydate")) {
									$this->load->view("userdata/mysalessummary",$data);

				}else{
					
						$this->load->view('userdata/'.$view,$data);

				}
				}
				
				

		$this->load->view("template/footerpage");
	
	}
	
	
	
		public function viewgsummaryreportbyuser2()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	   
  // echo$fromdate = date("Y-m-d H:i:s", strtotime($this->input->post("fromdate")));

		  $branchname = $this->input->post("branchname");
		  $maincategory = $this->input->post("maincategory");
		    $type = $this->input->post("type");
		  $view = $this->input->post("view");

	 $todate = $this->input->post("todate");
	  
	  	  $group = $this->input->post("group");
		  

	     //$frotime="00:00:00";
				//	$totime="23:59:59";
	  	    $display = $this->input->post("display");

	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		  
		  
		  
		  
		  
		  
		  
		
		  
		  
		  
				  $paymentstatus = $this->input->post("paymentstatus");	
				$config['base_url'] = base_url('Systemusers/mysales');
			
							$config['total_rows'] = $this->usermodel->count_allsalesbydategroup('sales','userid',$user,$fromdate, $todate,$branchname,$maincategory,$paymentstatus);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
					$data['viewexpenses'] = false;
					$data['allcollections'] ="";
					//$this->usermodel->populateexpense($fromdate,$todate,$companyid);

		
		
		
		
					$data['paidpurchase'] = null;

		
		
					$data['report']="yes";
		
		
					$data['user']=$user;
		$data['finaltodate']=$todate;
$data['finalfromdate']=$fromdate;


 $myusers="";
				if( $user!="all"){
				$allusers=$this->usermodel->geteuser($user);
    $myusers=$allusers[0]['firstname'];
						 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR ".$myusers;

				}else{
					
					 $myusers="All Users";
					 $data['reporttype']="SUMMARY DAILY SALES REPORT FOR  ALL USERS  ";
				}
				

	if( $branchname!="all"){
		
				$mybranch = $this->usermodel->populateallarray('branch','id',$branchname);
   $mybranchname=$mybranch[0]['name'];

						 $data['branchdata']=" ".$mybranchname;

				}else{
					
				
					 $data['branchdata']="All Branches/counters ";
				}
				







   $data["configuration"] =$this->usermodel->populateallarray('smsconfig','id',$companyid);
 

   $data["salesreport"] = $this->usermodel->displayallsalesbydategroup($config["per_page"], $page,'sales',$companyid,$user,$fromdate, $todate,$branchname,$maincategory,$paymentstatus,$group,$type);

			$data['allcollections'] = false;

			

	

	
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
						$data["group"]=$group;

				if( $group=="yes"){
									$this->load->view("userdata/mysalessummary",$data);

				}else{
					
						$this->load->view('userdata/'.$view,$data);

				}
				
				
				

		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function viewgsummaryreportbytable()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		  	      $dailysalesonly=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dailysalesonly',$userid);

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	   $fromdate = $this->input->post("fromdate");
		  $branchname = $this->input->post("branchname");
		  $mytable = $this->input->post("mytable");

		  $view = $this->input->post("view");

	  $todate = $this->input->post("todate");
	  
	  	  	    $group = $this->input->post("group");

	  	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		  
	  
	  $mycurrentdate = strtotime(date($fromdate));
	  	$finaldate = strtotime(date($todate));
			$secs = $finaldate-$mycurrentdate;
	  	$days = ($secs / 86400)+1;
							 $finaldays=round($days,0);
							
	  
	  //
	  
	  
	  
	  
				  $paymentstatus = $this->input->post("paymentstatus");	
				$config['base_url'] = base_url('Systemusers/viewgsummaryreportbytable');
			
							$config['total_rows'] = $this->usermodel->count_allsalesbydategroup('sales','userid',$user,$fromdate, $todate,$branchname,$mytable,$paymentstatus,$group);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
					//$data['viewexpenses'] = $this->usermodel->populateexpense($fromdate,$todate,$companyid);
					$data['viewexpenses']="";
					
					$data['allcollections'] ="";
					//$this->usermodel->populateexpense($fromdate,$todate,$companyid);

		
  
 $data["salesreport"] = $this->usermodel->displaydailytables('sales',$companyid,$branchname,$fromdate, $todate,$mytable,$paymentstatus,$group);
 
 //$data["salesreport"] = $this->usermodel->displaydailytables('sales',$companyid,$branchid,$fromdate,$todate,$mytable,$paymentstatus);
			//$data['allcollections'] = $this->usermodel->populatecollection($fromdate,$todate,$companyid);
	
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =count((array)$data["salesreport"]);
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/'.$view,$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
		public function viewverifiedmpesasales()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	   $fromdate = $this->input->post("fromdate");
		  $branchname = $this->input->post("branchname");
	  $todate = $this->input->post("todate");
				//
				  $branch = $this->input->post("branchname");
					  $download = $this->input->post("download");

 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
					  
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		$config['base_url'] = base_url('Systemusers/viewverifiedmpesasales');
			
			
							$config['total_rows'] = $this->usermodel->count_allmpesasalesbydate('mpesasales','userid',$user,$fromdate, $todate,$branchname);

			
			
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        $data["salesreport"] = $this->usermodel->displayallmpesasalesbydate($config["per_page"], $page,'mpesasales','userid',$user,$fromdate, $todate,$branchname,$download);

			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
				$data["finaltodate"]=$todate;
				$data["finalfromdate"]=$fromdate;
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

if($branch=="all"){
	$branchdata="All Counter/Branches";
}else{
	          		$allbranches = $this->usermodel->populateallarray('branch','id',$branch);
	$branchdata=$allbranches[0]['name'];

	
}

if($user=="all"){
	$user="All Users";
}else{
	          		$myusers = $this->usermodel->populateallarray('people','id',$user);
	$user=$myusers[0]['firstname'];

	
}


				$data["branch"]=$branch;


				$data["user"]=$user;
				$data["branchdata"]=$branchdata;
//
			$this->load->view('userdata/viewmympesa',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function viewtillbyuser()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $user = $this->input->post("user");
	   $fromdate = $this->input->post("fromdate");
		  $branchname = $this->input->post("branchname");

	  $todate = $this->input->post("todate");
				
				$config['base_url'] = base_url('Systemusers/viewtillbyuser');
			
			
			
			 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
					  
	  $fromdate=$fromdate." ".$frotime;
	  	  $todate=$todate." ".$totime;
		 
			
			
			
				

			
			
			
			
			
			
			
							$config['total_rows'] = $this->usermodel->count_allmpesasalesbydate('tillcollection','userid',$user,$fromdate, $todate,$branchname);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        $data["salesreport"] = $this->usermodel->displayallmpesasalesbydate($config["per_page"], $page,'tillcollection','userid',$user,$fromdate, $todate,$branchname);

			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
public function viewmympesa()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
   
   
   $mpesacode="";
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewmympesa');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }
   if (isset($_POST['code'])){
	    $code = $this->input->post("code");
    $mpesacode=$code;
	
	

   }else{
	   
	   $mpesacode=""; 
	
   }
	$data["code"]=$mpesacode;

		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									$config['total_rows'] = $this->usermodel->count_allsalesbydate('mpesasales','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			        $data["salesreport"] = $this->usermodel->displayallsalesbydate($config["per_page"], $page,'mpesasales','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewmympesa',$data);
				
		$this->load->view("template/footerpage");
	
	}
		public function mergempesa()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
   
   
   $mpesacode="";
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/mergempesa');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }
   if (isset($_POST['code'])){
	    $code = $this->input->post("code");
    $mpesacode=$code;
	
	

   }else{
	   
	   $mpesacode=""; 
	
   }
	$data["code"]=$mpesacode;

		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									$config['total_rows'] = $this->usermodel->count_allsalesbydate('mergedmpesa','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);


			
			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			        $data["salesreport"] = $this->usermodel->displayallsalesbydate($config["per_page"], $page,'mergedmpesa','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);

			
         $this->load->view("template/headerpagemin");
		//$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/mergempesa',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	public function viewtill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
   
   
   $mpesacode="";
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewtill');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }

		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);
		
									$config['total_rows'] = $this->usermodel->count_allsalesbydate('tillcollection','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			        $data["salesreport"] = $this->usermodel->displayallsalesbydate($config["per_page"], $page,'tillcollection','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function mysales()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/mysales');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		
		$pendingisdefault =$this->usermodel->populatuserpermissionsdataarray('cashiersales','pendingisdefault ',$userid);
 	   $clearsalesisdefault =$this->usermodel->populatuserpermissionsdataarray('cashiersales','clearsalesisdefault ',$userid);

		 
		  if( $pendingisdefault==true){
		   redirect('user/mypendingsales');
			 return false;
			  
		  }
		 
		  if( $clearsalesisdefault==true){
		   redirect('user/clearsales');
			 return false; 
		  }
		 
		 
		 
		   $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									$config['total_rows'] = $this->usermodel->count_allsalesbydate('sales','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);


			
			
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			        $data["salesreport"] = $this->usermodel->displayallsalesbydateCashiersales($config["per_page"], $page,'sales','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);
								
									//var_dump(	 $data["salesreport"]);
								
		
								$data['allcollections'] =false;
//$data['viewexpenses'] =false;
					
								//$data['allcollections'] = $this->usermodel->populatecollection($finalstartdate,$finalendate,$companyid);

						       $data["viewexpenses"] = $this->usermodel->displayallourexpenses($finalstartdate, $finalendate,$companyid);
							   
								$data['finalendate'] =$finalendate;



       
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
		
			$this->load->view('userdata/mysales',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		public function viewonlineorders()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/mysales');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
								$config['total_rows'] = $this->usermodel->count_allsalesbydate('sales','salestype',"order",$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);


			
			
		$config['per_page'] = '30';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			        $data["salesreport"] = $this->usermodel->displayallsalesbydateCashiersales($config["per_page"], $page,'sales','type',"order",$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);
								$data['allcollections'] =false;
//$data['viewexpenses'] =false;
					
								//$data['allcollections'] = $this->usermodel->populatecollection($finalstartdate,$finalendate,$companyid);

						       $data["viewexpenses"] = $this->usermodel->displayallourexpenses($finalstartdate, $finalendate,$companyid);
							   
							



         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/clearsales',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
		public function clearsales()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/clearsales');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 		$viewallcounters=$this->usermodel->populatuserpermissionsdataarray('cashiersales','viewallcounters',$userid);

		 
		 //
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			if( $viewallcounters==true){
	$config['total_rows'] = $this->usermodel->count_allsalesbydatecashier('sales','companyid',$companyid,$finalstartdate, $finalendate,"all",$maincategory);

			}else{
				$config['total_rows'] = $this->usermodel->count_allsalesbydatecashier('sales','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);
	
			}


			
			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;
	if( $viewallcounters==true){
			
			$data["salesreport"] = $this->usermodel->displayallsalesbydatecashier($config["per_page"], $page,'sales','companyid',$companyid,$finalstartdate, $finalendate,"all",$maincategory);
	
			}else{
			        $data["salesreport"] = $this->usermodel->displayallsalesbydatecashier($config["per_page"], $page,'sales','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);

			}

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/clearsales',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		
		public function mergebill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$config['base_url'] = base_url('Systemusers/mergebill');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									//$config['total_rows'] = $this->usermodel->count_allsalesbydatecashier('splitbillmaster','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);

		   	   $clearallsales=$this->usermodel->populatuserpermissionsdataarray('cashiersales','clearallsales',$userid);

			   

			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
				$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		if( $clearallsales==true){
					        $data["salesreport"] = $this->usermodel->displayallsalesbytype($config["per_page"], $page,'splitbillmaster','branch',$branchname,$finalstartdate, $finalendate,"merge",$companyid);

		}else{
					        $data["salesreport"] = $this->usermodel->displayallsalesbydate($config["per_page"], $page,'splitbillmaster','userid',$userid,$finalstartdate, $finalendate,"merge",$companyid);
	
		}
		
						$config['total_rows'] =count((array)$data["salesreport"] );

		$this->pagination->initialize($config);
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			       // $data["salesreport"] = $this->usermodel->displayallsalesbydatecashier($config["per_page"], $page,'splitbillmaster','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);


 
			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/mergebill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
		public function splitbill()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$config['base_url'] = base_url('Systemusers/splitbill');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									//$config['total_rows'] = $this->usermodel->count_allsalesbydatecashier('splitbillmaster','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);

		   	   $clearallsales=$this->usermodel->populatuserpermissionsdataarray('cashiersales','clearallsales',$userid);

			   

			
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
				$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		if( $clearallsales==true){
					        $data["salesreport"] = $this->usermodel->displayallsalesbytype($config["per_page"], $page,'splitbillmaster','branch',$branchname,$finalstartdate, $finalendate,"split",$companyid);

		}else{
					        $data["salesreport"] = $this->usermodel->displayallsalesbydate($config["per_page"], $page,'splitbillmaster','userid',$userid,$finalstartdate, $finalendate,"split",$companyid);
	
		}
		
						$config['total_rows'] =count((array)$data["salesreport"] );

		$this->pagination->initialize($config);
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        //$data["salesreport"] = $this->usermodel->displayallbydate($config["per_page"], $page,'sales','userid',$userid,'dateposted',$mydate);;

			       // $data["salesreport"] = $this->usermodel->displayallsalesbydatecashier($config["per_page"], $page,'splitbillmaster','companyid',$companyid,$finalstartdate, $finalendate,$branchname,$maincategory);


 
			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/mergebill',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewdailycollections()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewdailycollections');
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
		 }
		 
		 
				
		 
			 $data['branchid'] = $session_data['branchid'];
	 $branchname = $data['branchid'];
	 $maincategory="all";
							//$config['total_rows'] = $this->usermodel->count_allwheredatabydate('sales','userid',$userid,'dateposted',$mydate);

			
									$config['total_rows'] = $this->usermodel->count_dailycollectionsbydate('dailycollections',$companyid,$branchname,$finalstartdate, $finalendate);


			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		//displaydailycollectionbydate($limit, $start,$database,$companyid,$branchid,$startdate,$enddate) 
		
     

			        $data["collections"] = $this->usermodel->displaydailycollectionbydate($config["per_page"], $page,'dailycollections',$companyid,$branchname,$finalstartdate, $finalendate);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewdailycollections',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function myholdingsales()
	{ 
	
		
		
		
		
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $type = $data['usertype'];
	 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');
		$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		
	 
	 
	 
	 			 		   	   $clearallsales=$this->usermodel->populatuserpermissionsdataarray('cashiersales','clearallsales',$userid);

	 
	 
	 
	 
	 
	 
	 
	 
	 
				
				$config['base_url'] = base_url('Systemusers/myholdingsales');
			
			
			
			if( $clearallsales==true){
							$config['total_rows'] = $this->usermodel->count_allwheredatabyorderdateHold('sales_holding','branch',$branchid,$finalstartdate,$finalendate,$type);

		}else{
							$config['total_rows'] = $this->usermodel->count_allwheredatabyorderdateHold('sales_holding','userid',$userid,$finalstartdate,$finalendate,$type);
	
		}
		
		
		
			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		

				if( $clearallsales==true){
        $data["salesreport"] = $this->usermodel->displayallbydateorderHold($config["per_page"], $page,'sales_holding','branch',$branchid,$finalstartdate,$finalendate,$type);

		}else{
        $data["salesreport"] = $this->usermodel->displayallbydateorderHold($config["per_page"], $page,'sales_holding','userid',$userid,$finalstartdate,$finalendate,$type);
	
		}
		
			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/myholding',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function mypendingsales()
	{ 
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
				
				$config['base_url'] = base_url('Systemusers/mypendingsales');
			
			
							$config['total_rows'] = $this->usermodel->count_allwheredatabyorderdate('sales','userid',$userid,$finalstartdate,$finalendate,'branch',$branchid);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        $data["salesreport"] = $this->usermodel->displayallbydateorder($config["per_page"], $page,'sales','userid',$userid,$finalstartdate,$finalendate,'branch',$branchid);

			//
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/myorder',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
		public function viewmyorder()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewmyorder');
			
			
							$config['total_rows'] = $this->usermodel->count_allwheredatabydate('outgoingstock','userid',$userid,'date',$mydate);

			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		
        $data["viewincomingstock"] = $this->usermodel->displayallbydate($config["per_page"], $page,'outgoingstock','userid',$userid,'date',$mydate);

			
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewoutgoingstock',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function viewallorder()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewallorder');
			
	$config['total_rows'] = $this->usermodel->count_allwhere('outgoingstock','companyid',$companyid);

			
			
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		        $data["viewincomingstock"] = $this->usermodel->displayall($config["per_page"], $page,'outgoingstock','companyid',$companyid);

		

		
			
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewoutgoingstock',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		function createRandomPassword1() {
				$chars = "".time()."ABCDEFGHIJKL8MNOP6702389QRSTUVWXYZLMNPQRSTUVWXY012345678932".time()."3202345678945ABCDEFGHJK6677LMNPQRSTUVWXYZ3210123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

	//$chars = "0032323032320232320234567894532421312314253252412312353253256325213213546121425453553245355ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	//$chars = '2342355ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+';

	srand((int)microtime()*100000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 15) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}
	
	
	
	
	
	
	
	
	
	public function viewtimerreportbyuser()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");

				$branchname = $this->input->post("branchname");

			  $view = $this->input->post("view");

	$finalfromdate=$fromdate;
	$finaltodate=$todate;
		$data['timer'] = $this->usermodel->viewtimerreportbyuser($finalfromdate,$finaltodate,$companyid,$user,$branchname);
		
				$data['user']=$user;
$data['links']="";
$data['total_rows']=count((array)$data['timer']);
				$this->load->view('userdata/viewtimer',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewgroupreceiptreportbyuser()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  	  	  $groupuser = $this->input->post("groupuser");

	  
	  
	  
	  
	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  $maincategory = $this->input->post("maincategory");
			  			  $branchname = $this->input->post("branchname");
			  			  $group = $this->input->post("group");

			  $view = $this->input->post("view");
			  $paymentstatus = $this->input->post("paymentstatus");

		$this->load->view("template/tableheader");
	//$finalfromdate=$fromdate;
	//$finaltodate=$todate;
	
			 
	  $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		     $dailysalesonly=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dailysalesonly',$userid);
	  $mycurrentdate = strtotime(date($fromdate));
	  	$finaldate = strtotime(date($todate));
			$secs = $finaldate-$mycurrentdate;
	  	$days = ($secs / 86400);
							 $finaldays=round($days,0);
						
	  
		  

		 if( $dailysalesonly==true){
			 
			 	  $fromdate1 = $this->input->post("fromdate1");
	      $frotime1 = $this->input->post("frotime1");			
						
		  
		  	  $fromdate1=trim($fromdate1." ".$frotime1);
	
			 
			    if($finalfromdate <  $fromdate1){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The date selected ('.$finalfromdate.') can not be earlier than date of today ('.$fromdate1.'). You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 
			 
			 
			 
							
						   if($finaldays > 2){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 

		 }
		  
		 
		 
		 
		 
		 
		$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuserDetails("","",$finalfromdate,$finaltodate,$type,$companyid,$user,$maincategory,$branchname,$group,$groupuser,$paymentstatus);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']=$user;
	$data['group']=$group;
		$data['paymentstatus']=$paymentstatus;

	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;

				$this->load->view('userdata/viewgroupreceiptreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	public function viewgroupreceiptreportbyuserMergedRooms()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  	  	  $groupuser = $this->input->post("groupuser");

	  
	  
	  
	  
	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  $maincategory = $this->input->post("maincategory");
			  			  $branchname = $this->input->post("branchname");
			  			  $group = $this->input->post("group");

			  $view = $this->input->post("view");
			  $paymentstatus = $this->input->post("paymentstatus");

		$this->load->view("template/tableheader");
	//$finalfromdate=$fromdate;
	//$finaltodate=$todate;
	
			 
	  $finalfromdate=$fromdate." ".$frotime;
	  	 $finaltodate=$todate." ".$totime;
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		     $dailysalesonly=$this->usermodel->populatuserpermissionsdataarray('cashiersales','dailysalesonly',$userid);
	  $mycurrentdate = strtotime(date($fromdate));
	  	$finaldate = strtotime(date($todate));
			$secs = $finaldate-$mycurrentdate;
	  	$days = ($secs / 86400);
							 $finaldays=round($days,0);
						
	  
		  

		 if( $dailysalesonly==true){
			 
			 	  $fromdate1 = $this->input->post("fromdate1");
	      $frotime1 = $this->input->post("frotime1");			
						
		  
		  	  $fromdate1=trim($fromdate1." ".$frotime1);
	
			 
			    if($finalfromdate <  $fromdate1){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The date selected ('.$finalfromdate.') can not be earlier than date of today ('.$fromdate1.'). You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 
			 
			 
			 
							
						   if($finaldays > 2){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You dont have right to view sales for more than two days. Try again</div>');
								
								 redirect('user/mysales');
								 
								 return false;
					 

						 } 

		 }
		  
		 
		 
		 
		 
		 
		$data['salesreport'] = $this->usermodel->viewproductsalesreportbyuserDetailsMergedRooms("","",$finalfromdate,$finaltodate,$type,$companyid,$user,$maincategory,$branchname,$group,$groupuser,$paymentstatus);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']=$user;
	$data['group']=$group;
		$data['paymentstatus']=$paymentstatus;

	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;

				$this->load->view('userdata/viewgroupreceiptreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	public function viewdeliveryitemsbycustomer()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	  //$totime="23:59:59";
	$user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $group = $this->input->post("group");
				$this->load->view("template/headerpagemin");
			  $status = $this->input->post("status");
			  			  $branchname = $this->input->post("branchname");

			  $view = $this->input->post("view");

		$this->load->view("template/tableheader");
		
		
		
		
				$myuser = explode(':=',$this->input->post("user"));

 
  //$user = htmlspecialchars(trim($myuser[0]));
   
		
		
					
 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	
		
	 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		
		
	
		$data['viewlease'] = $this->usermodel->viewdeliveryitemsbycustomer($finalfromdate,$finaltodate,$group,$companyid,$user,$status,$branchname);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']=$user;

				$data['links']=1;
								$data['total_rows']=1;


				$this->load->view('userdata/viewparceldelivery',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	public function viewleaseditemsbycustomer()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	  //$totime="23:59:59";
	 // $myuser = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $group = $this->input->post("group");
				$this->load->view("template/headerpagemin");
			  $status = $this->input->post("status");
			  			  $branchname = $this->input->post("branchname");

			  $view = $this->input->post("view");

		$this->load->view("template/tableheader");
		
		
		
		
				$myuser = explode(':=',$this->input->post("user"));

 
  $user = htmlspecialchars(trim($myuser[0]));
   
		
		
					
 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	
		
	 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		
		
	
		$data['viewlease'] = $this->usermodel->viewleaseditemsbycustomer($finalfromdate,$finaltodate,$group,$companyid,$user,$status,$branchname);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']=$user;

				$data['links']=1;
								$data['total_rows']=1;


				$this->load->view('userdata/viewlease',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewleaseditemsmovement()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	  //$totime="23:59:59";
	
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $group = $this->input->post("group");
				$this->load->view("template/headerpagemin");
			  $status = $this->input->post("status");
			  			  $branchname = $this->input->post("branchname");
			  			  $movement = $this->input->post("movement");

			  $view = $this->input->post("view");

		$this->load->view("template/tableheader");

	
					
 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	
		
	 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		  
		  
		$data['viewlease'] = $this->usermodel->viewleaseditemsmovement($finalfromdate,$finaltodate,$group,$companyid,$status,$branchname,$movement);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']="all";

				$data['links']=1;
								$data['total_rows']=1;


				$this->load->view('userdata/viewlease',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	 
 public function printleasediteminvoice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= $this->usermodel->populateall('purchaseorderlist','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('lease','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printleaseinvoice', $data);
		
	}
  }
 
	
	
 public function printparceliteminvoice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= $this->usermodel->populateall('purchaseorderlist','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('lease','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printparcelinvoice', $data);
		
	}
  }
 
	
	
	 
 public function printleaseditem() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= $this->usermodel->populateall('purchaseorderlist','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('lease','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printlease', $data);
		
	}
  }
 	 
 public function printparcelitem() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= $this->usermodel->populateall('purchaseorderlist','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('parceldelivery','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printparcel', $data);
		
	}
  }
 
	
		
 public function printparcelitemdelivery() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= $this->usermodel->populateall('purchaseorderlist','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('parceldelivery','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printparcelitemdelivery', $data);
		
	}
  }
 
	 
 public function printreadingorder() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);
		$data['viewsales']= false;

$data['viewreceipt'] = $this->usermodel->populateallarraylease('openorders','id',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreadingorder', $data);
		
	}
  }
 
	
		 
 public function printvouchers() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	    $customer = $_GET['customer'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];

    		
									//$data['viewsales']= $this->usermodel->populateall('lease','invoice',$invoiceid);

$data['viewreceipt'] = $this->usermodel->populateallarraylease('voucher','invoice',$invoiceid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$data['customer']=$customer;
		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printvoucher', $data);
		
	}
  }
 
	
	
	
	public function viewleaseditemsbyuser()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	  //$totime="23:59:59";
	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $group = $this->input->post("group");
				$this->load->view("template/headerpagemin");
			  $status = $this->input->post("status");
			  			  $branchname = $this->input->post("branchname");
			  			  $product = $this->input->post("product");

			  $view = $this->input->post("view");

		$this->load->view("template/tableheader");
	//$finalfromdate=$fromdate;
	//$finaltodate=$todate;
	  			
 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	
		
	 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		  
		  
		  
		$data['viewlease'] = $this->usermodel->viewleaseditemsbyuser($finalfromdate,$finaltodate,$group,$companyid,$user,$status,$branchname,$product);
		//var_dump($data['salesreport']);
		//exit;
				$data['user']=$user;

				$data['links']=1;
								$data['total_rows']=1;


				$this->load->view('userdata/viewlease',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewproductsalesreportbyuser()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	 // $totime="23:59:59";
	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  			  	  $branchname = $this->input->post("branchname");

	  $user = $this->input->post("user");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  $maincategory = $this->input->post("maincategory");
			  $view = $this->input->post("view");
			  $group = $this->input->post("group");

		$this->load->view("template/tableheader");
	
	
	 $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
		  		$data['group']=  $group;
	$myuser="all";
	if($user=="all"){
		$myuser="all1";	
		
	}else{
	$myuser=$user;		
	}
			//$data['salesreport'] = $this->usermodel->viewsalesreport($finalfromdate,$finaltodate,$type,$companyid,$maincategory,$branchname);
$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="DETAILED DAILY SALES PER PERSON EPORT.";

		$data['salesreport'] = $this->usermodel->viewproductsalesreportbymyuser($finalfromdate,$finaltodate,$type,$companyid,$user,$maincategory,$branchname);
	$data['user']=$myuser;

				$this->load->view('userdata/viewsalesreport',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function accounting()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['paymentmethodes']= $this->usermodel->populateall('paymentmethodes','companyid',$companyid);


				$this->load->view('userdata/accounting',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function deliverynote()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['deliverynote']= $this->usermodel->populateall('paymentmethodes','companyid',$companyid);


				$this->load->view('userdata/deliverynote',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	public function purchaseorder()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
				$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');

			
			$finalsalesid=0;
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();


 }else{
$finalsalesid=$sale[0]['invoice'];  
									$data['purchaseorder']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);

 }
 $data['finalsalesid']=$finalsalesid;
		
		
		
		
$data['purchaseorder']= $this->usermodel->populateall('paymentmethodes','companyid',$companyid);


				$this->load->view('userdata/purchaseorder',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function payment()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");


				$this->load->view('userdata/payment');
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
		public function glgroups()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['glgroups']= $this->usermodel->populateall('glgroups','companyid',$companyid);


				$this->load->view('userdata/glgroups',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	public function kitchenprinter()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$database="robipos";
	 	 $database="robisear_myerp";

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
											$data['configuration']= $this->usermodel->populateallarray('smsconfig','id',$companyid);
									
									
									$data['printers']= $this->usermodel->populateall('printers','companyid',$companyid);



				$this->load->view('userdata/kitchenprinter',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function bulkupdate()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$database="robipos";
	 	 $database="robisear_myerp";

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['bulkupdate']= $this->usermodel->populatealltables($database);


				$this->load->view('userdata/bulkupdate',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function transferdeals()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$database="robipos";
	 	 $database="robisear_myerp";

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['bulkupdate']= $this->usermodel->populatealltables($database);


				$this->load->view('userdata/transferdeals',$data);
		$this->load->view("template/footerpage");
	}
	
	public function allaccounting()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['allaccounting']= $this->usermodel->populateall('glaccounts','companyid',$companyid);


				$this->load->view('userdata/allaccounting',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function accounttype()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];



				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
									$data['accounttype']= $this->usermodel->populateall('accounttype','companyid',$companyid);


				$this->load->view('userdata/accounttype',$data);
		$this->load->view("template/footerpage");
	}
	
	
	public function viewlowproductbycode()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
		$data['viewwarningproducts'] = $this->usermodel->viewlowproductbycode($code);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewwarningproductsgroups',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewlowproductbycodestore()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));
			 $branchid = htmlspecialchars(($this->input->post("branchid")));


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
		$data['viewwarningproducts'] = $this->usermodel->viewlowproductbycodestore($code,$branchid);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewwarningstoreproductsgroups',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewexpiredproducts()
	
	{ $session_data = $this->session->userdata('logged_in');

  
         $currentdate = date('Y-m-d');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $supplier = $this->input->post("supplier");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['links'] =0;
		$data['total_rows'] =0;
					$data['viewwarningproducts']  = $this->usermodel->populatealldatanoarraythree('products','expdate <>', '0000-00-00','expdate <', $currentdate,'companyid', $companyid);			   

		//$data['viewwarningproducts'] = $this->usermodel->viewlowproductbysupplierstore($supplier,$companyid);;
		//var_dump($data['viewwarningproducts']);
		//exit;

				$this->load->view('userdata/viewwarningproducts',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewexpiredstoclist()
	
	{ $session_data = $this->session->userdata('logged_in');

  
         $currentdate = date('Y-m-d');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $supplier = $this->input->post("supplier");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['links'] =0;
		$data['total_rows'] =0;
					$data['viewproducts']  = $this->usermodel->populatealldatanoarraythree('productlist','expdate <>', '0000-00-00','expdate <', $currentdate,'companyid', $companyid);			   

		//$data['viewwarningproducts'] = $this->usermodel->viewlowproductbysupplierstore($supplier,$companyid);;
		//var_dump($data['viewwarningproducts']);
		//exit;

				$this->load->view('userdata/viewlowstore',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewlowproductbysupplierstore()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $supplier = $this->input->post("supplier");
	  $branchid = $this->input->post("branchid");
	  $download = $this->input->post("download");
	  $category = $this->input->post("category");


	  $orderamount = $this->input->post("orderamount");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewwarningproducts'] = $this->usermodel->viewlowproductbysupplierstore($supplier,$orderamount,$companyid,$branchid,$download,$category);
		//var_dump($data['salesreport']);
		//exit;


///
 $myusers="";
		
				

	if( $branchid!="all"){
		
				$mybranch = $this->usermodel->populateallarray('branch','id',$branchid);
   $mybranchname=$mybranch[0]['name'];

						 $data['branchdata']=" ".$mybranchname;

				}else{
					
				
					 $data['branchdata']="All Branches/counters ";
				}






   $data["configuration"] =$this->usermodel->populateallarray('smsconfig','id',$companyid);
 

				if( $supplier!="all"){
					
							if( $supplier!="all"){
				$allusers=$this->usermodel->geteuser($supplier);
    $myusers=$allusers[0]['company']." ";
						 $data['reporttype']="LPO  STOCK  REQUEST  FOR  ".$myusers;

				}else{
					
					 $myusers="All Suppliers";
					 $data['reporttype']="LPO  STOCK  REQUEST  FOR ALL SUPPLIERS ";
				}
					
					
					
									$this->load->view('userdata/viewwarningstoreproductsitems',$data);

				}else{
					
							if( $supplier!="all"){
				$allusers=$this->usermodel->geteuser($supplier);
    $myusers=$allusers[0]['company'];
						 $data['reporttype']="SUMMARY LOW STOCK REPORT  FOR  ".$myusers;

				}else{
					
					 $myusers="All Suppliers";
					 $data['reporttype']="SUMMARY LOW STOCK REPORT  FOR ALL SUPPLIERS ";
				}
					
					
					
								$this->load->view('userdata/viewwarningstoreproductsgroups',$data);
	
				}



		$this->load->view("template/footerpage");
	}
	
	
	public function viewlowproductbysupplier()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $supplier = $this->input->post("supplier");
	  $category = $this->input->post("category");

	  $orderamount = $this->input->post("orderamount");
	  $download = $this->input->post("download");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
		$data['viewwarningproducts'] = $this->usermodel->viewlowproductbysupplier($supplier,$orderamount,$companyid,$download,$category);
		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewwarningproductsgroups',$data);
		$this->load->view("template/footerpage");
	}
	
	
	public function viewallproductbycategory()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $category = $this->input->post("category");
	  $branchid = $this->input->post("branchid");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	
	   if($branchid=="Main"){
			   		   							//$data['viewwarningproducts'] = $this->usermodel->populateall('products','category', $category);
			  				 $data['viewwarningproducts'] = $this->usermodel->populatealldatacategories('products','category', $category,'id > ', 0,'companyid', $companyid);			   

		   }else{
			  				 $data['viewwarningproducts'] = $this->usermodel->populatealldatacategories('productlist','category', $category,'branch', $branchid,'companyid', $companyid);			   
 
		   }  
		   
	$data['category']=$category;
		 
	
	
								//$data['viewwarningproducts']= $this->usermodel->populateall('products','category',$category);

		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/allproductsbycategory',$data);
		$this->load->view("template/footerpage");
	}
	
	public function viewallproductbysupplier()
	
	{ $session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $supplier = $this->input->post("supplier");
	  $branchid = $this->input->post("branchid");


				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
	
	
	
		if ($branchid=="Main")
						   {
								$data['viewwarningproducts']= $this->usermodel->populateall('products','supplier',$supplier);
   
							   
						   }else{

							 $data['viewwarningproducts'] = $this->usermodel->populatealldatanoarray('productlist','supplier', $supplier,'branch', $branchid);

							}
	
	
	
	
	
	
	

		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/allproductsbysupplier',$data);
		$this->load->view("template/footerpage");
	}
	
	  public function config() {
	  
	 
$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
$data['userid']=$companyid;
		 $this->load->view('userdata/config', $data);
		$this->load->view("template/footerpage");
		
	
  }
  
	
	
	
	
	public function viewproductbysubcategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 //$frotime="00:00:00";
	  //$totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
			 $category = htmlspecialchars(trim($this->input->post("category")));
	  $group = $this->input->post("group");

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchname");
				  
$user="NA";
	$data['user']=$user;
		$this->load->view("template/tableheader");
	
	
		  
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;

		  $data['reporttype']="DETAILED DAILY SALES   PER CATEGORY REPORT";

		  
	$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['type']=$type;
	$data['companyid']=$companyid;

		$data['mybranchid']=$branchname;
			$data['group']="yes";

	//
	
				$data['sales'] = $this->usermodel->getesalesbyproductcategory($finalfromdate,$finaltodate,$companyid,$branchname,$category);
					//$data['oursales'] = $this->usermodel->getesalesbyproductbydepartment($finalfromdate,$finaltodate,$companyid,$branchname);

		//var_dump($data['salesreport']);
		//exit;

				$this->load->view('userdata/viewsalepercategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function searchserialreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	  //$totime="23:59:59";
	  
	   
			 $code = htmlspecialchars(trim($this->input->post("code")));




				$this->load->view("template/headerpagemin");
			  	  $category = $this->input->post("category");
			  	 $branch = $this->input->post("branchname");

		$this->load->view("template/tableheader");

	
		  		  $finaltodate = date('Y-m-d 00:00:00');
		  		  $finalfromdate = date('Y-m-d 23ss:59:59');


$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$user="NA";
	$data['user']=$user;
		$data['group']=  "no";
		$data['links']=  "";
		$data['total_rows']=  "";

	
	 $data['reporttype']="SERIAL SALES  REPORT";

		
			$data['salesreport'] = $this->usermodel->searchserialreport($companyid,$code,$branch,$category);


				$this->load->view('userdata/viewsalesreport',$data);
				
		
				
			
	


		 
				
				
				
				
				
				
				
				
				
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	public function viewproductsalesreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	  //$totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
			 $code = htmlspecialchars(($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  	  $category = $this->input->post("category");

	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchname");
			  	  $daterange = $this->input->post("daterange");
			  	  $group = $this->input->post("group");
			  	  $reporttype = $this->input->post("reporttype");
			  	  $transactiontype = $this->input->post("transactiontype");

		$this->load->view("template/tableheader");

	
		  
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$user="NA";
	$data['user']=$user;
		$data['group']=  $group;
if(	$reporttype=="Sales"){
	
	 $data['reporttype']="DETAILED DAILY SALES  PER PRODUCT REPORT";

			$data['salesreport'] = $this->usermodel->viewserialproductsalesreport($finalfromdate,$finaltodate,$type,$companyid,$code,$branchname,$daterange,$category,$group,$transactiontype);


				$this->load->view('userdata/viewsalesreport',$data);
				
			
}else{
	
	
	 $data['reporttype']="DETAILED DAILY SALES/STOCK MOVEMENT PRODUCT REPORT";

		
			$data['salesreport'] =false;

			//$this->usermodel->viewserialproductsalesreport($finalfromdate,$finaltodate,$type,$companyid,$code,$branchname,$daterange,$category,$group,$transactiontype);
					$data['viewincomingstock'] = $this->usermodel->viewallproductmovements($finalfromdate,$finaltodate,$daterange,$branchname,$companyid,$code);


				$this->load->view('userdata/viewstockmovement',$data);
				
		
				
			
	
}

		 
				
				
				
				
				
				
				
				
				
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	public function viewproductsalesreportold()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	// $frotime="00:00:00";
	  //$totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
			 $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  	  $category = $this->input->post("category");

	  $type = $this->input->post("type");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchname");
			  	  $daterange = $this->input->post("daterange");
			  	  $group = $this->input->post("group");
			  	  $reporttype = $this->input->post("reporttype");
			  	  $transactiontype = $this->input->post("transactiontype");

		$this->load->view("template/tableheader");

	
		  
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$user="NA";
	$data['user']=$user;
		$data['group']=  $group;
if(	$reporttype=="Sales"){
	
	 $data['reporttype']="DETAILED DAILY SALES  PER PRODUCT REPORT";

		
			$data['salesreport'] = $this->usermodel->viewserialproductsalesreportold($finalfromdate,$finaltodate,$type,$companyid,$code,$branchname,$daterange,$category,$group,$transactiontype);


				$this->load->view('userdata/viewsalesreportold',$data);
				
			
}else{
	
	
	 $data['reporttype']="DETAILED DAILY SALES/STOCK MOVEMENT PRODUCT REPORT";

		
			$data['salesreport'] = $this->usermodel->viewserialproductsalesreportold($finalfromdate,$finaltodate,$type,$companyid,$code,$branchname,$daterange,$category,$group,$transactiontype);
					$data['viewincomingstock'] = $this->usermodel->viewallproductmovementsold($finalfromdate,$finaltodate,$daterange,$branchname,$companyid,$code);


				$this->load->view('userdata/viewstockmovementold',$data);
				
		
				
			
	
}

		 
				
				
				
				
				
				
				
				
				
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewmergedsplittedbill()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branch = $this->input->post("branch");
				    	  $download = $this->input->post("download");
		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']="";
		$data['salesreport'] = $this->usermodel->viewmergedsplittedbill($fromdate,$todate,$companyid,$code,$branch,$download);
				$data['total_rows']=count((array)$data['salesreport']);
				$this->load->view('userdata/mergebill',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
		public function viewdamagedproducts()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));
	 // $supplier = $this->input->post("supplier");
//




 $suppliers1 = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers1[0]));






	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branch = $this->input->post("branch");
				    	  $download = $this->input->post("download");
		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']="";
		$data['viewdamages'] = $this->usermodel->viewdamagedproducts($fromdate,$todate,$companyid,$code,$branch,$download,$supplier);
				$data['total_rows']=count((array)$data['viewdamages']);
				$this->load->view('userdata/viewdamages',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function viewissuedproducts()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branch = $this->input->post("branch");
		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']="";
		$data['viewincomingstock'] = $this->usermodel->viewissuedproducts($fromdate,$todate,$companyid,$code,$branch);
				$data['total_rows']=count((array)$data['viewincomingstock']);
				$this->load->view('userdata/viewoutgoingstock',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function searchvisitorcheckins()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			// $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $download = $this->input->post("download");

	  $method = $this->input->post("method");
 	  $type = $this->input->post("type");

				$this->load->view("template/headerpagemin");
			  	  $branch = $this->input->post("branch");
		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']="";
		$data['callcenter'] = $this->usermodel->searchvisitorcheckins($fromdate,$todate,$companyid,$method,$branch,$type,$download);
												$data['total_rows']=count((array)$data['callcenter']);

				$this->load->view('userdata/viewmygatepasscheckins',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	public function searchvisitorfequency()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			// $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
	  $download = $this->input->post("download");

	  
				$this->load->view("template/headerpagemin");
			  	  $branch = $this->input->post("branch");
		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links']="";
		$data['callcenter'] = $this->usermodel->searchvisitorfequency($fromdate,$todate,$companyid,$branch,$download);
			
				
								$data['total_rows']=count((array)$data['callcenter']);

				
				$this->load->view('userdata/viewvisitorfequency',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	public function viewpeoplebymonth()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $category = htmlspecialchars(trim($this->input->post("category")));
	  $month = $this->input->post("month");

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchid");
	  	  $datetype = $this->input->post("datetype");
		  	  	  $status = $this->input->post("status");
		  	  	  $status = $this->input->post("status");

		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
		$data['viewmember'] = $this->usermodel->viewpeoplebymonth($fromdate,$todate,$companyid,$category,$branchname,$datetype,$status,$month);
		
		if($data['viewmember']==false){
					$data['total_rows']=0;

		}else{
					$data['total_rows']=count((array)$data['viewmember'] );

		}
		
		
				$data['links']="";

				$this->load->view('userdata/viewmember',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	public function viewpeople()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $category = htmlspecialchars(trim($this->input->post("category")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchid");
	  	  $datetype = $this->input->post("datetype");
		  	  	  $status = $this->input->post("status");
		  	  	  $status = $this->input->post("status");

		$this->load->view("template/tableheader");
		
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
		$data['viewmember'] = $this->usermodel->viewpeople($fromdate,$todate,$companyid,$category,$branchname,$datetype,$status);
		
		if($data['viewmember']==false){
					$data['total_rows']=0;

		}else{
					$data['total_rows']=count((array)$data['viewmember'] );

		}
		
		
				$data['links']="";

				$this->load->view('userdata/viewmember',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewproductmovement()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchname");
	  	  $tobranch = $this->input->post("tobranch");
		$this->load->view("template/tableheader");
		  $user = $this->input->post("user");
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['supplier']="all";

		$data['viewincomingstock'] = $this->usermodel->viewproductmovement($fromdate,$todate,$companyid,$code,$branchname,$tobranch, $user);
		
				$this->load->view('userdata/viewincomingstock',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
		public function viewadvancereport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	$data['branchid'] = $session_data['branchid'];
	$branchid = $data['branchid'];

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	 // $branchname = $this->input->post("branchname");
	  	  $category = $this->input->post("category");
	
		  $user = $this->input->post("user");
			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
				$data['myid']=$user;
										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['supplier']="all";

		$data['mypayments'] = $this->usermodel->viewadvancereport($fromdate,$todate,$companyid,$category,$branchid, $user);
		
					//$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/viewmyadvancepayment',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	public function viewproductionmovement()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
			 $code = htmlspecialchars(trim($this->input->post("code")));

	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");
				$this->load->view("template/headerpagemin");
			  	  $branchname = $this->input->post("branchname");
	  	  $tobranch = $this->input->post("tobranch");
		$this->load->view("template/tableheader");
		  $user = $this->input->post("user");
		  		  $category = $this->input->post("category");

			$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
				$data['supplier']=$user;


										   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
		$data['viewincomingstock'] = $this->usermodel->viewproductionmovement($fromdate,$todate,$companyid,$code,$branchname,$tobranch, $user,$category);
		
				$this->load->view('userdata/viewincomingstock',$data);
		$this->load->view("template/footerpage");
	}
	
			public function viewtaskcategory()
	{ $session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewcategory'] = $this->usermodel->populatetaslcategory($companyid);

				$this->load->view('userdata/viewtaskcategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	  
  public function addmessage()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $branchid = $this->input->post("branchid");

		   	  $description = $this->input->post("description");

			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addmessage') == "message")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'message');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  message ..</div>');	
							redirect('user/viewmessage');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Message  was not added.. Try again</div>');
								
								 redirect('user/viewmessage');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  
  public function addtable()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		 $branchid = $this->input->post("branchid");
			  
		     $action = $this->input->post("action");
	 		 $mycategoryid = $this->input->post("mycategoryid");
	
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addtable') == "table")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
								
							 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'tables');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'tables','id',$mycategoryid);

								}
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  table ..</div>');	
							redirect('user/viewtables');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Table  was not added.. Try again</div>');
								
								 redirect('user/viewtables');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }






  public function addservices()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		// $branchid = $this->input->post("branchid");
			  
		     $action = $this->input->post("action");
	 		 $mycategoryid = $this->input->post("mycategoryid");
	
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addservice') == "service")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
								
							 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'services');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'services','id',$mycategoryid);

								}
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  service ..</div>');	
							redirect('user/viewservices');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Service  was not added.. Try again</div>');
								
								 redirect('user/viewservices');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }



  public function addassignclub()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		// $branchid = $this->input->post("branchid");
			  
		     $action = $this->input->post("action");
	 		 $mycategoryid = $this->input->post("mycategoryid");
		 		 $code = $this->input->post("code");

				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btnassign') == "assign")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
							'code'=>$code,

			
								);
								
							 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'assignclubs');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'assignclubs','id',$mycategoryid);

								}
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned  a new  club ..</div>');	
							redirect('user/assignclubs');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Club  was not assigned.. Try again</div>');
								
								 redirect('user/assignclubs');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }





  public function addassignservices()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		// $branchid = $this->input->post("branchid");
			  
		     $action = $this->input->post("action");
	 		 $mycategoryid = $this->input->post("mycategoryid");
		 		 $code = $this->input->post("code");

				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btnassign') == "assign")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
							'code'=>$code,

			
								);
								
							 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'assignservices');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'assignservices','id',$mycategoryid);

								}
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned  a new  services ..</div>');	
							redirect('user/assignservices');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Services  was not assigned.. Try again</div>');
								
								 redirect('user/assignservices');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }





  public function addclub()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	$branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		 $branchid = $this->input->post("branchid");
			  
		     $action = $this->input->post("action");
	 		 $mycategoryid = $this->input->post("mycategoryid");
	
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addclub') == "club")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
								
							 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'clubs');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'clubs','id',$mycategoryid);

								}
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  club ..</div>');	
							redirect('user/viewclubs');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Club  was not added.. Try again</div>');
								
								 redirect('user/viewclubs');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }












  public function addtillno()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		  $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
	 		 $branchid = $this->input->post("branchid");
			  
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

				  exit;

		 $this->load->view('userdata/viewttill', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addtill') == "till")
					   {
						   
						   
						
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'tills');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  till ..</div>');	
							redirect('user/viewttill');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Till  was not added.. Try again</div>');
								
								 redirect('user/viewttill');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }









 
  public function addcurrency()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");

			  
		   $baseamount = $this->input->post("baseamount");
 $toamount = $this->input->post("toamount");
	 $basecurrency = $this->input->post("basecurrency");	
				
				
				
			
				
				
				
				
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcurrency', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addcurrency') == "currency")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				//'branchid'=>$branchid,

			'createdate'=>$dateposted,
					
					'basecurrency'=>$basecurrency,
			
		  	'baseamount'=>$baseamount,
				 'toamount'=>$toamount,	
				
				
			
								);
							$usr_result = $this->usermodel->add($data,'currency');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  currency ..</div>');	
							redirect('user/viewcurrency');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Currency  was not added.. Try again</div>');
								
								 redirect('user/viewcurrency');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  
  public function addfiscalyear()
    {
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 
						 
						 
						  		   	  $closing = $this->input->post("closing");

									  $opening = $this->input->post("opening");

						 
						 
						 

						  		   	  $enddate = $this->input->post("enddate");

									  		   	  $startdate = $this->input->post("startdate");

											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("name", "Year name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/fiscalyear', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addfiscalyear') == "year")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
							'enddate'=>$enddate,


															'startdate'=>$startdate,

		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
			'createdate'=>$dateposted,
			'closing'=>$closing,
			'opening'=>$opening,

			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'fiscalyear');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'fiscalyear','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  fiscal year  ..</div>');	
							redirect('user/fiscalyear');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Fiscal year was not added.. Try again</div>');
								
								 redirect('user/fiscalyear');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  public function addglfiscalyear()
    {
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $number = $this->input->post("number");

		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 
						 
						 
						  		   	  $closing = $this->input->post("closing");

									  $opening = $this->input->post("opening");

						 
						 
						 

						  		   	  $enddate = $this->input->post("enddate");

									  		   	  $startdate = $this->input->post("startdate");

											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("name", "Year name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/fiscalyear', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addfiscalyear') == "year")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
							'enddate'=>$enddate,
							'number'=>$number,


															'startdate'=>$startdate,

		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
			'createdate'=>$dateposted,
			'closing'=>$closing,
			'opening'=>$opening,

			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'glfiscalyear');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'glfiscalyear','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new GL fiscal year  ..</div>');	
							redirect('user/glfiscalyear');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  GL Fiscal year was not added.. Try again</div>');
								
								 redirect('user/glfiscalyear');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
  
  
  
  
  
  
  
  
  
  
 
  public function addcustomerfiscalyear()
    {
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
					//	  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $fiscalyear = $this->input->post("fiscalyear");
		 		 $branchid = $this->input->post("branchid");
		 		 $dateposted = $this->input->post("dateposted");

		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 	$mynumber = explode(':=',$this->input->post("number"));

 				
  $number = htmlspecialchars(trim($mynumber[0]));
						 
						 
						  		   	  $closing = $this->input->post("closing");

									  $opening = $this->input->post("opening");

						 									  $category = $this->input->post("category");

						 
						 

						  		   	  $enddate = $this->input->post("enddate");

									  		   	  $startdate = $this->input->post("startdate");

											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("number", "Customer/Supplier name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/customerfiscalyear', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addcustomerfiscalyear') == "year")
					   {
						   
						   
						   $getfiscalyear = $this->usermodel->populateallarray('fiscalyear','id',$fiscalyear);

  //   $startdate=$getfiscalyear[0]["startdate"];
		  	  //$enddate=$getfiscalyear[0]["enddate"];	 
						   
						   
					
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$fiscalyear,
							'enddate'=>$enddate,
							'number'=>$number,

		'category'=>$category,
															'startdate'=>$startdate,

		  	'status'=>$status,
				 'companyid'=>$companyid,
		'branchid'=>$branchid,
				 
			'createdate'=>$dateposted,
			'closing'=>$closing,
			'opening'=>$opening,

			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'customerfiscalyear');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'customerfiscalyear','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new Closing/ Opening Balance  ..</div>');	
							redirect('user/customerfiscalyear');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Closing/ Opening Balance was not added.. Try again</div>');
								
								 redirect('user/customerfiscalyear');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
  
  
  
  
  
  
  
  
  public function addbudget()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $view = $this->input->post("view");

				 $expamount = $this->input->post("expamount");

				 $month = $this->input->post("month");

					$code = $this->input->post("code");
		 		 $description = $this->input->post("description");

		 		 $year = $this->input->post("year");
		 		
		   

			$mycategoryid = $this->input->post("mycategoryid");
		    	 $fromdate = $this->input->post("fromdate");
		    	 $todate = $this->input->post("todate");

		    	 $action = $this->input->post("action");

						    	 $usedamount = $this->input->post("usedamount");

										    	 $closingtype = $this->input->post("closingtype");

			
					 $todate=	 $todate." "."23:59:59";
					
				
				
				
				
				
			
				
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("expamount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_budget') == "budget")
					   {
									$totalamaountused=0;
								
									
									
		
									
									
									
									
									
									
									
									
											 if($action=="insert"){
									
				$balance=0;
$totalamaountused=0;
							}else 	if($action=="update"){
				
				
				
					if($closingtype=="Automatic"){
										
									
						$getexpenses = $this->usermodel->getbudetexpense($fromdate,$todate,$companyid,$code,$branchid);
			$totalamaountused=$getexpenses[0]["amount"];
			
				
				
										
									}else{
										
									$totalamaountused=	$usedamount;
										
									}
$balance=$expamount-$totalamaountused;
								}
									
									
			
												$data=array(		
			
				 	'userid'=>$userid,
			
				'code'=>$code,
				'year'=>$year,
				'createdate'=>$fromdate,
				'month'=>$month,

				'description'=>$description,
				'branch'=>$branchid,


		  	'expamount'=>$expamount,
				 'companyid'=>$companyid,
				 'balance'=>$balance,
				 'usedamount'=>$totalamaountused,
				 'todate'=>$todate,

				
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'budget');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'budget','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  budget  ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Budget  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
	
  
  
  
  public function addprojectbudget()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $view = $this->input->post("view");

				 $expamounts = $this->input->post("expamount");
				 $qty = $this->input->post("qty");

				 $uom = $this->input->post("uom");

					$code = $this->input->post("code");
		 		 $description = $this->input->post("description");

		 		 $year = $this->input->post("year");
		 		
		   		 		 $todate = $this->input->post("todate");


			$mycategoryid = $this->input->post("mycategoryid");
		    	 $fromdate = $this->input->post("fromdate");
		    	 $todate = $this->input->post("todate");

		    	 $action = $this->input->post("action");
						    	 $projectid = $this->input->post("projectid");

						    	 $usedamount = $this->input->post("usedamount");

										    	 $closingtype = $this->input->post("closingtype");

			
					 //$todate=	 $todate." "."23:59:59";
					
				
				
				
				
				
			
				
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("qty", "Expected qty", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_budgetproject') == "budgetproject")
					   {
									$totalamaountused=0;
								
									
									
		
													$productname = $this->usermodel->populateallarray('products','code', $code);

	$buyingprice=$productname[0]['buyingprice']; 		
									
									
									
				$expamount	=	$qty *$buyingprice;			
									
									
									
											 if($action=="insert"){
									
				$balance=0;
$totalamaountused=0;
							}else 	if($action=="update"){
				
				
				
					if($closingtype=="Automatic"){
										
									
						$getexpenses = $this->usermodel->getbudetexpense($fromdate,$todate,$companyid,$code,$branchid);
			$totalamaountused=$getexpenses[0]["amount"];
			
			
									
										
									}else{
										
									$totalamaountused=	$usedamount;
										
									}
$balance=$expamount-$totalamaountused;
								}
									
									
									
									
												$data=array(		
			
				 	'userid'=>$userid,
			
				'code'=>$code,
				'year'=>$year,
				'createdate'=>$fromdate,
				'qty'=>$qty,
				'uom'=>$uom,

				'description'=>$description,
				'branch'=>$branchid,
				'buyingprice'=>$buyingprice,


		  	'expamount'=>$expamount,
				 'companyid'=>$companyid,
				 'balance'=>$balance,
				 'usedamount'=>$totalamaountused,
				 'todate'=>$todate,

								 'projectid'=>$projectid,

				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'projectsbudget');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'projectsbudget','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  budget for the project  ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Budget  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
  
  public function addprojectbudgettask()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $view = $this->input->post("view");

				 $expamounts = $this->input->post("expamount");
				 $qty = $this->input->post("qty");

				 $uom = $this->input->post("uom");

					$code = $this->input->post("code");
		 		 $description = $this->input->post("description");

		 		 $year = $this->input->post("year");
		 		
		   		 		 $todate = $this->input->post("todate");


			$mycategoryid = $this->input->post("mycategoryid");
		    	 $fromdate = $this->input->post("fromdate");
		    	 $todate = $this->input->post("todate");

		    	 $action = $this->input->post("action");
						    	 $projectid = $this->input->post("projectid");

						    	 $usedamount = $this->input->post("usedamount");

										    	 $closingtype = $this->input->post("closingtype");

			
					 //$todate=	 $todate." "."23:59:59";
					
				
				
				
				
				
			
				
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("qty", "Expected qty", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_budgetproject') == "budgetproject")
					   {
									$totalamaountused=0;
								
									
									
		
													$productname = $this->usermodel->populateallarray('products','code', $code);

	$buyingprice=$productname[0]['buyingprice']; 		
									
									
									
				$expamount	=	$qty *$buyingprice;			
									
									
									
											 if($action=="insert"){
									
				$balance=0;
$totalamaountused=0;
							}else 	if($action=="update"){
				
				
				
					if($closingtype=="Automatic"){
										
									
						$getexpenses = $this->usermodel->getbudetexpense($fromdate,$todate,$companyid,$code,$branchid);
			$totalamaountused=$getexpenses[0]["amount"];
			
			
									
										
									}else{
										
									$totalamaountused=	$usedamount;
										
									}
$balance=$expamount-$totalamaountused;
								}
									
									
									
									
												$data=array(		
			
				 	'userid'=>$userid,
			
				'code'=>$code,
				'year'=>$year,
				'createdate'=>$fromdate,
				'qty'=>$qty,
				'uom'=>$uom,

				'description'=>$description,
				'branch'=>$branchid,
				'buyingprice'=>$buyingprice,


		  	'expamount'=>$expamount,
				 'companyid'=>$companyid,
				 'balance'=>$balance,
				 'usedamount'=>$totalamaountused,
				 'todate'=>$todate,

								 'projectid'=>$projectid,

				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'projectsbudgettasks');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'projectsbudgettasks','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  budget for the project  ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Budget  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
  public function addlabour()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $view = $this->input->post("view");

				 $expamount = $this->input->post("expamount");

				 $month = $this->input->post("month");

					$code = $this->input->post("code");
		 		 $description = $this->input->post("description");

		 		 $employeeid = $this->input->post("employeeid");
		 		
		   

			$mycategoryid = $this->input->post("mycategoryid");

		    	 $action = $this->input->post("action");

						    	 $exactdate = $this->input->post("exactdate");
								 
						    	 $exactdate = $exactdate." ".$currenttime;

										    	 $qty = $this->input->post("qty");

			
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("qty", "qty/No", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_labour') == "labour")
					   {
						   
						   
						   
						     $products=$this->usermodel->populateallarray('salarycharges','code', $code);
									
									$rate=$products[0]['amount'];
									$total=$rate*$qty;
						   
						   
						   
						   
						   
						   
						   
						   
									
												$data=array(		
			
				 	'userid'=>$userid,
			
				'code'=>$code,
				'employeeid'=>$employeeid,
				'createdate'=>$createdate,
								'rate'=>$rate,
								'total'=>$total,

				'month'=>$month,

				'description'=>$description,
				'branch'=>$branchid,
				'qty'=>$qty,


				 'companyid'=>$companyid,
				 'exactdate'=>$exactdate,

				
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'labour');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'labour','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  budget  ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Budget  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
  public function assignmytask()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['branchid'] = $session_data['branchid'];
	 $branch = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $view = $this->input->post("view");

				 $employeeid = $this->input->post("employeeid");

				 $taskid = $this->input->post("taskid");

					$period = $this->input->post("period");
		 		 $description = $this->input->post("description");

		 		 $mode = $this->input->post("mode");
		 		

			$tasktype = $this->input->post("tasktype");

			$mycategoryid = $this->input->post("mycategoryid");

		    	 $action = $this->input->post("action");
		    	 $target = $this->input->post("target");

						    	 $year = $this->input->post("year");
					$fromdate = $this->input->post("fromdate");
		    	 $todate = $this->input->post("todate");
		    	 $branchid = $this->input->post("branchid");

									$defaulttype = $this->input->post("defaulttype");

		
				
				
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("branchid", "Branch name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assigntask') == "task")
					   {
									
												$data=array(		
			
				 	'userid'=>$userid,
			
				'period'=>$period,
				'mode'=>$mode,
				'createdate'=>$createdate,
				'target'=>$target,
				'tasktype'=>$tasktype,

				'description'=>$description,
				'branchid'=>$branchid,
				'defaulttype'=>$defaulttype,


		  	'year'=>$year,
				 'companyid'=>$companyid,
				 'taskid'=>$taskid,
				 'employeeid'=>$employeeid,
				 				 'fromdate'=>$fromdate,

							 'todate'=>$todate,


				
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'assigntask');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'assigntask','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assign task to the employee/ user  ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Task   was not assigned.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
  
  public function addcomplain()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $type = $this->input->post("type");
				 		 		 $messageid = $this->input->post("messageid");

								 		 		 $subject = $this->input->post("subject");

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");


		   	  $status = "New";

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");
											  		   	  $view = $this->input->post("view");

		    		   	 
											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("description", "Description", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/complain', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcomplain') == "addcomplain")
					   {
									
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
				'messageid'=>$messageid,
				'subject'=>$subject,
				'createdate'=>$createddate,

				'description'=>$description,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'complain');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'complain','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Complain/ Message  ..</div>');	
							redirect($view );																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Complain/ Message  was not added.. Try again</div>');
								
redirect($view );							
}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
	
	
	
	
	
  
  public function addnewcalls()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");
				 		 		 $calldate = $this->input->post("calldate");

								 		 		 $subject = $this->input->post("subject");

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");


			  						  		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 
											   $action = $this->input->post("action");

$sendsms = $this->input->post("sendsms");
$sms = trim($this->input->post("sms"));



			  		  $this->form_validation->set_rules("callername", "Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addaddnewcalls') == "calls")
					   {
									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				'callername'=>$callername,
				'calldate'=>$calldate,
	'media'=>$media,
				'phone'=>$phone,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'callcenter');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'callcenter','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
			if($sendsms	=="yes"){

									
													
									$myview="user/callcenter";				  
		  $this->addallpushedsms($sms,$phone,$myview);



			}				
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  call details  ..</div>');	
							redirect('user/callcenter');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Call  was not added.. Try again</div>');
								
								 redirect('user/callcenter');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
  public function addneworders()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 		 		 $category = $this->input->post("category");
		$mycode = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($mycode[0]));
	  $startdate = $this->input->post("startdate");

				 		 		 $closedate = $this->input->post("closedate");
	 		 		 $fuel = $this->input->post("fuel");
$trips = $this->input->post("trips");
$millage = $this->input->post("millage");

	 
	 //$nextfuel = $this->input->post("nextfuel");

	 
	 
	 
	 
	 
	 
	 
	 
		 				 		

	$messageid = $this->input->post("messageid");
 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");


			  						  		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 
											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("description", "Description", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addaddneworders') == "orders")
					   {
						   
						   						$people = $this->usermodel->populateallarray('people','id',$code);
									$fuelrate=$people[0]["rate"];
									$fuellimit=$people[0]["limitamount"];

									
						 $previoufueldate=0;
						 $previousfuelused=0;

 	$lastrecord = $this->usermodel->last_salesbycustomer($code,$companyid);
			if($lastrecord !=false){
				 $previoufueldate=$lastrecord[0]["dateposted"];
				
				 
$mysales = $this->usermodel->populateallarray('sales_order','invoice',$lastrecord[0]["invoice"]);
									$previousfuelused=$mysales[0]["qty"];
				 
			}else{
				
				 $previoufueldate="na";
					$previousfuelused=0;

			}
 			$mynextfuel=($millage/$fuelrate);
									
				$expectedfuel	=($fuellimit-$mynextfuel);				
					//$adjusted	=$expectedfuel-$fuel;			
					$nextfuel=$mynextfuel+	$adjusted;
//$adjusted=0;					
											$nextfuel=$mynextfuel;			
			
									
									
									
									
												$data=array(		
			'userid'=>$userid,
						'previoufueldate'=>$previoufueldate,
						'previousfuelused'=>$previousfuelused,

				'category'=>$category,
								'millage'=>$millage,
								//'adjusted'=>$adjusted,

				'code'=>$code,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,

				'description'=>$description,
				'startdate'=>$startdate,
				'closedate'=>$closedate,
								'nextfuel'=>$nextfuel,

	'trips'=>$trips,
				//'fuel'=>$fuel,
				'fuellimit'=>$fuellimit,
				'fuelrate'=>$fuelrate,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'openorders');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'openorders','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  order  ..</div>');	
							redirect('user/openorders');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Orders  was not added.. Try again</div>');
								
								 redirect('user/openorders');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
  public function starttimer()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $startdates = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdat =  ($startdates)." ".$currenttime ;
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
						$companyid = $data['companyid'];
							$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
						
		 				 		 $enddate = $this->input->post("enddate");
								 		 				 		 $startdate = $this->input->post("startdate");

		 				 		 $hour = $this->input->post("hour");
		 					$product = $this->input->post("product");
				 		 		
				 $station = $this->input->post("station");
					$createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 	
		 		 $invoice = $this->input->post("invoice");


			  						  		   	  $status = $this->input->post("status");

			  						  		   	  $myproductid = $this->input->post("myproductid");

		    		   	 
											  		   	  $action = $this->input->post("action");

				
			  		  $this->form_validation->set_rules("product", "product", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtimer', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addtimer') == "timer")
					   {
							
							
							
							
							
							
							
							
							
								$productname = $this->usermodel->populateallarray('products','code', $product);

 
				  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
				redirect('user/viewtimer');	
							redirect($myview);	

								}	

								
		 	
 		 $amount = 0;
	 $unit=$productname[0]['sellingprice']; 
				 
								 
 $amount =  $hour* $unit;

							

							
												$data=array(		
				'userid'=>$userid,
			
				'product'=>$product,
				
				'station'=>$station,
				'startdate'=>$startdate,
				'description'=>$description,
				'enddate'=>$enddate,
				'createdat'=>$createdat,
								'invoice'=>$invoice,

					'amount'=>$amount,
							
				'unit'=>$unit,
				'hour'=>$hour,


		  	'status'=>$status,
				 'companyid'=>$companyid,
				 'branchid'=>$branchid,

				 
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'timer');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'timer','id',$myproductid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully started  ..</div>');	
							redirect('user/printtimer?invoice='.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You were not able to start.. Try again</div>');
								
								 redirect('user/viewtimer');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
  
	
  public function postendtime()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $startdates = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createdat =  ($startdates)." ".$currenttime ;
		 $userid = $data['id'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				$data['companyid'] = $session_data['companyid'];
						$companyid = $data['companyid'];
		 				 		 $enddate = $this->input->post("enddate");

		 				 		 $hour = $this->input->post("hour");
		 				 		 $unit = $this->input->post("unit");
		 				 		 $amount = 0;
								  $diffrent = 0;
								 
 //
 
 
 			  						  		   	  $myproductid = $this->input->post("endtimeid");

 
 
 $timer = $this->usermodel->populateallarray('timer','id',$myproductid);
$mystatus=$timer[0]['status'];
			 $unit=$timer[0]['unit'];			   
		 $startdate=$timer[0]['startdate'];
 $start=strtotime(date($startdate));
  $end=strtotime(date($enddate));
 $minutes =  0;
  $myhour =  0;
   $diffrent =  $end- $start;
   if($diffrent>=60){
	   //$minutes = round($diffrent/60); 
   }else{
	   
	  /// $minutes=0;
   }
   	   $minutes = round($diffrent/60); 

    $myhour =   round($minutes/60);
	    $finalmyhour =   round($minutes,2);

$amount =  $finalmyhour * $unit;

$duration="";
$finalminute=fmod($minutes,60);

if($myhour>=1){
	

		
if($finalminute>=1){
	$duration=$myhour ."H ".$finalminute."Min";

}else{
	
	$duration=$myhour ."H ";

}


}else{
$duration=$finalminute ."Min";

}



			  						  		   	  $status = "completed";


		    		   	 

				
			  		  $this->form_validation->set_rules("enddate", "Description", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtimer', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addtimer') == "timer")
					   {
							

							
						   if(($mystatus=="completed") && ($usertype!="admin")){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This event had completed.  Once closed, you can not close again. Try again</div>');
								
								 redirect('user/viewtimer');
								 
								 return false;
					 

						 } 

							
							
							
							
							
							
							
												$data=array(		
				
			
				'status'=>$status,
			
				'enddate'=>$enddate,
								'hour'=>$finalmyhour,

					'amount'=>$amount,
								'duration'=>$duration,


				 
				
			
								);
								
								$usr_result = $this->usermodel->updatedata($data,'timer','id',$myproductid);

								
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully closed the time  ..</div>');	
							redirect('user/viewtimer');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You were not able to end the timer.. Try again</div>');
								
								 redirect('user/viewtimer');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	  public function addproject()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $category = $this->input->post("category");

		   	  $description = $this->input->post("description");

			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addproject') == "addproject")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'category'=>$category,

				 
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'projects');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  project ..</div>');	
							redirect('user/viewprojets');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Project  was not added.. Try again</div>');
								
								 redirect('user/viewprojets');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
	  public function addrequistion()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $createdate = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $orderedby = $this->input->post("orderedby");

		   	  $description = $this->input->post("description");

			  		   	  $branchid = $this->input->post("branchid");
			  		   	  $orderdate = $this->input->post("orderdate");
			  		   	  $invoice = $this->input->post("invoice");

		      $taskid = $this->input->post("taskid");
			  		   	  $subtaskid = $this->input->post("subtaskid");

			
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewprojetstasks', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postrequest') == "request")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'orderedby'=>$orderedby,
			'branchid'=>$branchid,

				 			'taskid'=>$taskid,
			'subtaskid'=>$subtaskid,

			'orderdate'=>$orderdate,
							'createdate'=>$createdate,
							'invoice'=>$invoice,

			
								);
							$usr_result = $this->usermodel->add($data,'requisition');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully started a new  requistion ..</div>');	
						


						redirect('user/viewstartrequistion?invoice='.$invoice.'&subtaskid='.$subtaskid.'&taskid='.$taskid);	







							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Requistion was not started. Try again</div>');
								
								 redirect('user/viewprojets');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }








 public function viewstartrequistion() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];	
		
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $taskid = $_GET['taskid'];
	      $subtaskid = $_GET['subtaskid'];

	      $invoice = $_GET['invoice'];

   	
		$this->load->view("template/tableheader");

    $this->load->view("template/headerpagemin", $data);
$data['viewbudget']  = $this->usermodel->populatealldatanoarray('projectsbudgettasks','projectid', $subtaskid,'companyid', $companyid);


		 $data['invoice']=$invoice;
		  		 $data['links']="";
  		 $data['total_rows']=count((array)$data['viewbudget'] );
		$data['subtaskid']=$subtaskid;

$data['taskid']=$taskid;

		
		 $this->load->view('userdata/viewstartrequistion', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	







	
  public function addnewprinter()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $categoryno = $this->input->post("categoryno");

		   	  $description = $this->input->post("description");

			  		   	  $branchid = $this->input->post("branchid");
			  		   	  $status = $this->input->post("status");
			  		   	  $action = $this->input->post("action");

		    			  		   	  $mycategoryid = $this->input->post("mycategoryid");

		
				
			  		  $this->form_validation->set_rules("categoryno", "Main Category No", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postprinter') == "printer")
					   {
						   
						   
						   					if($action=="insert"){

									
							
								
						   		  $confirmprinters = $this->usermodel->populatealldatanoarray('printers','categoryno', $categoryno,'branchid', $branchid);

						   
						   if(  $confirmprinters !=false){
							   
							   			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Main  Category had been created/ enabled on that same branch selected. Kindly edit it or Try again another one</div>');
								
								 redirect('user/kitchenprinter');
								 
								 return false;
							   
							   
							   }
						   }
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'categoryno'=>$categoryno,
							'branchid'=>$branchid,

		  	'description'=>$description,
				 'companyid'=>$companyid,
				 'status'=>$status,

				 
			'createdate'=>$dateposted,
				
			
								);
								
								
														if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'printers');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'printers','id',$mycategoryid);

								}	
								
								
								
								
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  category printer ..</div>');	
							redirect('user/kitchenprinter');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Category Printer  was not added.. Try again</div>');
								
								 redirect('user/kitchenprinter');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


	
  public function sendpointsotp()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
		   	  $myview = $this->input->post("myview");

			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsales', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_POINTSOTOP') == "otp")
					   {
						   
						   
						   
						$confirmcard = $this->usermodel->Getcardnumber($name,$companyid);
			   								
	if($confirmcard==FALSE){
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Card No/ Id No/Phone No Does not exist.Try again.</div>');
								
								 redirect($myview);
								   return  false;
	
						   
						   
	}	
						   
		$contact=trim($confirmcard[0]['phone']);
				$employeeno=trim($confirmcard[0]['id']);

		
		  $correctime=date("Y-m-d H:i:s");

		$smscode =  $userid.$this->createRandomPasswordForLogin();

	
		$view="";
		 	$taskmessage = "Dear ". $confirmcard[0]['firstname'] ."! Your one time(OTP) Point redemption code is: .". $smscode ." at  ". $correctime .". Use it within 10 minutes.";


									  $this->pushroomsms($taskmessage,$contact,$view);
									//

			$updatesmsdata=array(		
		
							'smscode'=>$smscode,
							'timesent'=>$correctime,

							);
						
	
							 	$usr_result=  	$this->usermodel->updatedata($updatesmsdata,'people','id',$employeeno);

		
		
		
		
		
				   
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent Otp ..</div>');	
							redirect($myview);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> OTP was not sent.. Try again</div>');
								
							redirect($myview);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


	
  public function addbranch()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");

			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addbranch') == "branch")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'branch');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  branch ..</div>');	
							redirect('user/viewbranch');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Branch  was not added.. Try again</div>');
								
								 redirect('user/viewbranch');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }





	
  public function savebulklabels()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 //$code = $this->input->post("code");
		 		 $newproduct = $this->input->post("newproduct");

		   	  $branch = $this->input->post("branch");

			  
 			$mycode = explode(':=',$this->input->post("code"));

 
  $newcode = htmlspecialchars(trim($mycode[0]));

 
		    if($newcode!=""){
				$code= $newcode;
				
			}else{
				
					$code= $newproduct;
			}
		
				
			  		  $this->form_validation->set_rules("branch", "branch name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_savelabels') == "SAVE PRODUCT")
					   {
						   
						   if ($from =="Main")
						   {
							$productname = $this->usermodel->populateallarray('products','code', $code);
   
							   
						   }else{
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

							   
							}
					
   
							   
						
						
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
								redirect("user/viewbulklables");
	   return false;
						   }
						   			



						 
	
									 
				$name=$productname[0]['name']; 
				
					  	$shortname=$productname[0]['shortname'];    
							$sellingprice=$productname[0]['sellingprice'];    

						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			'code'=>$code,
		  	'description'=>$shortname,
				 'companyid'=>$companyid,
				 'sellingprice'=>$sellingprice,

	 'branch'=>$branch,
				 
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'labels');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  product to printing labels list ..</div>');	
							redirect('user/viewbulklables');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Item  was not added.. Try again</div>');
								
								 redirect('user/viewbulklables');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }








	
  public function editetimsitems()
    {
		

			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
					$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 				   
						   $itemclassification = $this->input->post("ItemClassification");
						  $itemtype = $this->input->post("itemtype");
						  $packagingunit = $this->input->post("packagingunit");
						   $salesunit = $this->input->post("salesunit");
						   $countryoforigin = $this->input->post("countryoforigin");
						   $itemstatus = $this->input->post("itemstatus");
						   $itemtax = $this->input->post("itemtax");

						   
		$branchname = $this->input->post("branchname");
	  $orderamount = $this->input->post("orderamount");

	  	  $vattype = $this->input->post("vattype");

	  	  $category = $this->input->post("category");
			$producttype = $this->input->post("producttype");
	  	  $maincategory = $this->input->post("maincategory");

						   
						 
   
			  		  $this->form_validation->set_rules("salesunit", "item sales unit", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewetimsbulkupdate', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_etimsupdate') == "etimsupdate")
					   {
						   
						    $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
						   }											
							
						  
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
			  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);



if($onlineoffline=="OSCU"){
            $apiUrl = ''.$etimsurl.'/etims-api/saveItem';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/saveItems';

			 }
			    
						   
						   $stocklist = $this->usermodel->viewproductsforetimsupdate($category,$orderamount,$companyid,$branchname,$producttype,$maincategory,$vattype);

						  	//$stocklist = $this->usermodel->viewproductsforetimsupdate('products','status', "active",'itemclassification',"" );
		$usr_result=true;
		

if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	  $myitemcode=$countryoforigin.$itemtype.$packagingunit.$salesunit;
		$code=$row->code;
				$sellingprice=$row->sellingprice;
				$reorderevel=$row->reorderevel;

		$name=$row->name;
		$id=$row->id;
		$itemcode = $myitemcode . sprintf("%07d", $id)	;
 //echo "</br>";
	$updatedata=array(
											
		'itemclassification'=>$itemclassification,
		'country'=>$countryoforigin,
			'itemtype'=>$itemtype,
			'packagingunit'=>$packagingunit,
			'salesunit'=>$salesunit,
				   	
					 'itemstatus'=>$itemstatus,
						'itemtax'=>$itemtax,
						'hscode'=>$itemcode,

								);
								
	
		$usr_result =$this->usermodel->updatedata($updatedata,'products','code',$code);
		$usr_result=$this->usermodel->updatedata($updatedata,'productlist','code',$code);


         $data = [
		   "tin" => $kra_pin,
              "bhfId" => $branch_id,
 
            "itemCd" => $itemcode,
            "itemClsCd" => $itemclassification,
            "itemTyCd" => $itemtype,
            "itemNm" => $name,
            "itemStdNm" => $name,
            "orgnNatCd" => $countryoforigin,
            "pkgUnitCd" => $packagingunit,
            "qtyUnitCd" => $salesunit,
            "taxTyCd" => $itemtax,
            "btchNo" => 2,
            "bcd" =>$code,
            "dftPrc" => $sellingprice,
            "grpPrcL2" => $sellingprice,
            "grpPrcL3" => $sellingprice,
            "grpPrcL4" => $sellingprice,
            "grpPrcL5" => null,
            "addInfo" => null,
            "sftyQty" => $reorderevel,
            "isrcAplcbYn" => "N",
            "useYn" => "Y",
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
	
	
				
				
            // Check for cURL errors
            if (curl_errno($ch)) {


				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
						   
				if ($resultCd == '000') {	
						
							$datasaved=1;
						}else {

							$datasaved=0;
						}							
							

$updatedataetims=array(
											
'is_serialized'=>$datasaved,		

								);							
						$usr_result =$this->usermodel->updatedata($updatedataetims,'products','code',$code);
						$usr_result=$this->usermodel->updatedata($updatedataetims,'productlist','code',$code);
			   
				}

			}		











		
   } 
						   
}					   

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated items with Etims data..</div>');	
							redirect('user/viewetimsbulkupdate');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/viewetimsbulkupdate');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
  public function editetimsitemsproducts()
    {
		

			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
					$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 				   
						   $itemclassification = $this->input->post("ItemClassification");
						  $itemtype = $this->input->post("itemtype");
						  $packagingunit = $this->input->post("packagingunit");
						   $salesunit = $this->input->post("salesunit");
						   $countryoforigin = $this->input->post("countryoforigin");
						   $itemstatus = $this->input->post("itemstatus");
						   $itemtax = $this->input->post("itemtax");

						$code = $this->input->post("code");
		   
		$branchname = $this->input->post("branchname");
	  $orderamount = $this->input->post("orderamount");

	  	  $vattype = $this->input->post("vattype");

	  	  $category = $this->input->post("category");
			$producttype = $this->input->post("producttype");
	  	  $maincategory = $this->input->post("maincategory");

					  	  $page = $this->input->post("page");
		   
				 $updatetype = $this->input->post("updatetype");
	 
   
			  		  $this->form_validation->set_rules("salesunit", "item sales unit", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewetimsbulkupdate', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_etimsupdates') == "etimsupdates")
					   {
		
			$stocklist = $this->usermodel->populateall("products","code",$code);

						  	//$stocklist = $this->usermodel->viewproductsforetimsupdate('products','status', "active",'itemclassification',"" );
		$usr_result=true;
		

if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	  $myitemcode=$countryoforigin.$itemtype.$packagingunit.$salesunit;
		$code=$row->code;
				$sellingprice=$row->sellingprice;
				$reorderevel=$row->reorderevel;
		$id=$row->id;


   if(($row->hscode =="")|| ($row->itemclassification =="")) {
$itemcode = $myitemcode . sprintf("%07d", $id)	;


   }else if(($row->hscode !="")|| ($row->itemclassification =="")) {
$itemcode = $myitemcode . sprintf("%07d", $id)	;


   }else{
		$itemcode=$row->hscode;
   }	   

 
		$name=$row->name;
		
 //echo "</br>";
	$updatedata=array(
											
		'itemclassification'=>$itemclassification,
		'country'=>$countryoforigin,
			'itemtype'=>$itemtype,
			'packagingunit'=>$packagingunit,
			'salesunit'=>$salesunit,
				   	
					 'itemstatus'=>$itemstatus,
						'itemtax'=>$itemtax,
						'hscode'=>$itemcode,

								);
								
	
		$this->usermodel->updatedata($updatedata,'products','code',$code);
		$usr_result=$this->usermodel->updatedata($updatedata,'productlist','code',$code);
	

	if ($usr_result==TRUE) //active user record is present
							{



            if ($updatetype == 'both') {


			   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
	   
						    $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewetimsupdate?randomitemidentifier='.$code.'&page='.$page);																
						   

						   
						   return false;
						   }											
							
						  
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
							redirect('user/viewetimsupdate?randomitemidentifier='.$code.'&page='.$page);																
						   return false;
	}
			  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);



if($onlineoffline=="OSCU"){
            $apiUrl = ''.$etimsurl.'/etims-api/saveItem';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/saveItems';

			 }
			   










         $data = [
		   "tin" => $kra_pin,
              "bhfId" => $branch_id,
 
            "itemCd" => $itemcode,
            "itemClsCd" => $itemclassification,
            "itemTyCd" => $itemtype,
            "itemNm" => $name,
            "itemStdNm" => $name,
            "orgnNatCd" => $countryoforigin,
            "pkgUnitCd" => $packagingunit,
            "qtyUnitCd" => $salesunit,
            "taxTyCd" => $itemtax,
            "btchNo" => 2,
            "bcd" =>$code,
            "dftPrc" => $sellingprice,
            "grpPrcL2" => $sellingprice,
            "grpPrcL3" => $sellingprice,
            "grpPrcL4" => $sellingprice,
            "grpPrcL5" => null,
            "addInfo" => null,
            "sftyQty" => $reorderevel,
            "isrcAplcbYn" => "N",
            "useYn" => "Y",
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
          $response = curl_exec($ch);


				
	
	
				
				
            // Check for cURL errors
            if (curl_errno($ch)) {


				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
			
						
							$datasaved=1;
						

						

$updatedataetims=array(
											
'is_serialized'=>$datasaved,		

								);							
						$usr_result =$this->usermodel->updatedata($updatedataetims,'products','code',$code);
						$usr_result=$this->usermodel->updatedata($updatedataetims,'productlist','code',$code);
			   
				}

			}		
	}

			}




			
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated items with Etims data..</div>');	
							redirect('user/viewetimsupdate?randomitemidentifier='.$code.'&page='.$page);																
							



		
   } else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
							redirect('user/viewetimsupdate?randomitemidentifier='.$code.'&page='.$page);																
							}
   
   
   
   
						   
}					   

}						//check if username and password is correct
						
					
							
						
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	 public function adddealfeedback()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		   	  $action = $this->input->post("action");

		   	  $description = $this->input->post("description");

			  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdealsfeedback', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
		
					   //validation succeeds
					 	if ($this->input->post('btn_adddealfeedback') == "deal")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 
			'createdate'=>$dateposted,
				
			
								);
									
								if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'dealsfeedback');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'dealsfeedback','id',$mycategoryid);

								}
										
							
							
							
							
							
							//check if username and password is correcst
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the feedback ..</div>');	
							redirect('user/viewdealsfeedback');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Feedback  was not saved.. Try again</div>');
								
								 redirect('user/viewdealsfeedback');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  public function addrole()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		   	  $action = $this->input->post("action");

		   	  $description = $this->input->post("description");

			  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewroles', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
		
					   //validation succeeds
					 	if ($this->input->post('btn_addrole') == "role")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,

				 
			'createdate'=>$dateposted,
				
			
								);
									
								if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'roles');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'roles','id',$mycategoryid);

								}
										
							
							
							
							
							
							//check if username and password is correcst
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the role ..</div>');	
							redirect('user/viewroles');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Role  was not saved.. Try again</div>');
								
								 redirect('user/viewroles');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

public function convertsales()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		 		
		 		 $type = $this->input->post("type");
		 		 $salesid = $this->input->post("salesid");

		   	  $salesinvoice = $this->input->post("salesinvoice");

			  
		    
		
				
			  		  $this->form_validation->set_rules("type", "Sales type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/allquatation', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_convertquotation') == "quotation")
					   {
						   
						   
						
						   $getquotation = $this->usermodel->populateallarray('quotation','id',$salesid);
						   
						   
							  	   	if($getquotation[0]["supplier"]==""){
							   
						  

						    
								 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Error! You must select customer first on this quotation for you to convert it. Kindly add customer  or Try again</div>');
								
							redirect('user/viewnewquotation?randomitemidentifier='.$salesinvoice);																
								 
								 return false;
								
							
						}  



						   
						   
						   if($type =="SalesOrder"){
							   
							   	if($salesinvoice!=""){
							   
						  
						     $confirmno = $this->usermodel->populateall('purchaseorder', 'invoice',$salesinvoice);

						    if($confirmno!=FALSE){
								 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This quotation had been converted to Sales Order already. Kindly edit the sales order directly or Try again</div>');
								
							redirect('user/viewnewquotation?randomitemidentifier='.$salesinvoice);																
								 
								 return false;
								
							}
						}  
							   
							   
							   
							   
							   
							   
							   
							   
							   
	$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$ordeno=$myconfiguration[0]["website"]; 
		$taxindicator=$myconfiguration[0]["display1"];

$total_rows = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'status','s.o');
$finalorder=$ordeno.$total_rows;	
										$data=array(		
			'userid'=>$getquotation[0]["userid"] ,
			'companyid'=>$companyid,
			'branchid'=>$branchid,

			'supplier'=>$getquotation[0]["supplier"],
			
		  	'description'=>$getquotation[0]["description"],
							'deliverymethod'=>$getquotation[0]["deliverymethod"],

		
			'createdate'=>$getquotation[0]["orderdate"],
						'agent'=>"",

				'invoice'=>$salesinvoice,
			  	'orderdate'=>$getquotation[0]["orderdate"],
			  	'ordernumber'=>$finalorder,
			  	'orderedby'=>$getquotation[0]["orderedby"],
			  	'shippingto'=>$getquotation[0]["shippingto"],
			  	'canceldate'=>$getquotation[0]["canceldate"] ,
			  	'fob'=>$getquotation[0]["fob"],
			  	'amount'=>$getquotation[0]["amount"],
				'status'=>"s.o",
			  	'terms'=>$getquotation[0]["terms"],  
						'controller'=>"",	   
						 
						   	);
						   
						   
						
	$myusr_result = $this->usermodel->add($data,'purchaseorder');
if ($myusr_result ==TRUE) //active user record is present
							{

	$sales_orderdata = array();
			$solditems= $this->usermodel->populateall('purchaseorderlist','invoice',$salesinvoice);
$i=0;
	if(is_array($solditems)){
	
	   foreach($solditems as $row)
	   {
			$i++;    
		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 	 $serial=$row->serial;
$allproducts = $this->usermodel->populateallarray('products','code',$code);
	
						$salesaccount="";	
					 
					 	$expenseaccount="";	
						$assetaccount="";	


	
	   if($allproducts[0]['expenseaccount']!=""){ $expenseaccount=$allproducts[0]['expenseaccount'];}else{ $expenseaccount=5500; }
 if($assetaccount=$allproducts[0]['assetaccount']!=""){ $assetaccount=$allproducts[0]['assetaccount'];}else{ $assetaccount=1110; }	  
						  
					  
 if($allproducts[0]['salesaccount']!=""){ $salesaccount=$salesaccount=$allproducts[0]['salesaccount'];}else{ $salesaccount=4000; }
	
	
	
		
	 
	 
	 $branch=$row->branch;
		$sprice=$row->sprice;
		if($row->salestype!=""){
			$salestype=$row->salestype;
		}else{
			$salestype="retail";
		}
	
	
		$vattype=$allproducts[0]["vattype"] ;
		
		
		
				$myinvoice=($row->invoice)+$i;




				$updatedby=$userid;
		$bprice=$row->bprice;
	$tax=$row->tax;
	$tax2=$row->tax2;
		$taxable=$row->taxable;
	$amount=$row->amount;
	$discount=$row->discount;

		$maincategory=$row->maincategory;
	$category=$row->category;
	
		 	$uomqty=$row->mode;


		
$sales_orderdata[]=array(		
			'userid'=>$userid,
			
				'code'=>$code,
								'uomqty'=>"",
			'myinvoice'=> $myinvoice,
	//'qty'=> $myqty,
			'sales'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => "PO",    
		  		   'address' => "", 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uomqty, 
				  			   			      'status' => "printed", 

				  			   			'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,
//jakom
      'ordersales' => "new", 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
		  
		  
		  
		}
		  	  $usr_result =$this->db->insert_batch('sales_order', $sales_orderdata); 

		  
		        if($this->db->affected_rows() > 0)
	{
	
			
		}	
		
		
		
		
	}	
	
						   }








							   
						   }else{
							   
							   
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						
							//$usr_result = $this->usermodel->add($data,'branch');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Converted the quotation ..</div>');	
							redirect('user/viewnewsalesorder?randomitemidentifier='.$salesinvoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Quotation   was not converted.. Try again</div>');
								
								 redirect('user/allquatation');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }



  public function postopeningbalance()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $type = $this->input->post("type");
		 		 $customer = $this->input->post("customer");
		 		 $supplier = $this->input->post("customer");

		   	  $description = $this->input->post("description");

			  		   	  $credit = $this->input->post("credit");
		   	  $debit = $this->input->post("debit");
  $branchid = $this->input->post("branchid");
		    		  $fromdate = $this->input->post("currenttime");

		  $currenttime = $this->input->post("currenttime");
		  $total = $this->input->post("total");
		  $finaltotalamount = $this->input->post("total");

				
			  		  $this->form_validation->set_rules("type", "Transaction type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postopeningbalance') == "balance")
					   {
						   
                   	$finalsalesid = $userid.time();
						   
						   if($type=="customer"){
							  	   
														
		
               
					
					
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
									'customer' => $customer,

                                 //'amount' => $emapData['B'],
 							      'balance' => "-".$total,
									'credit' => $total,
								'total' => $total,

 									'description' => $description,
									'branch' => $branchid,

									'type' => "Opening Balance",
									//'fromdate' => $fromdate,
									'invoice' => $finalsalesid,

									'userid' => $userid,
									'salestype' => "retail",
 									'companyid' => $companyid,
									 'dateposted' => $currenttime,
									 'due_date' => $currenttime,
									 	'card' => 0,
									 	'voucher' => 0,
										'points' => 0,
									 	'mpesa' => 0,
 									'cheque' => 0,
 										'cash' => 0,
                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("sales",$mydata);
						
					
								 $debitdata=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>"Opening Balance Equity",'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);


$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$finaltotalamount,'description'=>$description,'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);

							$this->usermodel->add($creditdata,'debitcredit');
							$this->usermodel->add($debitdata,'debitcredit');	
							
							
							
							
								$openingbalancedata=array(		
			'userid'=>$userid,
			
				'description'=>"Opening Balance",
							'enddate'=>$fromdate,
							'customerid'=>$customer,

'startdate'=>$fromdate,

		  	'opening'=>$finaltotalamount,
				 'companyid'=>$companyid,

				 			'type'=>$type,

			'createdate'=>$currenttime,
			'closing'=>0,
			

			
								);
								
									$this->usermodel->add($openingbalancedata,'customersupplierbalance');
							
								$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["balance"];
									

			
								$finalcustomerbalance=$supplierbalance+$total;
							

								$peopledata=array(		
												'balance'=>$finalcustomerbalance,
													'lastbalancedate'=>$currenttime,
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$customer);
							
							
							
							
							
							   
						   }else{
							 
     $mydatas = array(
                              
									'supplier' => $supplier,

                                 'amount' => $total,
 							      'balance' => $total,

 									'description' => $description,
									'branchid' => $branchid,

									'status' => "Opening Balance",
									'fromdate' => $fromdate,
									'invoice' => $finalsalesid,

									'userid' => $userid,

 									'companyid' => $companyid,
									 'createdate' => $currenttime,
									 'paiddate' => $currenttime,

 									
                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("purchaseorder",$mydatas);
						 $debitdata=array( 'userid'=>$userid,'account'=>$debit,'debit'=>$finaltotalamount,'description'=>"Opening Balance Equity",'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);


$creditdata=array( 'userid'=>$userid,'account'=>$credit,'credit'=>$finaltotalamount,'description'=>$description,'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'supplier'=> $supplier);

							$this->usermodel->add($creditdata,'debitcredit');
							$this->usermodel->add($debitdata,'debitcredit');	
							
							
							
							
								$myopeningbalancedata=array(		
			'userid'=>$userid,
			
				'description'=>"Opening Balance",
							'enddate'=>$currenttime,
							'customerid'=>$supplier,

'startdate'=>$currenttime,

		  	'opening'=>$finaltotalamount,
				 'companyid'=>$companyid,

				 			'type'=>$type,

			'createdate'=>$currenttime,
			'closing'=>0,
			

			
								);
								
									$this->usermodel->add($myopeningbalancedata,'customersupplierbalance');
							
										$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["supplierbalance"];
									

			
								 $finaltotalcustomeramount=$supplierbalance+$total;
							
							
								$peopledata=array(		
												'supplierbalance'=>$finaltotalcustomeramount,
												'lastbalancedate'=>$currenttime,
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$supplier);
							
							











							 
							   
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						   
					
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Opening Balance..</div>');	
							redirect('user/viewmember');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Opening   was not added.. Try again</div>');
								
								 redirect('user/viewmember');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }




  public function addbbackup()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		   $server = $this->input->post("server");
			   $path = $this->input->post("path");
			  $status = $this->input->post("status");
			  $createdat = $this->input->post("createdat");
			  $host = $this->input->post("host");
						  $password = $this->input->post("password");

						  $database = $this->input->post("database");

			  						  $location = $this->input->post("location");
			  						  $user = $this->input->post("user");
		    

				
			  		  $this->form_validation->set_rules("user", "User name", "trim|required");
			  		  $this->form_validation->set_rules("password", "Password", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbackup', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addbackup') == "backup")
					   {
												$data=array(		
			
			'server'=>$server,
			'path'=>$path,
			'host'=>$host,
			'database'=>$database,
			'userid'=>$userid,
																
			'userid'=>$userid,
			
				'user'=>$user,
							 'location'=>$location,

		  	'host'=>$host,
				 'companyid'=>$companyid,
			'password'=>$password,
			'status'=>$status,

			'createdat'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'backup');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  backup ..</div>');	
							redirect('user/viewbackup');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Backup  was not added.. Try again</div>');
								
								 redirect('user/viewbackup');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }



	
  public function displaylinkwindow()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		   $branch = $this->input->post("branch");
			   		 		   $stockstatus = $this->input->post("stockstatus");

			   
			  		  $this->form_validation->set_rules("branch", "branch", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewopeningstock', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('displaywindow') == "link")
					   {
							//stockstatus
$mylink="";
$finalurl="";

						$baseurl = base_url();

if(	$stockstatus=="open"){
$mylink="openstock";

}else{

$mylink="closestock";

}	
	echo$finalurl=$baseurl.$mylink."?branchid=".$branch;
							exit;	
								
								
								
							$usr_result = $this->usermodel->add($data,'backup');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  backup ..</div>');	
							redirect('user/viewbackup');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Backup  was not added.. Try again</div>');
								
								 redirect('user/viewbackup');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }





 public function addmympesa()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
       
		$userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 	$myuserid = $this->input->post("userid");

		 		 //$myuserid = $userid;
				 
			 

		   	  $dateposted = $this->input->post("dateposted");

			  		   	  $branch = $this->input->post("branch");

		    		 $type = $this->input->post("type");

			 $code = htmlspecialchars(trim($this->input->post("code")));
			 $amount = htmlspecialchars(trim($this->input->post("amount")));

		
					if($code==""){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You do not have right to post mpesa payment. Request for right or Try again</div>');
								
								 redirect('user/viewmympesa');
								 
								 return false;
					}
						
				
			  		  $this->form_validation->set_rules("code", "Transaction code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmympesa', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   
					   
					$mpesastatus="2";
					    $finalamount="";

						$paymentstatus="";
					 	if ($this->input->post('btn_savemympesa') == "mpesa")
					   {
						   
						   	$productname = $this->usermodel->populateallarray('mpesasales','code', $code);

			
				        //$productname = $this->usermodel->geteproductbyid($code);
								
						
						  if ($productname !=false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Transaction code ('.$code.')  has been used. Try again</div>');
								
								 redirect('user/viewmympesa');
								 
								 return false;
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   						   		$mpesaresult = $this->usermodel->populatependingmypayment($code);

						   if($amount==0){
						   

					if($mpesaresult==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Transaction code ('.$code.')  does not exist or has been activated. Try again</div>');
								
								 redirect('user/viewmympesa');
								 
								 return false;
					}
						 

						 } 

				
				
				
		if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
					
			$paymentstatus="Cleared";
			 $finalamount= $mpesaresult['0']['amount']; 
			 $mpesastatus="1";
			 
			 
			 
		$exactime=$mpesaresult[0]['exactime'];




		$claimoldcodes=$this->usermodel->populatuserpermissionsdataarray('sales','claimoldcodes',$userid);



if(trim($claimoldcodes)==false){
$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		

		 
		


			 			if($exactime<$finalstartdate){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Transaction code ('.$code.') with this date  ('.$exactime.') can not be claimed since the shift time has ended. Request admin to help you. Try again</div>');
								
								 redirect('user/viewmympesa');
								 
								 return false;
					}
					
					
					
					
					

					
					
					
					
						 
			 
		}
			 
			 
			 
			 
					
		}else{
			//
			
			
			$paymentstatus="No";
			$finalamount=$amount; 
			$mpesastatus="2";
		}  
						   
						   
						   
						
			
			
			
			
			
			
						   							$paymentdata=array(		
			'id'=>$mpesaid,
			
				'used'=>$mpesastatus,
		
						   
					  	);	


	

   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$myuserid,
			
				'code'=>$code,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
				'type'=>$type,
				 	'amount'=>$finalamount,
			'dateposted'=>$dateposted,
				'paymentstatus'=>$paymentstatus,
			
								);
							$usr_result = $this->usermodel->add($data,'mpesasales');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 $this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid)
								 ;
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Transaction ..</div>');	
							redirect('user/viewmympesa');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> A new  Transaction   was not added.. Try again</div>');
								
								 redirect('user/viewmympesa');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	






	 public function addmergedmpesa()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
       
		// $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 	$myuserid = $this->input->post("userid");

		 		 //$myuserid = $userid;
				 
			 

		   	  $dateposted = $this->input->post("dateposted");

			  		   	  $branch = $this->input->post("branch");

		    		 $type = $this->input->post("type");

			 $code = htmlspecialchars(trim($this->input->post("code")));
			 $amount = htmlspecialchars(trim($this->input->post("amount")));

		
					if($code==""){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You do not have right to post mpesa payment. Request for right or Try again</div>');
								
								 redirect('user/mergempesa');
								 
								 return false;
					}
						
				
			  		  $this->form_validation->set_rules("code", "Transaction code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");


		 $this->load->view('userdata/mergempesa', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   
					   
					$mpesastatus="2";
					    $finalamount="";

						$paymentstatus="";
					 	if ($this->input->post('btn_savemympesa') == "mpesa")
					   {
						   
						   	$productname = $this->usermodel->populateallarray('mpesasales','code', $code);

			
				        //$productname = $this->usermodel->geteproductbyid($code);
								
						
						  if ($productname !=false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Transaction code ('.$code.')  has been used. Try again</div>');
								
								 redirect('user/mergempesa');
								 
								 return false;
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   						   		$mpesaresult = $this->usermodel->populatependingmypayment($code);

						   if($amount==0){
						   

					if($mpesaresult==FALSE){
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This Transaction code ('.$code.')  does not exist or has been activated. Try again</div>');
								
								 redirect('user/mergempesa');
								 
								 return false;
					}
						 

						 } 

				
				
				
		if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
					
			$paymentstatus="Cleared";
			 $finalamount= $mpesaresult['0']['amount']; 
			 $mpesastatus="1";
					
		}else{
			
			
			
			$paymentstatus="No";
			$finalamount=$amount; 
			$mpesastatus="2";
		}  
						   
						   
						   
						
			
			
			
			
			
			
						   							$paymentdata=array(		
			'id'=>$mpesaid,
			
				'used'=>$mpesastatus,
		
						   
					  	);	


	

   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$myuserid,
			
				'code'=>$code,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
				'type'=>$type,
				 	'amount'=>$finalamount,
			'dateposted'=>$dateposted,
				'paymentstatus'=>$paymentstatus,
			
								);
							$usr_result = $this->usermodel->add($data,'mergedmpesa');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 $this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid)
								 ;
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Transaction ..</div>');	
								 redirect('user/mergempesa');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> A new  Transaction   was not added.. Try again</div>');
								
								 redirect('user/mergempesa');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
  public function addmytill()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
       
		 $addedby = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 	$myuserid = $this->input->post("userid");

		 		 //$myuserid = $userid;
				 		   	  $short = $this->input->post("short");


		   	  $dateposted = $this->input->post("dateposted");
			  		   	  $mode = $this->input->post("mode");

			  		   	  $branch = $this->input->post("branch");

		    		 $description = $this->input->post("description");

			 $amount = htmlspecialchars(trim($this->input->post("amount")));
			 $myshort= $amount-$description;

		
				
				
			  		  $this->form_validation->set_rules("amount", "Amount collected", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtill', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   
					   
					

					 	if ($this->input->post('btn_savemytill') == "till")
					   {
						   
						   	$productname = $this->usermodel->populateallarray('mpesasales','code', $code);

			
				     
						   
						   
						   
						   
						   
						   
						   

						   if(($amount==0) || ($amount<0)){
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  The amount can not be zero(0). Try again</div>');
								
								 redirect('user/viewtill');
								 
								 return false;
					 

						 } 

				
				
				
			   
						   
						   
						
			
			
			
			
			
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$myuserid,
						'addedby'=>$addedby,

				'description'=>$description,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
							 'mode'=>$mode,

				 	'amount'=>$amount,
			'dateposted'=>$dateposted,
				'short'=>$myshort,
			
								);
							$usr_result = $this->usermodel->add($data,'tillcollection');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Transaction ..</div>');	
							redirect('user/viewtill');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> A new  Transaction   was not added.. Try again</div>');
								
								 redirect('user/viewtill');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
  public function adduom()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $code = $this->input->post("code");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Unit name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adduom') == "uom")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'code'=>$code,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'uom');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  UOM..</div>');	
							redirect('user/viewuom');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM  was not added.. Try again</div>');
								
								 redirect('user/viewuom');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
		
  public function adduompricemain()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 							 $mybranchid = trim($this->input->post("mybranchid"));

		 		
		 		 $uom = $this->input->post("uom");
		 		 $page = $this->input->post("page");

		   	  $branch = $this->input->post("branch");
			  		   	  $code = $this->input->post("code");
								  		   	  $mybranchid = $this->input->post("mybranchid");


		    			  		   	  $qty = $this->input->post("qty");
	 $brice = trim($this->input->post("brice"));
									
									  	$price = $this->input->post("price");
									  	$status = $this->input->post("status");

$data['itemid']=$code;
$data['page']=$page;
				
			  		  $this->form_validation->set_rules("uom", "Unit name", "trim|required");

			  

   			        		$data['viewprice'] = $this->usermodel->populateall('productlist','code', $code);
   			        		$data['product'] = $this->usermodel->populateall('products','code', $code);
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewprice', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adduomprice') == "adduomprice")
					   {
						   
				$getprice = $this->usermodel->populateallarray('products','code',trim($uom));
		   
				$mybrice=$getprice[0]["buyingprice"] * $qty;		   
				$mysprice=$getprice[0]["sellingprice"] * $qty;		   

				//$mybrice=$brice *$qty;		   
			//$mysprice=$price*$qty;		   
	   		   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'uom'=>$uom,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
				 				 'price'=>$price,
				 				 'qty'=>$qty,

			'code'=>$code,
			'brice'=>$brice,
			'createdate'=>$dateposted,
							'status'=>$status,

			
								);
							$usr_result = $this->usermodel->add($data,'uomproducts');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
						   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
								
														  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);

													      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
						   

						   
						   return false;
						   }											
							$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		
		
		
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

if($onlineoffline=="OSCU"){
   $apiUrl = ''.$etimsurl.'/etims-api/saveItemComposition';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/saveItemComposition';

			 }
			    

        // Data to send in the JSON format
		
		
			$productname = $this->usermodel->populateallarray('products','code', $code);
			$productnamechild = $this->usermodel->populateallarray('products','code', $uom);
						 
				
		  	$item_code=$productname[0]['hscode']; 
				  	$composition_item_code=$productnamechild[0]['hscode']; 

		
		
		
        $data = [
		  "tin" => $kra_pin,
            "bhfId" => $branch_id,
            "itemCd" => $item_code,
            "cpstItemCd" => $composition_item_code,
            "cpstQty" => $qty,
            "regrId" => "Admin",
            "regrNm" => "Admin"
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);
        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
		
		
 // Check for cURL errors
        if (curl_errno($ch)) {
              $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
						   

						   
						   return false;
        } else {
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];


            if ($resultCd == '000') {

                //\Log::debug('eTims Response From Saving item Composition.', $responseArray);
            }else{
				
			}
	 	
								
		}						
								
								
		 }					
								
								
								
								

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  UOM price..</div>');	
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM  was not added.. Try again</div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
		
  public function adduomprice()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 							 $mybranchid = trim($this->input->post("mybranchid"));

		 		
		 		 $uom = $this->input->post("uom");
		 		 $page = $this->input->post("page");

		   	  $branch = $this->input->post("branch");
			  		   	  $code = $this->input->post("code");
								  		   	  $unitprice = $this->input->post("unitprice");


		    			  		   	  $qty = $this->input->post("qty");
	 $brice = trim($this->input->post("brice"));
									
									  	$price = $this->input->post("price");
									  	$status = $this->input->post("status");
									  
									

$data['itemid']=$code;
$data['page']=$page;
				
			  		  $this->form_validation->set_rules("uom", "Unit name", "trim|required");

			  

   			        		$data['viewprice'] = $this->usermodel->populateall('productlist','code', $code);
   			        		$data['product'] = $this->usermodel->populateall('products','code', $code);
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewprice', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adduomprice') == "adduomprice")
					   {
						   
				$getprice = $this->usermodel->populateallarray('products','code',trim($uom));
		      

				//$mybrice=$brice *$qty;		   
			//$mysprice=$price*$qty;		

if($unitprice=="Yes"){

				//$mybrice=$getprice[0]["buyingprice"] * $qty;		   
				$mysprice=$getprice[0]["sellingprice"] * $qty;	


				$stocklist  = $this->usermodel->populatealldatarrayfour('uomproducts','code',$code,'branch', $branch,'status',"child",'unitprice<>', "Yes");

if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	      $allbrice=trim($row->brice);
		  
	   $ttbbprice=$ttbbprice+$allbrice;

		

		
   }
   
    $mybrice=$this->formatMoney((($qty/100)*$ttbbprice),true);	
 
	

}








				


}else if($unitprice=="YesSingle"){
	
				$mybrice=(($getprice[0]["buyingprice"]/100) * $qty);	

 $mybrice=  $this->formatMoney($mybrice, true);				
				$mysprice=$getprice[0]["sellingprice"] * $qty;		
	
}else{
	
	
				$mybrice=$getprice[0]["buyingprice"] * $qty;		   
				$mysprice=$getprice[0]["sellingprice"] * $qty;		
				$mybrice=$getprice[0]["buyingprice"] * $qty;		   
				$mysprice=$getprice[0]["sellingprice"] * $qty;		
	
	
}
	   		   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'uom'=>$uom,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
				 				 'price'=>$mysprice,
				 				 'qty'=>$qty,

			'updatedate'=>"Active",
			'code'=>$code,
			'brice'=>$mybrice,
			'createdate'=>$dateposted,
							'status'=>$status,
							'unitprice'=>$unitprice,

			
								);
							$usr_result = $this->usermodel->add($data,'uomproducts');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
						   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
								
														  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);

													      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
						   

						   
						   return false;
						   }											
							$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encrypt->decode(trim($configuration[0]["verification"]),"KENGA"));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		
		
		
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

if($onlineoffline=="OSCU"){
   $apiUrl = ''.$etimsurl.'/etims-api/saveItemComposition';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/saveItemComposition';

			 }
			    

        // Data to send in the JSON format
		
		
			$productname = $this->usermodel->populateallarray('products','code', $code);
			$productnamechild = $this->usermodel->populateallarray('products','code', $uom);
						 
				
		  	$item_code=$productname[0]['hscode']; 
				  	$composition_item_code=$productnamechild[0]['hscode']; 

		
		
		
        $data = [
		  "tin" => $kra_pin,
            "bhfId" => $branch_id,
            "itemCd" => $item_code,
            "cpstItemCd" => $composition_item_code,
            "cpstQty" => $qty,
            "regrId" => "Admin",
            "regrNm" => "Admin"
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);
        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
		
		
 // Check for cURL errors
        if (curl_errno($ch)) {
              $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
						   

						   
						   return false;
        } else {
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];


            if ($resultCd == '000') {

                //\Log::debug('eTims Response From Saving item Composition.', $responseArray);
            }else{
				
			}
	 	
								
		}						
								
								
		 }					
								
								
								
								

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  UOM price..</div>');	
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM  was not added.. Try again</div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  public function addbranchuomprice()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $uom = $this->input->post("uom");
		 		 $page = $this->input->post("page");

		   	  $branch = $this->input->post("branch");
			  		   	  $code = $this->input->post("code");

		    			  		   	  $qty = $this->input->post("qty");
	 $brice = trim($this->input->post("brice"));
									
									  	$price = $this->input->post("price");
									  	$status = $this->input->post("status");

$data['itemid']=$code;
$data['page']=$page;
				
			  		  $this->form_validation->set_rules("uom", "Unit name", "trim|required");

			  

   			        		$data['viewprice'] = $this->usermodel->populateall('productlist','code', $code);
   			        		$data['product'] = $this->usermodel->populateall('products','code', $code);
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewprice', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adduomprice') == "adduomprice")
					   {
						   
				$getprice = $this->usermodel->populateallarray('products','code',$uom);
		   
				$mybrice=$getprice[0]["buyingprice"]*$qty;		   
				$mysprice=$getprice[0]["sellingprice"]*$qty;		   
	   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'uom'=>$uom,
			
		  	'branch'=>$branch,
				 'companyid'=>$companyid,
				 				 'price'=>$mysprice,
				 				 'qty'=>$qty,

			'code'=>$code,
'brice'=>$mybrice,
			'createdate'=>$dateposted,
							'status'=>$status,

			
								);
							$usr_result = $this->usermodel->add($data,'uomproducts');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  UOM price..</div>');	
							redirect('user/viewbranchproduction?mycode='.$code.'&page='.$page.'&branch='.$branch);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM  was not added.. Try again</div>');
								
							redirect('user/viewbranchproduction?mycode='.$code.'&page='.$page.'&branch='.$branch);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	

 
  
  public function addpayrollsetup()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
		
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $code = $this->input->post("code");
			  $category = $this->input->post("category");

			  
			   $amountmode = $this->input->post("amountmode");
			   $amount = $this->input->post("amount");
			  $qtymode = $this->input->post("qtymode");
			  $quantity = $this->input->post("quantity");
			  $unit = $this->input->post("unit");

						  $status = $this->input->post("status");

			  						  $action = $this->input->post("action");
			  						  $mycategoryid = $this->input->post("mycategoryid");

			  
			  
			  
		     $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/payrollsetup', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsalarycharges') == "salarycharges")
					   {
												$data=array(

			'amountmode'=>$amountmode,
			'amount'=>$amount,
			'code'=>$code,
			'qtymode'=>$qtymode,
			'quantity'=>$quantity,
			'unit'=>$unit,
																
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'code'=>$code,
				 'companyid'=>$companyid,
			'category'=>$category,
			'status'=>$status,

			'createdate'=>$dateposted,
				
			
								);
								
								 if($action=="insert"){
										$usr_result = $this->usermodel->add($data,'salarycharges');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'salarycharges','id',$mycategoryid);

								}
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Payment.</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
  
  public function processsinglepayment()
    {
		
			$session_data = $this->session->userdata('logged_in');
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];

				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 $salaryid = $companyid.$userid.time();
		 		 $myid = $this->input->post("myid");

		   	  $salaryyear = $this->input->post("salaryyear");
			 
			 // $myid = $this->input->post("myid");

			  //
			   $slarymonth = $this->input->post("slarymonth");
			 
			  			   $payment = $this->input->post("payment");

			  			   $branchid = $this->input->post("branchid");
			  
		     $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("salaryyear", "Year", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/mypayrollsetup', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_processpayment') == "payment")
					   {
						   
        		$people = $this->usermodel->populateallarray('people','id',$myid);






 $confirmsalary = $this->usermodel->populatealldataarrayfour('salary','memberid', $myid,'slarymonth', $slarymonth,'salaryyear', $salaryyear,'paymentmode', $payment);

	 if($confirmsalary !=false) 

 {
	 
 $updatesalary=$this->usermodel->populatuserpermissionsdataarray('payroll','updatesalary',$userid);
 	if($updatesalary==true){
	$salaryid=$confirmsalary[0]["salaryid"]; 
	 $this->usermodel->deletedata($salaryid,"salaryid","salary");
	 	 $this->usermodel->deletedata($salaryid,"salaryid","employeepayments");

	
			 $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> Salary for this employee for  same month, year and method had been processed earlier and it has now been updated with latest details.</div>');
								redirect($view);
								//return false;
								
	}else{
		
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> Salary for this employee for  same month, year and method had been processed earlier. You can cancel it then try process a new one. Same payroll can not be processed twice. Try again</div>');
								redirect($view);
								return false;
		
	}
	
 }





	$mainrelief = $this->usermodel->populatealldatanorraythree('constants','id>', 0,'category',"Relief",'companyid', $companyid);
   
						   
						   
						   
						   
		 $salary=$people[0]['salary'];
		 $bankname=$people[0]['bankname'];		
			$bankaccount=$people[0]['bankaccount'];
		 $paymentmode=$people[0]['paymentmode'];	
$method=$people[0]['method'];
		 $number=$people[0]['number'];	
			 
								// $payment=$people[0]['payment'];	
   
						   
						   $pay=0;
						   
						  $bonus=0;
						   $deduction=0;
						   $relief=0;
						   
							$NSSF=0;
						   $NHIF=0;
						   $PAYE=0;	   
						    $HOUSELEVY=0;	
						   
						   
						   
   $gross=0;
      $nhifrelief=0;

		 $mygross=0;		
	$relief=$mainrelief[0]['amount'];			 
			//	
	$nhifrelief=$people[0]['nhifrelief'];			 
			
			  $myrequestedproducts = $this->usermodel->populatealldatanoarray('employeecharges','memberid', $myid,'status', "Active");



if(is_array($myrequestedproducts)) {

   foreach($myrequestedproducts as $row)
   {
	   $statutory=trim($row->statutory);
   $category=trim($row->category);
    $qtymode=trim($row->qtymode);
    $unit=trim($row->unit);
    $status=trim($row->status);
    $name=trim($row->name);
    $code=trim($row->code);

   $quantity=trim($row->quantity);
    $amount=trim($row->amount);
	  $amountmode=trim($row->amountmode);
	 $total=$quantity*$amount;
	 if($category!="Deduction"){
			$gross=$gross+$total;

		}
		if($category=="Pay"){
						$pay=$pay+$total;

		}else if($category=="Deduction"){
						$deduction=$deduction+$total;

		}else if($category=="Bonus"){
			$bonus=$bonus+$total;
		}else {
			
			
	

		
						
						   
		
						//$relief=$relief+$total;

			}	


		
			if($statutory=="NSSF"){
			 $NSSF=$NSSF+$total;
		
			}
		if($statutory=="NHIF"){
			$NHIF=$NHIF+$total;
		
			}
				if($statutory=="PAYE"){
			$PAYE=$PAYE+$total;
				
			}
				if($statutory=="HOUSE LEVY"){
			$HOUSELEVY=$HOUSELEVY+$total;
								

			}






			$data=array(

			'amountmode'=>$amountmode,
			'amount'=>$amount,
		
			'qtymode'=>$qtymode,
			'quantity'=>$quantity,
			'unit'=>$unit,
			'userid'=>$userid,
			'code'=>$code,
						
			'memberid'=>$myid,
			
				'name'=>$name,
			'salaryid'=>$salaryid,

				 'companyid'=>$companyid,
			'category'=>$category,
			'status'=>$status,

			'createdate'=>$dateposted,
					);
			$this->usermodel->add($data,'employeepayments');


			
   }
}   
						   
						   
			$mygross=$gross	+ $salary;	   
				$netsalry=	$mygross-$deduction;   
					
						   
						   
						   
							  $myrequestedproducts = $this->usermodel-> getloanbalance($companyid,$myid);
		   
						   $loanbalance= $myrequestedproducts[0]["paid"]-$myrequestedproducts[0]["loanpaid"];
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(

			'salary'=>$salary,
						'relief'=>$relief,
							'nhifrelief'=>$nhifrelief,

			'bankname'=>$bankname,
			'paymentmode'=>$paymentmode,
			'bankaccount'=>$bankaccount,
			'method'=>$method,
					'userid'=>$userid,
														'branchid'=>$branchid,

									'gross'=>$mygross,
									'netsalry'=>$netsalry,
									'loanbalance'=>$loanbalance,

			'memberid'=>$myid,
				'salaryyear'=>$salaryyear,
				'slarymonth'=>$slarymonth,

				'number'=>$number,
			
				 'companyid'=>$companyid,
						'payment'=>$payment,
						'salaryid'=>$salaryid,

					'nhif'=>$NHIF,
						'nssf'=>$NSSF,
						'paye'=>$PAYE,
						'houselevy'=>$HOUSELEVY,

					
						   
						 'pay'=>$pay,
			'bonus'=>$bonus,
			'deductions'=>$deduction,
			  
						   
			'createdate'=>$dateposted,
				
			
								);
								
								
										$usr_result = $this->usermodel->add($data,'salary');

						
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully processed salary.</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Salary was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
  
  public function processbulkpayroll()
    {
		
			$session_data = $this->session->userdata('logged_in');
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];

				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 $salaryid = $companyid.$userid.time();
		 		 $myid = "";
  $payment = "";
		   	  $salaryyear = $this->input->post("salaryyear");
			 
		   	  $jobstatus = $this->input->post("jobstatus");
			  		   	  $branchid = $this->input->post("branchid");


			  //
			   $slarymonth = $this->input->post("slarymonth");
			 			   $category = $this->input->post("category");

		
			  
		     $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("salaryyear", "Year", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/salaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_processbulkpayroll') == "bulkpayment")
					   {
						   
        		//$people = $this->usermodel->populateallarray('people','id',$myid);

   if($category !="all"){
						$mypeople = $this->usermodel->populatealldatanoarrayfive('people','status', 1,'category', "user",'paid',"Yes",'branchid',$branchid,'group',$category);
   
   }else{
	 					$mypeople = $this->usermodel->populatealldatanoarrayfour('people','status', 1,'category', "user",'paid', "Yes",'branchid',$branchid);
  
   }
						   

	 if(is_array($mypeople)) 

 {
	foreach ($mypeople as $people){
		
		//
		$salaryid =$salaryid +1;
		
		
				//$salary=$people->salary;
	 $salary=$people->salary;
		 $bankname=$people->bankname;		
			$bankaccount=$people->bankaccount;
		 $paymentmode=$people->paymentmode;	
$method=$people->method;
		 $number=$people->number;	
		 		 $nhifrelief=$people->nhifrelief;
if(trim($people->nhifrelief)==0){
	 $nhifrelief=0;
}
				 

			 $myid = $people->id;
  $payment =  $people->paymentmode;		
							$mainrelief = $this->usermodel->populatealldatanorraythree('constants','id>', 0,'category',"Relief",'companyid', $companyid);




 $confirmsalary = $this->usermodel->populatealldatanoarrayfour('salary','memberid', $myid,'slarymonth', $slarymonth,'salaryyear', $salaryyear,'paymentmode', $payment);
	 if(!is_array($confirmsalary)){

					   
						   
	
			 
								// $payment=$people[0]['payment'];	
   $deduction=0;
   
   	  		 
						   $pay=0;
						   
						  $bonus=0;
						//   $deduction=0;
						   $relief=0;
						   
						  		$NSSF=0;
						   $NHIF=0;
						   $PAYE=0;	   
						    $HOUSELEVY=0; 
						   
						   
						   
						   
   $gross=0;
		 $mygross=0;		 

							
	$relief=$mainrelief[0]['amount'];			 
			//			   
			  $myrequestedproducts = $this->usermodel->populatealldatanoarray('employeecharges','memberid', $myid,'Status', "Active");

if(is_array($myrequestedproducts)) {

   foreach($myrequestedproducts as $row)
   {
	     $statutory=trim($row->statutory);
   $category=trim($row->category);
    $qtymode=trim($row->qtymode);
    $unit=trim($row->unit);
    $status=trim($row->status);
    $name=trim($row->name);
    $code=trim($row->code);

   $quantity=trim($row->quantity);
    $amount=trim($row->amount);
	  $amountmode=trim($row->amountmode);
	 $total=$quantity*$amount;
	 if($category!="Deduction"){
			$gross=$gross+$total;

		}
		if($category=="Pay"){
						$pay=$pay+$total;

		}else if($category=="Deduction"){
						$deduction=$deduction+$total;

		}else if($category=="Bonus"){
			$bonus=$bonus+$total;
		}else {
			
			
			
		
						//$relief=$relief+$total;

			}	
			
			
				if($statutory=="NSSF"){
			 $NSSF=$NSSF+$total;
		
			}
		if($statutory=="NHIF"){
			$NHIF=$NHIF+$total;
		
			}
				if($statutory=="PAYE"){
			$PAYE=$PAYE+$total;
				
			}
				if($statutory=="HOUSE LEVY"){
			$HOUSELEVY=$HOUSELEVY+$total;
								

			}
			
			
			

			$data=array(

			'amountmode'=>$amountmode,
			'amount'=>$amount,
		
			'qtymode'=>$qtymode,
			'quantity'=>$quantity,
			'unit'=>$unit,
			'userid'=>$userid,
			'code'=>$code,
						
			'memberid'=>$myid,
			
			'name'=>$name,
			'salaryid'=>$salaryid,

				 'companyid'=>$companyid,
			'category'=>$category,
			'status'=>$status,

			'createdate'=>$dateposted,
					);
			$this->usermodel->add($data,'employeepayments');


			
   }
}   
			
			   
						   
			$mygross=$gross	+ $salary;	   
				$netsalry=	$mygross-$deduction;   
					
						   
						   
												$data=array(

			'salary'=>$salary,
			'relief'=>$relief,
			'nhifrelief'=>$nhifrelief,
			'bankname'=>$bankname,
			'paymentmode'=>$paymentmode,
			'bankaccount'=>$bankaccount,
			'method'=>$method,
					'userid'=>$userid,
			'gross'=>$mygross,
			'netsalry'=>$netsalry,

			'memberid'=>$myid,
				'salaryyear'=>$salaryyear,
				'slarymonth'=>$slarymonth,

				'number'=>$number,
			
				 'companyid'=>$companyid,
						'payment'=>$payment,
						'salaryid'=>$salaryid,

							'nhif'=>$NHIF,
						'nssf'=>$NSSF,
						'paye'=>$PAYE,
						'houselevy'=>$HOUSELEVY,
						   
						   
						 'pay'=>$pay,
						'bonus'=>$bonus,
						'deductions'=>$deduction,
			  
						   
						'createdate'=>$dateposted,
				
			
								);
								
								
										$usr_result = $this->usermodel->add($data,'salary');

	}
								
								
								}
  	
 }	   
	
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully processed salary.</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Salary was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
  public function updateloanpayment()
    {
		
$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		 $mydateposted = date('Y-m-d H:i:s');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
		  $dateposted = $this->input->post("dateposted");
 		$dateposted =  ($dateposted)." ".$currenttime ;
		 $userid = $data['id'];
		        
  $month = Date('F') ;
		 			   	  $code = $this->input->post("code");


		   	  $description = $this->input->post("description");

		   	  $amount = $this->input->post("amount");
			  
		    		   	  $itemid = $this->input->post("itemid");
		    		   	  $view = $this->input->post("view");

		    		   	  $status = $this->input->post("status");

				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewloan', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updatealoandvance') == "loanadvance")
					   {
						   
						   
						   
						   
						   
						   $myadvance = $this->usermodel->populateallarray('expenses','id', $itemid);

	 $mybalance=$myadvance[0]['loanbalance'];
	 $customer=$myadvance[0]['supplier'];
	
	
		 $myamount=$myadvance[0]['paid'];
		  $mypaid=$myadvance[0]['loanpaid'];

		 			   $balance = $mypaid-$amount;
							$finalpaid = $mypaid+$amount;
	
								
								if ($finalpaid > $myamount)	{
									
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The balance ('.$balance.')is less then what you are paying ('.$amount.'). Try again</div>');
								
							redirect($view);
									return false;
								}						

								
														     $products=$this->usermodel->populateallarray('salarycharges','code', $code);

									
								if ($products !=true)	{
									
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The loan/advance code ('.$code.') doest not exist. Try again</div>');
								
							redirect($view);
									return false;
								}						

								
								
								
								
								
								
								
								
						    $productdata=array(		
						'loanbalance'=>$balance,
						'loanpaid'=>$finalpaid,
												'status'=>$status,

						
						);
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
			'description'=>$description,

		  	'balance'=>$balance,
			
			'companyid' => $companyid,
				'amount' => $amount,
			'createdat'=>$dateposted,
							'advanceid'=>$itemid,

			
								);
							$usr_result = $this->usermodel->add($data,'advancepayment');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							 $this->usermodel->updatedata($productdata,'expenses','id',$itemid);
								 
								 
								 
								 
								 	$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
													$employeeid=$people[0]["idno"];


			
								$finalcustomerbalance=$supplierbalance-$amount;
	
			
				
				
				
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
							'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
								 
								 
								 
								
						     $products=$this->usermodel->populateallarray('salarycharges','code', $code);
									
								
						   
						   
						   
						   
						   
						   
						   
						   
									
												$data=array(		
			
				 	'userid'=>$userid,
			
				'code'=>$code,
				'employeeid'=>$employeeid,
				'createdate'=>$dateposted,
								'rate'=>1,
								'total'=>1,

				'month'=>$month,

				'description'=>$description,
				'branch'=>$branchid,
				'qty'=>$amount,


				 'companyid'=>$companyid,
				 'exactdate'=>$mydateposted,

				
				
			
								);
								$this->usermodel->add($data,'labour'); 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted payment deduction..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Payment deduction  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
  
  public function processbulklabour()
    {
		
			$session_data = $this->session->userdata('logged_in');
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];

				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 $salaryid = $companyid.$userid.time();
		 		 $myid = "";
  $payment = "";
			 		   	  $branchid = $this->input->post("branchid");
	  $bankname = $this->input->post("bankname");
		   	  $fromdate = $this->input->post("fromdate");
			  		   	  $todate = $this->input->post("todate");


			  //
			   $slarymonth = $this->input->post("slarymonth");
			 
			  		   
						   $pay=0;
						   
						  $bonus=0;
						   $deduction=0;
						   $relief=0;
   $gross=0;
		 $mygross=0;		 

			  
		     $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("slarymonth", "Month", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/salaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_processbulkLoabour') == "labour")
					   {



   	   	$mylabour = $this->usermodel->populatealllabourbydate('labour','labour.companyid', $companyid,'labour.branch', $branchid,$slarymonth, $fromdate, $todate);








	 if(is_array($mylabour)) 

 {
	foreach ($mylabour as $mylabourrow){
		
		
		
		
				//$salary=$people->salary;
	 $mycode=$mylabourrow->mycode;
		 $myemployeenumber=$mylabourrow->employeeid;		
			$myqty=$mylabourrow->myqty;
		 
			 $myid = $mylabourrow->myid;
			
			 
			//			   
			  $myrequestedproducts = $this->usermodel->populatealldataarray('employeecharges','memberid', $myid,'code', $mycode);

   
    $unit=$myrequestedproducts[0]["unit"];
	 $total=$unit*$myqty;
    $currentid=$myrequestedproducts[0]["id"];
	
		
	$data=array(

			'quantity'=>$myqty,
			//'amount'=>$total,
		

			'updatedate'=>$dateposted,
					);
			


			
 
	
															 	$updateArray[] =array(	
																'id'=>$currentid,
															'quantity'=>$myqty,
																//'amount'=>$total,
		

																'updatedate'=>$dateposted,
																);	

														   }

														$RESULT =	$this->db->update_batch('employeecharges',$updateArray, 'id');
  	
 }	   
	
							//check if username and password is correct
							if($this->db->affected_rows() > 0)
						{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully processed labour payments.</div>');	
							redirect($view);																
							}else {     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Labour payment was not processed.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
 
 
 
  
  public function assignpayrollsetup()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $code = $this->input->post("code");
			  $category = $this->input->post("category");
			  $myid = $this->input->post("myid");

			  
			   $amountmode = $this->input->post("amountmode");
			   $amount = $this->input->post("amount");
			  $qtymode = $this->input->post("qtymode");
			  $quantity = $this->input->post("quantity");
			  $unit = $this->input->post("unit");
						  $statutory = $this->input->post("statutory");

						  $status = $this->input->post("status");

			  						  $action = $this->input->post("action");
			  						  $mycategoryid = $this->input->post("mycategoryid");

			
			  
			  
		     $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/payrollsetup', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsalarycharges') == "salarycharges")
					   {
						   
						   
						  if($action=="insert")//active user record is present
							{
						   
					 $mysalary = $this->usermodel->populatealldataarray('employeecharges','code', $code,'memberid', $myid);

						   	if ($mysalary !=FALSE) //active user record is present
							{
								
								 
						
			 $this->session->set_flashdata('activemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> '.$name.' could not be added  as '.$category.' since it exist .Try again</div>');
							redirect($view);	
									return false;
							}
						
						   
						   }
						   
						   
						   
						   
						   
						   
						   
												$data=array(

			'amountmode'=>$amountmode,
			'amount'=>$amount,
			'code'=>$code,
			'qtymode'=>$qtymode,
			'quantity'=>$quantity,
			'unit'=>$unit,
			'userid'=>$userid,
											
			'memberid'=>$myid,
			
				'name'=>$name,
			
		  	'code'=>$code,
				 'companyid'=>$companyid,
			'category'=>$category,
			'status'=>$status,
			'statutory'=>$statutory,

			'createdate'=>$dateposted,
				
			
								);
								
								 if($action=="insert"){
										$usr_result = $this->usermodel->add($data,'employeecharges');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'employeecharges','id',$mycategoryid);

								}
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('activemsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Payment.</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('activemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
  
  public function startprojectdispatch()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		   	  $invoice = $this->input->post("invoice");

		   	  $description = $this->input->post("description");

			  		   	  $startdate = $this->input->post("startdate");
			  		   	  $salestype = $this->input->post("salestype");

						  	 $frombranch = $this->input->post("frombranch");
		    			  		   	  $status = $this->input->post("status");

		    			  		   	  $view = $this->input->post("view");
		    			  		   	  $type = $this->input->post("type");
		    			  		   	  $category = $this->input->post("category");
		    			  		   	  $approvedby = $this->input->post("approvedby");

			  		   	 // $supplier = $this->input->post("supplier");
			  		   	  $project = $this->input->post("project");
$suppliers = explode(':=',$this->input->post("supplier"));

 				
  $supplier = htmlspecialchars(trim($suppliers[0]));


	  $tobranch="";

if($supplier !=""){
	 $tobranch=$supplier;
	
}else{
	
		 $tobranch=$project;

	
	
}






		
				
			  		  $this->form_validation->set_rules("frombranch", "From name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addprojectdispatch') == "startproject")
					   {
												$data=array(		
			'userid'=>$userid,
						'branchid'=>$branchid,

				'name'=>$name,
			'tobranch'=>$tobranch,
				 'frombranch'=>$frombranch,
			'invoice'=>$invoice,
		  	'description'=>$description,
					  	'status'=>$status,

				 'companyid'=>$companyid,
			'startdate'=>$startdate,
			'category'=>$category,

			'createdate'=>$dateposted,
				
						'type'=>$type,
						'remarks'=>"new",

								);
							$usr_result = $this->usermodel->add($data,'bulkdispatch');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
								 
								 
								
   if($name!=""){
	 
   $correctime = date("d/m/Y H:i", strtotime($dateposted));

		
	   			$applicant=$this->usermodel->populateallarray('people','id', $userid);
		$applicantname=$applicant[0]['firstname'];
		
	
		
							$mycustomer=$this->usermodel->populateallarray('people','id', $name);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];


	   
	   	$message="Dear ".$firstname.", ".$applicantname." applied for items  on ". $correctime .". Kindly Check your erp for action.";

  
														
													
									$myview=$view;				  
		  $this->addallpushedsms($message,$contact,$myview);	
							
	   
	   
   } 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product dispatch..</div>');	
					
redirect('user/bulkdispatch?invoice='.$invoice.'&type='.$type.'&frombranch='.$frombranch.'&tobranch='.$tobranch.'&status='.$status.'&category='.$category .'&salestype='.$salestype);	

							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product dispatch was not started.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
  
  public function startdispatch()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $salestype = $this->input->post("salestype");

		 		 $name = $this->input->post("name");
		   	  $invoice = $this->input->post("invoice");

		   	  $description = $this->input->post("description");

			  		   	  $startdate = $this->input->post("startdate");
			  		   	  $tobranch = $this->input->post("tobranch");
			  		   	  $enddate = $this->input->post("enddate");

						  	 $frombranch = $this->input->post("frombranch");
		    			  		   	  $status = $this->input->post("status");

		    			  		   	  $view = $this->input->post("view");
		    			  		   	  $type = $this->input->post("type");
		    			  		   	  $category = $this->input->post("category");


		
				
			  		  $this->form_validation->set_rules("invoice", "invoice code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addstartdispatch') == "start")
					   {
						   
						   
						   
						 
							  	if (($tobranch == $frombranch)&& ($type=="Transfer")){
									
											 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not move  products to the same branch / source.  To and from should not be the same.. Try again</div>');
								redirect($view);	
								return false;	
									
								}
								    
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
						'branchid'=>$branchid,

				'name'=>$name,
			'tobranch'=>$tobranch,
				 'frombranch'=>$frombranch,
			'invoice'=>$invoice,
		  	'description'=>$description,
					  	'status'=>$status,

				 'companyid'=>$companyid,
			'startdate'=>$startdate,
			'enddate'=>$enddate,

			'createdate'=>$dateposted,
				
						'type'=>$type,

								);
							$usr_result = $this->usermodel->add($data,'bulkdispatch');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product dispatch..</div>');	
					
redirect('user/bulkdispatch?invoice='.$invoice.'&type='.$type.'&frombranch='.$frombranch.'&tobranch='.$tobranch.'&status='.$status.'&category='.$category.'&salestype='.$salestype);	
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product dispatch was not started.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
 
  
  public function addproductcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    			  		   	  $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addproductcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'maincategory'=>$maincategory,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'productcategory');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product Category..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product Category was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
  public function addproductcustomedcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
				
					$data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
	 	 $branchid = $this->input->post("branchid");
	 
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    			  		   	  $view = $this->input->post("view");
		    			  		   	  $action = $this->input->post("action");

				    			  		   	  $itemid = $this->input->post("itemid");

				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addproductcustomedcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'branchid'=>$branchid,

			'createdate'=>$dateposted,
				
			
								);
							


		 if($action=="insert"){
						  							$usr_result = $this->usermodel->add($data,'customedproductcategory');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'customedproductcategory','id',$itemid);

								}

						   
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Customed Product Category..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Customed Product Category was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

			public function viewuom()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['uom']= $this->usermodel->populateall('uom','companyid',$companyid);

	

				$this->load->view('userdata/viewuom',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
			public function viewcustomedproductcategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['maincategory']= $this->usermodel->populateall('maincategory','companyid',$companyid);

							$data['viewproductcategory']= $this->usermodel->populateall('customedproductcategory','companyid',$companyid);


				$this->load->view('userdata/viewcustomedproductcategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
			public function viewproductcategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['maincategory']= $this->usermodel->populateall('maincategory','companyid',$companyid);

	
		$data['viewproductcategory'] = $this->usermodel->populatemyproductcategory($companyid);

				$this->load->view('userdata/viewproductcategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
			public function viewproductcategorybox()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewproductcategory']= $this->usermodel->populateall('productcategorybox','companyid',$companyid);

	
		//$data['viewproductcategory'] = $this->usermodel->populatemyproductcategory($companyid);

				$this->load->view('userdata/viewproductcategorybox',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
  
  public function updateproductcategorybox()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	  $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");
			  		   	  $type = $this->input->post("type");

		    
		   	  $commission = $this->input->post("commission");
			  		   	  $shipping = $this->input->post("shipping");
			  		   	  $status = $this->input->post("status");
			  		   	  $imgid = $this->input->post("imgid");

		 	  $icon = $this->input->post("icon");
			  		   	  $myheader = $this->input->post("myheader");

		

			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproductcategorybox', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatecategory') == "category")
					   {					  
	
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'status'=>$status,
				'type'=>$type,

			'createdate'=>$dateposted,
				'maincategory'=>$maincategory,
			'commission'=>$commission,
				'shipping'=>$shipping,
					'myheader'=>$myheader,

				'icon'=>$icon,

								);
							

												$usr_result = $this->usermodel->updatedata($data,'productcategorybox','id',$mycategoryid);
	
						
					

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										
			
						
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the product category..</div>');	
							redirect('user/viewproductcategorybox');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> product Category  was not Updated.. Try again</div>');
								
								 redirect('user/viewproductcategorybox');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    
	}
	
	
	
	
	
	
	
	
	
	
	
  public function addproductcategorybox()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    			  		   	  $view = $this->input->post("view");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addproductcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'maincategory'=>$maincategory,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'productcategorybox');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product Category..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product Category was not added.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
	
	
	
	
	
	
			public function reseller()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/resellerpage");
		
					

				$this->load->view('userdata/viewreseller',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
			public function payrollsetup()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['payrollsetup']= $this->usermodel->populateall('salarycharges','companyid',$companyid);

	

				$this->load->view('userdata/payrollsetup',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
public function viewmember()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
				$config['base_url'] = base_url('Systemusers/viewmember');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','member');
			//	$config['total_rows'] = $this->usermodel->count_allwheredata('people','branchid',$branchid,'category','member');

		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
	       // $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','branchid',$branchid,'category','member');

        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','member');

			
		       // $data["viewmember"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'people','companyid',$companyid,'category',"member","zip","asc");

		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewmember',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
		
	
	
	
public function viewcomputerno()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
				$config['base_url'] = base_url('Systemusers/viewmember');
		$config['total_rows'] = $this->usermodel->count_allwheredata('peopleregistration','id >',0,'category','member');
			//	$config['total_rows'] = $this->usermodel->count_allwheredata('people','branchid',$branchid,'category','member');

		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
	       // $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','branchid',$branchid,'category','member');

        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'peopleregistration','id >',0,'category','member');

			
		       // $data["viewmember"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'people','companyid',$companyid,'category',"member","zip","asc");

		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		//	$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewcomputer',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
			public function opencloseshift()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
			$data['viewmember'] = $this->usermodel->populatealldatanoarray('people','category', "user",'companyid', $companyid);

		$data['links'] ="";
		$data['total_rows'] =count((array)$data['viewmember']);

				$this->load->view('userdata/opencloseshift',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
public function recorddelivery()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/recorddelivery');
		$config['total_rows'] = $this->usermodel->count_allwheredata('delivery','companyid',$companyid,'branch',$branchid);
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
	
        $data["delivery"] = $this->usermodel->displayalldatadelivery($config["per_page"], $page,'delivery','companyid',$companyid,'branch',$branchid);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["page"] =$page;
				$data["total_rows"] =$config['total_rows'];

		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/recorddelivery',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	public function trialbalance()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
													

	
		
				
				 if ($this->input->post('btn_report') == "report")
					   { 
				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
					   $branchid = $this->input->post("branchname");
		
					 	 $frotime="00:00:00";
					$totime="23:59:59";
	  
	  
	  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

	  
					   }else{
															$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

						   
															 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }																 
						   
 		   
	 
	 
	 
	 
	 
	 
	 
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		  $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];		
					   }
									   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

				
				  $data["startdate"] =$startdate;
		        $data["enddate"] =$enddate;
				
				$data['startdate']=$startdate;
$data['enddate']=$enddate;
				
				$config['base_url'] = base_url('Systemusers/trialbalance');
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		//
	if($branchid=="all"){
		
		        $data["trialbalance"] = $this->usermodel->displayalldatatrialbalance($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate);

		
	}else{
		
		
		        $data["trialbalance"] = $this->usermodel->displayalldatatrialbalance($config["per_page"], $page,'debitcredit','companyid',$companyid,'branch',$branchid,$startdate,$enddate);

		
	}

			$config['total_rows'] =count((array) $data["trialbalance"]);
		
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/trialbalance',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	public function journalentry()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		 $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];		
				
		
				
					if ($this->input->post('btn_report') == "report")
					   { 
				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
					 
					   }else{
						   
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		 $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];		
					   }
								
				
				
				
				
				
				$config['base_url'] = base_url('Systemusers/journalentry');
		$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','companyid',$companyid,'id >',0);
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
				
	
        $data["trialbalance"] = $this->usermodel->displayalljournalentry($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/journalentry',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	public function viewbalancesheetaccount()
	{ 
	
	   if (isset($_GET['bankname'])){

    
				  
					  $bankname = $_GET['bankname'];
					  					  $startdate = $_GET['startdate'];

										  					  $enddate = $_GET['enddate'];

    }
    else {
		
					  $bankname = $this->input->post("bankname");
					  
				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
	}
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
			 

					
				
					
					 		
								
				
				
				
				         $this->load->view("template/headerpagemin");

	
        //$data["trialbalance"] = $this->usermodel->displayspecificaccount('debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate,$bankname);

$data["trialbalance"] = $this->usermodel->displaysuaccount('debitcredit','companyid',$companyid,'bankname',$bankname,$startdate,$enddate);

		
		
			$this->load->view('userdata/journalentry',$data);
				
		$this->load->view("template/footerpage");
					   
	}
		public function viewaccount()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	


	   if (isset($_GET['bankname'])){
 	
    
				  	  $download = "no";
					  $bankname = $_GET['bankname'];
					  	 $startdate = $_GET['startdate'];
						$enddate = $_GET['enddate'];
												$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

							 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }	
															  
				
		$bankname = trim($this->usermodel->allterms_handler($bankname,'bankname'));
				$branchid = trim($this->usermodel->allterms_handler($branchid,'branchid'));
		
		$startdate = ($this->usermodel->allterms_handler($startdate,'startdate'));

		$enddate = trim($this->usermodel->allterms_handler($enddate,'enddate'));
		$download = trim($this->usermodel->allterms_handler($download,'download'));







				
															  
															  

						   
																					  
				
    }
    else {
		$bankname = trim($this->usermodel->allterms_handler($this->input->get_post('bankname', TRUE),'bankname'));
		$branchid = trim($this->usermodel->allterms_handler($this->input->get_post('branchid', TRUE),'branchid'));
		
		$startdate = ($this->usermodel->allterms_handler($this->input->get_post('startdate', TRUE),'startdate'));

		$enddate = trim($this->usermodel->allterms_handler($this->input->get_post('enddate', TRUE),'enddate'));
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));

	}





				
				$config['base_url'] = base_url('Systemusers/viewaccount');
	if($branchid=="all"){
		
       $config['total_rows'] = $this->usermodel->displayspecificaccountCounter('debitcredit','debitcredit.companyid',$companyid,'debitcredit.id >',0,$startdate,$enddate,$bankname,$download,"","");

		
	}else{
		
		
        $config['total_rows'] = $this->usermodel->displayspecificaccountCounter('debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branchid,$startdate,$enddate,$bankname,$download,"", "");

		
	}
	
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','branch',$branchid);


			
	if($branchid=="all"){
		
        $query = $this->usermodel->displayspecificaccount('debitcredit','debitcredit.companyid',$companyid,'debitcredit.id >',0,$startdate,$enddate,$bankname,$download,$config["per_page"], $page);

		
	}else{
		
		
        $query = $this->usermodel->displayspecificaccount('debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branchid,$startdate,$enddate,$bankname,$download,$config["per_page"], $page);

		
	}
	
	//$config['total_rows'] = $query['records'];

			$data["generalledger"]=$query['data'];








				
         $this->load->view("template/headerpagemin");
						 		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/generalledger',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	public function viewaccount2()
	{ 
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	
	
	   if (isset($_GET['bankname'])){
 	
    
				  	  $download = "no";
					  $bankname = $_GET['bankname'];
					  	 $startdate = $_GET['startdate'];
						$enddate = $_GET['enddate'];
												$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

							 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }	
															  
				
		$bankname = trim($this->usermodel->allterms_handler($bankname,'bankname'));
				$branchid = trim($this->usermodel->allterms_handler($branchid,'branchid'));
		
		$startdate = ($this->usermodel->allterms_handler($startdate,'startdate'));

		$enddate = trim($this->usermodel->allterms_handler($enddate,'enddate'));
		$download = trim($this->usermodel->allterms_handler($download,'download'));







				
															  
															  

						   
																					  
				
    }
    else {
		$bankname = trim($this->usermodel->allterms_handler($this->input->get_post('bankname', TRUE),'bankname'));
		$branchid = trim($this->usermodel->allterms_handler($this->input->get_post('branchid', TRUE),'branchid'));
		
		$startdate = ($this->usermodel->allterms_handler($this->input->get_post('startdate', TRUE),'startdate'));

		$enddate = trim($this->usermodel->allterms_handler($this->input->get_post('enddate', TRUE),'enddate'));
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));

	}

				 $data['links'] = "";
	
				

					
				
					
					 		
								
				
				
				
				         $this->load->view("template/headerpagemin");

	
	
	
	
			
	if($branchid=="all"){
		
        $data["generalledger"] = $this->usermodel->displayspecificaccount('debitcredit','debitcredit.companyid',$companyid,'debitcredit.id >',0,$startdate,$enddate,$bankname,$download);

		
	}else{
		
		
        $data["generalledger"] = $this->usermodel->displayspecificaccount('debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branchid,$startdate,$enddate,$bankname,$download);

		
	}
	
	
	
	
	
	
	
	
	
	
	
	
$data["total_rows"]=count((array)   $data["generalledger"]);
			
		
		
			$this->load->view('userdata/generalledger',$data);
				
		$this->load->view("template/footerpage");
					   
	}
	
	
	
	public function viewaccounttransfer()
	{ 
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	
	
	   if (isset($_GET['bankname'])){
 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];  
    
				  	  $download = "no";
					  $bankname = $_GET['bankname'];
					  					  $startdate = $_GET['startdate'];

										  					  $enddate = $_GET['enddate'];

    }
    else {
		
					  $bankname = $this->input->post("bankname");
					$branchid = $this->input->post("branchid");

				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
			  			  $download = $this->input->post("download");

	}

				 $data['links'] = "";
	
				

					
				
					
					 		
								
				
				
				
				         $this->load->view("template/headerpagemin");

	
	
	
	
			
	if($branchid=="all"){
		
        $data["generalledger"] = $this->usermodel->viewaccounttransfer('debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate,$bankname,$download);

		
	}else{
		
		
        $data["generalledger"] = $this->usermodel->viewaccounttransfer('debitcredit','companyid',$companyid,'branch',$branchid,$startdate,$enddate,$bankname,$download);

		
	}
	
	
	
	
	
	
	
	
	
	
	
	
$data["total_rows"]=count((array)   $data["generalledger"]);
			
		
		
			$this->load->view('userdata/viewallbanktransfers',$data);
				
		$this->load->view("template/footerpage");
					   
	}
	
	
		
	public function profitloss()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        				   	$data['branchid'] = $session_data['branchid'];

		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				     
					if ($this->input->post('btn_report') == "report")
					   { 
				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
			  			  $mybranch = $this->input->post("branchname");

			   $frotime="00:00:00";
					$totime="23:59:59";
	  
	  	  $branch=$mybranch;

	  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

					 
					   }else{
						   
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		  $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];	
	
				  
				  		$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

						   
															 if( $viewallaction==true){
																 
															 $branch ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branch = $data['branchid'];

															 }																 
						   
 		   
				  
				  
				  
				  
				  
				  
				  
				  
				  
				  
				  
				  
				  

					   }
					   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


				$config['base_url'] = base_url('Systemusers/profitloss');
	if($branch == "all"){
				$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','companyid',$companyid,'id >',0);

	}else{
				$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','companyid',$companyid,'branch',$branch);

		}		
		
		
		
		$config['per_page'] = '100000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
				// $data["incglgroups"] = $this->usermodel->populateincomeglgroups($companyid);

			 //$data["expglgroups"] = $this->usermodel->populateexpenseglgroups($companyid);

		 $data["expense"] = $this->usermodel->displayexpense($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate,$branch);



					 $data["income"] = $this->usermodel->displayincome($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate,$branch);

		
		//
		
		 $data["startdate"]= $startdate;
		 		 $data["enddate"]= $enddate;

		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/profitloss',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	public function viewallstatements()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				 
	
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");




				
				  if (isset($_GET['startdate'])){

    							$reporttype = $_GET['reporttype'];


					  $bankname = $_GET['bankname'];
					  $startdate = $_GET['startdate'];
						$enddate = $_GET['enddate'];
						$supplier = $_GET['supplier'];
						$type = $_GET['type'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

    }
    else {
		
			
			
		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  				  			    $reporttype = $this->input->post("reporttype");   

		 		 	 $type = $this->input->post("type");   

		 		 	// $bankname = $this->input->post("bankname");   

		 	 $startdate = $this->input->post("startdate");   
			     	
		
			    $enddate = $this->input->post("enddate");   
				  
				
 			$suppliers = explode(':=',$this->input->post("supplier"));

 				
  $supplier = htmlspecialchars(trim($suppliers[0]));
  

			    $enddate = $this->input->post("enddate");   
				  			    $branchid = $this->input->post("branchid");   

  
  
  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

	}
	

















	
		
				
								 $data["startdate"]=$startdate;
								 $data["type"]=$type;

				 $data["enddate"]=$enddate;
				$config['base_url'] = base_url('Systemusers/viewallstatements');
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
//
$previousbalance=0;
 			 $data['viewreceipt'] = $this->usermodel->populatealldataarray('people','companyid', $companyid,'id', $supplier);

		 $customername="";
		 
		
					
						 $data["customername"]=$customername;

		
		
         $this->load->view("template/headerpagemin");

		// $this->load->view("template/tableheader");
		
		
			
							$config['base_url'] = base_url('Systemusers/viewallstatements');
							//$config['total_rows'] = $this->usermodel->count_allwhere('products','companyid',$companyid);
		$config['per_page'] = '10000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
		
		
		 $data["reporttype"]=$reporttype;
		
		
		$data["links"] = $this->pagination->create_links();
	
			if($type=="Supplier"){
						
						
						

						
					
						
						
						
						
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displayallstatementSupplier($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displayallstatementSupplierNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);

		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
			            $previousbalance=($MYopeningbalance);	
						// $previousbalance=0;	


           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
						
						
												// $data["previousbalance"]=0;

						
						 $data["previousbalance"]=$previousbalance;
						
						
						
						
						
		     $data["cashflow"] = $this->usermodel->displayallstatement($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/allstatements',$data);

				}else if( $type=="Bill"){
						
						
						

						
						
						
						
						
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displayallstatementBill($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displayallstatementBillNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);



		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
			            $previousbalance=($MYopeningbalance);	
						

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
						
					
						
						 $data["previousbalance"]=$previousbalance;
						
						
			
						
						
		     $data["cashflow"] = $this->usermodel->displayallstatementAllBills($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/allstatements',$data);

				}else{
					
			
			
					
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if($myfiscalyear !=false){
					
		
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERS($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);



			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
					
				
				 $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERSNOopening($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);

//exit;
		   // $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
			            $previousbalance=($MYopeningbalance);	
						
			//var_dump($previousbalance );
	
	
           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
		
					
					
										 $data["previousbalance"]=$previousbalance;
	
					
					
				//	$data["cashflow"] =true;
				
	
				//$data["cashflow"] = $this->usermodel->displaycustomerstatement($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);
								//$data["cashflow"] = $this->usermodel->displaycustomerstatementLATEST($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);
					$data["cashflow"] = $this->usermodel->displaycustomerstatementBoth($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);
					//$data["cashflow"] = $this->usermodel->displaycustomerstatement2($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);
					//$data["cashflow"] = $this->usermodel->displaycustomerstatement333($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);

	
					 
					 
					// var_dump($data["cashflow"]);
					// exit;
					 
					 
					 
$config['total_rows'] =count((array)$data["cashflow"] );




		$this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/customerstatements',$data);
	
				}
		$this->load->view("template/footerpage");
	
	}
	
	
		public function viewallstatements2222()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				 
	
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");




				
				  if (isset($_GET['startdate'])){

    

					  $bankname = $_GET['bankname'];
					  $startdate = $_GET['startdate'];
						$enddate = $_GET['enddate'];
						$supplier = $_GET['supplier'];
						$type = $_GET['type'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

    }
    else {
		
			
			
		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
		 		 	 $type = $this->input->post("type");   

		 		 	// $bankname = $this->input->post("bankname");   

		 	 $startdate = $this->input->post("startdate");   
			     	
		
			    $enddate = $this->input->post("enddate");   
				  
				
 			$suppliers = explode(':=',$this->input->post("supplier"));

 				
  $supplier = htmlspecialchars(trim($suppliers[0]));
  

			    $enddate = $this->input->post("enddate");   
				  			    $branchid = $this->input->post("branchid");   

  
  
  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

	}
	

















	
		
				
								 $data["startdate"]=$startdate;
								 $data["type"]=$type;

				 $data["enddate"]=$enddate;
				$config['base_url'] = base_url('Systemusers/viewallstatements');
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
//
$previousbalance=0;
 			 $data['viewreceipt'] = $this->usermodel->populatealldataarray('people','companyid', $companyid,'id', $supplier);

		 $customername="";
		 
		
					
						 $data["customername"]=$customername;

		
		
         $this->load->view("template/headerpagemin");

		// $this->load->view("template/tableheader");
		
		
			
							$config['base_url'] = base_url('Systemusers/viewallstatements');
							//$config['total_rows'] = $this->usermodel->count_allwhere('products','companyid',$companyid);
		$config['per_page'] = '10000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
		
		
		
		
		
		$data["links"] = $this->pagination->create_links();
	
			if( $type=="Supplier"){
						
						
						

						
					
						
						
						
						
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displayallstatementSupplier($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displayallstatementSupplierNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);

		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
			            $previousbalance=($MYopeningbalance);	
						

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
						
						
						
						
						 $data["previousbalance"]=$previousbalance;
						
						
						
						
						
		     $data["cashflow"] = $this->usermodel->displayallstatement($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/allstatements',$data);

				}else if( $type=="Bill"){
						
						
						

						
						
						
						
						
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displayallstatementBill($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displayallstatementBillNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);



		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
			            $previousbalance=($MYopeningbalance);	
						

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
						
					
						
						 $data["previousbalance"]=$previousbalance;
						
						
			
						
						
		     $data["cashflow"] = $this->usermodel->displayallstatementAllBills($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/allstatements',$data);

				}else{
					
			
			
					
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if($myfiscalyear !=false){
					
	
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERS($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);



			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
					
				
				 $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERSNOopening($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);

//exit;

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
			            $previousbalance=($MYopeningbalance);	
						
			//var_dump($previousbalance );
	
	
           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
		
					
					
										 $data["previousbalance"]=$previousbalance;
	
					
					
				//	$data["cashflow"] =true;
				
	
					$data["cashflow"] = $this->usermodel->displaycustomerstatement($config["per_page"], $page,$branchid,$companyid,$startdate,$enddate,$supplier,$type);
			
	
				 
					 
					 
					 
$config['total_rows'] =count((array)$data["cashflow"] );




		$this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/customerstatements',$data);
	
				}
		$this->load->view("template/footerpage");
	
	}
	
		
	public function viewallstatements2()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				 
	
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		//$startdate=$fiscalyear[0]['startdate'];
		 //$enddate=$fiscalyear[0]['enddate'];		
		 
		 // $frotime="00:00:00";
					//$totime="23:59:59";
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
		 		 	 $type = $this->input->post("type");   

		 		 	 $bankname = $this->input->post("bankname");   

		 	 $startdate = $this->input->post("startdate");   
			     	
		
			    $enddate = $this->input->post("enddate");   
				  
				
 			$suppliers = explode(':=',$this->input->post("supplier"));

 				
  $supplier = htmlspecialchars(trim($suppliers[0]));
  

			    $enddate = $this->input->post("enddate");   
				  			    $branchid = $this->input->post("branchid");   

  
  
  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;
		
				
								 $data["startdate"]=$startdate;
								 $data["type"]=$type;

				 $data["enddate"]=$enddate;
				$config['base_url'] = base_url('Systemusers/viewallstatements');
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
//
$previousbalance=0;
 			 $data['viewreceipt'] = $this->usermodel->populatealldataarray('people','companyid', $companyid,'id', $supplier);

		 $customername="";
		 
		
					
						 $data["customername"]=$customername;

		
		
         $this->load->view("template/headerpagemin");

		// $this->load->view("template/tableheader");
		$data["links"] = $this->pagination->create_links();
					if( $type=="Supplier"){
						
						
						
					
						
						
						
						
						
						
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displayallstatementSupplier($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displayallstatementSupplierNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);

		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finaldebit-$finalcredit;
			            $previousbalance=($MYopeningbalance);	
						

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
						
						
						
						
						 $data["previousbalance"]=$previousbalance;
						
						
						
						
						
		     $data["cashflow"] = $this->usermodel->displayallstatement($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/allstatements',$data);

				}else{
					
					
					
						
						   $myfiscalyear = $this->usermodel->populatecustomersupplierGLfiscalyear($companyid, $startdate,$supplier);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];



			
						    $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERS($branchid,$companyid,$fiscalyearstartdate,$startdate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
						
					  $previousbalance=($openingbalance+$MYopeningbalance);		
						

					
				}else{
				 $data["fiscalyear"] = $this->usermodel->displaycustomerstatementcUSTOMERSNOopening($branchid,$companyid,$startdate,$enddate,$supplier,$type);

		  //   $data["fiscalyear"] = $this->usermodel->displayallstatementGL($branchid,$companyid,$startdate,$enddate,$supplier,$type);

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			$MYopeningbalance=$finalcredit-$finaldebit;
			            $previousbalance=($MYopeningbalance);	
						

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 
						
					
					
					
										 $data["previousbalance"]=$previousbalance;
	
					
					
					
					
					
					
					
					 $data["cashflow"] = $this->usermodel->displaycustomerstatement2($branchid,$companyid,$startdate,$enddate,$supplier,$type);
				
				
				
				
				
				
				
				
				
				$config['total_rows'] =count((array)$data["cashflow"]);
						 		$data["total_rows"] =$config['total_rows'];

			$this->load->view('userdata/customerstatements',$data);
	
				}
		$this->load->view("template/footerpage");
	
	}
	
		
	public function cashflow()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				 
	
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		// $startdate=$fiscalyear[0]['startdate'];
		// $enddate=$fiscalyear[0]['enddate'];		
		 
		//  $frotime="00:00:00";
					//$totime="23:59:59";
	  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  	  	  $branchid = $this->input->post("branchid");


		 		 	 $bankname = $this->input->post("bankname");   

		 	$startdate = $this->input->post("startdate");   
			     
			    $enddate = $this->input->post("enddate");   
				  			    $type = $this->input->post("type");   

  
  
  
  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;
		  
		  
$openingbalance=0;
				
				$config['base_url'] = base_url('Systemusers/cashflow');
	
		$fiscalyearstartdate="";
		$data['startdate']=$startdate;
$data['enddate']=$enddate;
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		
//
$previousbalance=0;
 
		     $myfiscalyear = $this->usermodel->populateoneGLfiscalyear($companyid, $startdate,$bankname);
	
				if(!$myfiscalyear==false){
						$fiscalyearstartdate=$myfiscalyear[0]["startdate"];
				$openingbalance=$myfiscalyear[0]["opening"];
$previousbalance=$myfiscalyear[0]["opening"];
					
				}else{
					
					
						$data["fiscalyear"] = $this->usermodel->displayalldebitcreditsummary($companyid,$fiscalyearstartdate,$startdate,$bankname,trim($branchid));

			$finaldebit= $data["fiscalyear"][0]["finaldebit"];
			$finalcredit= $data["fiscalyear"][0]["finalcredit"];
			            $previousbalance=($openingbalance);	

           // $previousbalance=($openingbalance+($finaldebit-$finalcredit));	
					
				}
				 

  
	
						 $data["previousbalance"]=$previousbalance;

				 
					$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','companyid',$companyid,'branch',$branchid);
		     $data["cashflow"] = $this->usermodel->displayalldacashflowSpecific('debitcredit','companyid',$companyid,'branch',$branchid,$startdate,$enddate,$bankname);
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		
		if($type=="Balance"){
						$this->load->view('userdata/cashflowbalance',$data);

		}else{
						$this->load->view('userdata/cashflow',$data);

			
		}
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function startreconciliation()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				
				
				
						
				  if (isset($_GET['bankname'])){

    

					  $bankname = $_GET['bankname'];
					  $startdate = $_GET['startdate'];
						$enddate = $_GET['enddate'];
						$balance = $_GET['balance'];
						$type = $_GET['type'];
	$lastmonthbalance = $_GET['lastmonthbalance'];

    }
    else {
		
			
			
			
	  	    $lastmonthbalance = $this->input->post("lastmonthbalance");

	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  

		 		 	 $bankname = $this->input->post("bankname");   
		 		 	 $balance = $this->input->post("balance");   

		 	 $startdate = $this->input->post("startdate");   
			     
			    $enddate = $this->input->post("enddate");   

  			    $type = $this->input->post("type");   

  
  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

	}
	
	
	

				
				 
						   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


		
				
				$config['base_url'] = base_url('Systemusers/startreconciliation');
		
	
//
										$previousbalance=0;
 
		   $data["startdate"]=$startdate;
		   			$data['lastmonthbalance']= $lastmonthbalance; 

		    $data["bankname"]=$bankname;
			 $data["enddate"]=$enddate;
			
						 $data["previousbalance"]=0;
						 $data["balance"]=$balance;
						 $data["type"]=$type;

				
		     $data["cashflow"] = $this->usermodel->displayallbankreconcilition('debitcredit','companyid',$companyid,'id >',0,$startdate,$enddate,$bankname,$type);
		
		
		
         $this->load->view("template/headerpagemin");
	
	
						$this->load->view('userdata/startreconciliation',$data);

				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function updateinbulk()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
				  $debitcredit = $this->usermodel->populatealldatanoarray("productlist","id > ", 0,"companyid", $companyid);
  $i=0;
														if(is_array($debitcredit)) {
														//$updateArray = array();
														   foreach($debitcredit as $row)
														   {
															   $i++;
											$code=trim($row->code);

															$productname = $this->usermodel->populateallarray('products','code', $code);
															$orderamount=$productname[0]['orderamount']; 	

														
														
														
												
														 $myid=trim($row->id);
														 

															 	$updateArray[] =array(	
																'id'=>$myid,													
																'orderamount'=>$orderamount,
																);	

														   }

												$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');
																}
													

				if($this->db->affected_rows() > 0)
						{
								 
								 echo "You have successfully sinked the data";
							
						}else {     
echo "Data were not sinked. May be there was no matching data";
		

					}
						
			
	
	}
	
	
		public function sinkaccounts()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
				  $debitcredit = $this->usermodel->populatealldatanoarray("debitcredit","crateddate", "0000-00-00 00:00:00","companyid", $companyid);
  $i=0;
														if(is_array($debitcredit)) {
														//$updateArray = array();
														   foreach($debitcredit as $row)
														   {
															   $i++;
															 //  echo $i;
														//  echo":   ";
															   
															 
														$mydate=($row->crateddate_old);
														
														$splitTimeStamp = explode(" ",$mydate);
												$date = $splitTimeStamp[0];											
														
													 $correctdate = date("Y-m-d H:i:s", strtotime($date));
											
														//echo "   ".	$mydate=($row->description);
												
														 $myid=trim($row->id);
														 

															 	$updateArray[] =array(	
																'id'=>$myid,													
																'crateddate'=>$correctdate,
																);	

														   }

												$RESULT =	$this->db->update_batch('debitcredit',$updateArray, 'id');
																}
													

				if($this->db->affected_rows() > 0)
						{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully sinked the dates</div>');	
							redirect("user/generalledger");
						}else {     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Dates were not sinked. May be there was no wrong dates.Try again</div>');
							redirect("user/generalledger");

					}
						
			
	
	}
	
	
	
	public function generalledger()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				  if ($this->input->post('btn_report') == "report")
					   { 
				   					$branch = $this->input->post("branchname");

				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
					  $frotime="00:00:00";
					$totime="23:59:59";
				 $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;
					   }else{
						   
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		 $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];	



				  		$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

						   
															 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }																 
						   



		 
					   }
				
		  
		  
		  $data['startdate']=$startdate;
		  $data['enddate']=$enddate;
				
				$config['base_url'] = base_url('Systemusers/generalledger');
		$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','companyid',$companyid,'id >',0);
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
	
        $data["generalledger"] = $this->usermodel->displayalldataacounting($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/generalledger',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function generalledgerVariance()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				  if ($this->input->post('btn_report') == "report")
					   { 
				   					$branch = $this->input->post("branchname");

				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
					  $frotime="00:00:00";
					$totime="23:59:59";
				 $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;
					   }else{
						   
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		 $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];	



				  		$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

						   
															 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }																 
						   



		 
					   }
				
		  
		  
		  $data['startdate']=$startdate;
		  $data['enddate']=$enddate;
				
				$config['base_url'] = base_url('Systemusers/generalledgerVariance');
		
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
	
        $data["generalledger"] = $this->usermodel->displayalldataacountingVariance($config["per_page"], $page,'debitcredit','companyid',$companyid,'id >',0);

			$config['total_rows'] =count((array) $data["generalledger"]);
		
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/generalledgervariance',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	public function balancesheet()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
	$data['branchid'] = $session_data['branchid'];
		 $branch = $data['branchid'];
			  if ($this->input->post('btn_report') == "report")
					   { 
				   	$startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
					$branch = $this->input->post("branchname");
 
					 
					 	 $frotime="00:00:00";
					$totime="23:59:59";
	  
	  
	  $startdate=$startdate." ".$frotime;
	  	  $enddate=$enddate." ".$totime;

	  
					   }else{
						   
						   
								$viewallaction=$this->usermodel->populatuserpermissionsdataarray('reports','viewall',$userid);

						   
															 if( $viewallaction==true){
																 
															 $branchid ="all";	 
															 }else{
														$data['branchid'] = $session_data['branchid'];
														 $branchid = $data['branchid'];

															 }																 
						   
					 
			  $fiscalyear = $this->usermodel->populatealldataarray('fiscalyear','companyid', $companyid,'status', "active");

		 $startdate=$fiscalyear[0]['startdate'];
		 $enddate=$fiscalyear[0]['enddate'];		
					   }
									   		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

			
				$data["startdate"]= $startdate;
				
				$data["enddate"] =$enddate;
				$config['base_url'] = base_url('Systemusers/balancesheet');
				
				
						
		if($branch == "all"){
					$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','debitcredit.companyid',$companyid,'debitcredit.id > ',0);

		}else{
					$config['total_rows'] = $this->usermodel->count_allwheredata('debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branch);

		}
		$config['per_page'] = '100000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
	
   


		
				 $data["equity"] = $this->usermodel->displaybalancesheettype($config["per_page"], $page,'debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branch,$startdate,$enddate,3);

		 $data["liability"] = $this->usermodel->displaybalancesheettype($config["per_page"], $page,'debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branch,$startdate,$enddate,2);

					 $data["asset"] = $this->usermodel->displaybalancesheettype($config["per_page"], $page,'debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branch,$startdate,$enddate,1);
					 $data["netprofit"] = $this->usermodel->displaynetprofit($config["per_page"], $page,'debitcredit','debitcredit.companyid',$companyid,'debitcredit.branch',$branch,$startdate,$enddate);

		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/balancesheet',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	public function activityloggs()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/activityloggs');
		$config['total_rows'] = $this->usermodel->count_allwheredata('activityloggs','companyid',$companyid,'id >',0);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
	
        $data["loggs"] = $this->usermodel->displayalldata($config["per_page"], $page,'activityloggs','companyid',$companyid,'id >',0);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/activityloggs',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	public function loggs()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/loggs');
		$config['total_rows'] = $this->usermodel->count_allwheredata('loggs','companyid',$companyid,'id >',0);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
	
        $data["loggs"] = $this->usermodel->displayalldata($config["per_page"], $page,'loggs','companyid',$companyid,'id >',0);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/loggs',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function complain()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/complain');
		$config['total_rows'] = $this->usermodel->count_allwheredata('complain','companyid',$companyid,'userid',$userid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["complain"] = $this->usermodel->displayalldata($config["per_page"], $page,'complain','companyid',$companyid,'id >',0);

		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/complain',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	public function viewtimer()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/viewtimer');
		$config['total_rows'] = $this->usermodel->count_allwheredata('timer','companyid',$companyid,'id >',0);
		$config['per_page'] = '60';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		        $data["timer"] = $this->usermodel->displayalldata($config["per_page"], $page,'timer','companyid',$companyid,'id >',0);

		

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewtimer',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	public function callcenter()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/callcenter');
		$config['total_rows'] = $this->usermodel->count_allwheredata('callcenter','companyid',$companyid,'id >',0);
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["callcenter"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'callcenter','companyid',$companyid,'id >',0,"id","DESC");

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/callcenter',$data);
				
	//	$this->load->view("template/footerpage");
	
	}
	
	
	public function viewgatepass()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/viewgatepass');
		$config['total_rows'] = $this->usermodel->count_allwheredata('gatepass','branchid',$branchid,'id >',0);
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["callcenter"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'gatepass','branchid',$branchid,'id >',0,"id","DESC");

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewgatepass',$data);
				
	//	$this->load->view("template/footerpage");
	
	}
	
	
	public function viewallgatepassandcheckins()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
			 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				$config['base_url'] = base_url('Systemusers/viewallgatepassandcheckins');
		$config['total_rows'] = $this->usermodel->count_allwheredata('checkin','branchid',$branchid,'id >',0);
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["callcenter"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'checkin','branchid',$branchid,'id >',0,"id","DESC");

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewmygatepasscheckins',$data);
				
	//	$this->load->view("template/footerpage");
	
	}
	
	
	
	public function gatepass()
	{ 		
         $this->load->view("template/headerpagemin");
	 $this->load->view("template/tableheader");
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategorybox','description','DESC','companyid',1 ,'status','active');

			 $data['gatepass'] = $this->usermodel->populateallarray('gatepass','id', -1);
								

													

		$this->load->view('userdata/gatepass',$data);
		$this->load->view("template/footerpage");
	}
	
  
	
	
	
	
	
	
	
	
	
	
  
  
  public function addnewgatepass()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 				 		// $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		 //$userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");

								 		 		 $subject = $this->input->post("subject");

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
$officename = $this->input->post("officename");
		 		 $phone = $this->input->post("phone");


			  						  		   	  $status = $this->input->post("status");

			  						  		   	  $mycategoryid = $this->input->post("mycategoryid");

		    		   	 
											   $action = $this->input->post("action");

$sendsms = $this->input->post("sendsms");

$sms = trim($this->input->post("sms"));

			$idno = $this->input->post("idno");
		 				 		 $name = $this->input->post("name");
		 				 		 $business = $this->input->post("business");

								$vehicleno = $this->input->post("vehicleno");
				 		 		 $vehiclecolor = $this->input->post("vehiclecolor");
				 		 		 $vehiclemodel = $this->input->post("vehiclemodel");
								$location = $this->input->post("location");
		 				 		 $checkindate = $this->input->post("checkindate");
			 				 		  $myid = $this->input->post("myid");
									  
									  
									  	 $subject = $this->input->post("subject");
			 				 		  $messageid = $this->input->post("messageid");
									  $printgatepass = $this->input->post("printgatepass");
									  
									  		  $membership = $this->input->post("membership");
									  $bookedby = $this->input->post("bookedby");

							

		$invoice = $userid.time()+ 1;
			  		  $this->form_validation->set_rules("checkindate", "checkindate", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    		
         $this->load->view("template/headerpagemin");
	 $this->load->view("template/tableheader");

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addgatepass') == "gatepass")
					   {
 
 $confirmusers=false;
 $confirmusers=$this->usermodel->Getmembedetails($subject,$phone,$idno,$vehicleno,$branchid);
$mycurrentid=$confirmusers[0]['id'];
$myid="";

									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$sms,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				//'media'=>$media,
				'phone'=>$phone,
				'branchid'=>$branchid,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 	'idno'=>$idno,
				
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				'messageid'=>$invoice,
				'membership'=>$membership,
				'bookedby'=>$bookedby,
			
								);
								
								 if($confirmusers==false){
								// if(trim($myid)==""){
							$usr_result=$this->usermodel->add($data,'gatepass');

							}else{
							$usr_result=TRUE;
								
								
								///$this->usermodel->updatedata($data,'gatepass','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result==TRUE) //active user record is present
							{
								

						if(trim($mycurrentid) !=""){
		
		 

							
								
			$chekdata=array(		
			'updatedby'=>$userid,
			'status'=>"Active",
			'updateddate'=>$dateposted,

			'checkindate'=>$dateposted,

			
								);
	  
					$this->usermodel->updatedata($chekdata,'gatepass','id',$mycurrentid);


		 }
		 
		
								
		 
		 
		 
								
								if($mycurrentid !=""){
									$myid=$mycurrentid;
									
								}else{
									$mydata = $this->usermodel->populateallarray('gatepass','messageid',$invoice);

									
										$myid=$mydata[0]["id"];
								}
								
								
		 
		 
		 
		 
		 
			
		
										$checkindata=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
			
				'phone'=>$phone,
	'bookedby'=>$bookedby,

		'status'=>"Active",
		'companyid'=>$companyid,

				 	'idno'=>$idno,
				'visitorid'=>$myid,
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,
				'branchid'=>$branchid,
				'officename'=>$officename,
				'category'=>$category,
				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				'subject'=>$subject,
				'messageid'=>$messageid,
				'media'=>$invoice,
								);
								
			 $this->usermodel->add($checkindata,'checkin');
		 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added a new  call details  ..</div>');	
							redirect('user/viewallgatepassandcheckins');	
										
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Call  was not added.. Try again</div>');
								
								 redirect('user/gatepass');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
  
	 public function printgatepass() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();

 $data['collections'] = $this->usermodel->populateallarray('checkin','media',$invoiceid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printgatepass', $data);
		
	}
  }
  
	
	
	public function openorders()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/openorders');
		$config['total_rows'] = $this->usermodel->count_allwheredata('openorders','companyid',$companyid,'id >',0);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["openorders"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'openorders','companyid',$companyid,'id >',0,"id","DESC");

		
		
		
		
         $this->load->view("template/headerpagemin");
	 $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/openorders',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
			public function searchdocuemnts()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchdocuemnts';
		$query = $this->usermodel->searchdocuemnts($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['viewdocuments'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/viewdocuments',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
	
	
	
	
			public function searchallvisitorhistory()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallvisitor';
		$query = $this->usermodel->searchvisitorHistory($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 300;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['callcenter'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/viewmygatepasscheckins',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
			public function searchallvisitor()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallvisitor';
		$query = $this->usermodel->searchvisitor($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 300;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['callcenter'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/viewgatepass',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
			public function searchcallcenter()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchcallcenter';
		$query = $this->usermodel->searchallcalls($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 300;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['callcenter'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/callcenter',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
	public function prospects()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/allresellers');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','prospects');
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','prospects');

		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewagents',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	public function viewaccomodation()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/allresellers');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','accomodation');
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','accomodation');

		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewagents',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	public function allresellers()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/allresellers');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','reseller');
		$config['per_page'] = '5000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','reseller');

		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewagents',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		public function allbirthdays()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
											  $mymonth=date("m");


 $mydob = (int)$mymonth;
				$config['base_url'] = base_url('Systemusers/allbirthdays');
		$config['total_rows'] = $this->usermodel->countBirthdays($companyid,$mydob);
	
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["viewmember"] = $this->usermodel->displayduebirthdates($config["per_page"], $page,'people','companyid',$companyid,'dob',$mydob);

		
	
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewmember',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	public function viewsupplier()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
				
				$config['base_url'] = base_url('Systemusers/viewsupplier');
						//$config['total_rows'] = $this->usermodel->count_allwheredata('people','branchid',$branchid,'category','supplier');

		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','supplier');
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
       // $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','branchid',$branchid,'category','supplier');

		        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','supplier');

		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewsupplier',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	public function allsuppliers()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/allsuppliers');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','supplier');
		$config['per_page'] = '300';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
        $data["viewmember"] = $this->usermodel->displayalldataWITHORDER($config["per_page"], $page,'people','companyid',$companyid,'category','supplier','supplierbalance','DESC');

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/allsuppliers',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
public function allcustomers()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/allcustomers');
		$config['total_rows'] = $this->usermodel->count_allwheredata('people','companyid',$companyid,'category','member');
		$config['per_page'] = '300';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
	
        $data["viewmember"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','member');

			        $data["viewmember"] = $this->usermodel->displayalldataWITHORDER($config["per_page"], $page,'people','companyid',$companyid,'category','member','balance','DESC');

		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/allcustomers',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	public function viewemployee()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/viewemployee');
		//$config['total_rows'] = $this->usermodel->count_allwhere('people','companyid',$companyid);
		
		
					$config['total_rows'] = $this->usermodel->count_where('people','companyid',$companyid,'category','user');

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		
		
				 $data["viewemployee"] = $this->usermodel->displayalldata($config["per_page"], $page,'people','companyid',$companyid,'category','user');

	
      //  $data["viewemployee"] = $this->usermodel->displayall($config["per_page"], $page,'people','companyid',$companyid);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewemployee',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	public function leavebalance()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/leavebalance');
		//$config['total_rows'] = $this->usermodel->count_allwhere('people','companyid',$companyid);
		
		
					//$config['total_rows'] = $this->usermodel->count_where('people','companyid',$companyid,'category','user');
	$config['total_rows'] = $this->usermodel->count_allwheredatathree('people','companyid',$companyid,'category','user','status',1);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
									
													$data["viewemployee"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'people','companyid',$companyid,'category','user','status',1);

      //  $data["viewemployee"] = $this->usermodel->displayall($config["per_page"], $page,'people','companyid',$companyid);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/leavebalance',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	public function salaryhistory()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				
				
				$config['base_url'] = base_url('Systemusers/salaryhistory');
		$config['total_rows'] = $this->usermodel->count_allwhere('salary','salary.companyid',$companyid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		
		
	
        $data["viewemployee"] = $this->usermodel->displayallsalary($config["per_page"], $page,'salary','salary.companyid',$companyid);

			
		
		
		
		
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/salaryhistory',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewreport()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


		
				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewreport');

				
							$config['total_rows'] = $this->usermodel->count_allwhere('salesreport','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
        $data["viewreport"] = $this->usermodel->displayall($config["per_page"], $page,'salesreport','companyid',$companyid);

			
				

         $this->load->view("template/headerpagemin");
		
			$data["page"]=$page;
		$data["total_rows"] =$config['total_rows'];
		
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viewreport',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	public function viewsms()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($companyid);
$smscompany=$confirmsmsaccount_result[0]['smscompany'];
$paymenttypes=$confirmsmsaccount_result[0]['paymenttypes'];







//

				//
		 

$mytotal_amount = $this->usermodel->countamount($paymenttypes);

	$total_amount=$mytotal_amount[0]['totalsms'];			
				
				$config['base_url'] = base_url('Systemusers/viewsms');
		
		$config['total_rows'] = $this->usermodel->count_allwhere('sms','companyid',$companyid);
         $this->load->view("template/headerpagemin");

		$this->load->view("template/tableheader");

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
			
        $data["viewsms"] = $this->usermodel->displayall($config["per_page"], $page,'sms','companyid',$companyid);
			$data['total_sms'] = $this->usermodel->countSMS($userid); 

			
				
				
		 	
				$data['receiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);
				$data['mycategory'] = $this->usermodel->populateall('category', 'companyid',$companyid);

				
		
	//$data['mycategory'] = $this->usermodel->populatecategory($userid);
			//$data['total_sms'] = $this->usermodel->countamount($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["total_amount"] =$total_amount;
		$data["links"] = $this->pagination->create_links();
			
if($smscompany=="Infobip"){
				$this->load->view('userdata/viewsmsinfo',$data);

}else		if($smscompany=="Africaistalking"){
				$this->load->view('userdata/viewsmsafricaistalking',$data);

}else{
				$this->load->view('userdata/viewsms',$data);

	
}
				
		$this->load->view("template/footerpage");
	
	}
	
	
	   public function downloadmembers() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."member.csv";
		
								
							
									
 									

        $query = "SELECT phone,firstname,lastname,email,country,idno,	gender,comments,computernouserdata FROM people WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
  
	
	
	
	  public function downloaddeals() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Deals and Leads.csv";
		
								
							
									
 									

        $query = "SELECT * FROM deals WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
	
	  public function downloadcalls() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Incoming Calls.csv";
		
								
							
									
 									

        $query = "SELECT phone,callername,receiver,subject,description,createdate,	media FROM callcenter WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
  	
	public function postpayment()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['id'] = $session_data['id'];
	 //$userid = $data['id'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		//  $dateposted = date('Y-m-d H:i:s');
					  $dateposted = date('Y-m-d H:i:s');

		  $userid = $this->input->post("userid");
	  $companyid = $this->input->post("companyid");		  
		  $amount = $this->input->post("amount");    
		 $code = $this->input->post("code"); 
		 		 $description = $this->input->post("description"); 

			
				 $rate = $this->input->post("rate");    
		 $units = $this->input->post("units"); 
		 		
				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
				$this->load->view("template/headerpage");
        	

		
		 $this->load->view('userdata/startpayment', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   
					   
					   
					   	if ($this->input->post('btn_postmypayment') == "volume")
					   {
						   
						   $finalvolume=  ($amount/$rate);
						   $finalvolume=  $this->formatMoney($finalvolume, true);
						   redirect('admin/recharge?randomitemidentifier='.$userid."&finalvolume=".$finalvolume."&amount=".$amount."&description=".$description."&code=".$code."&rate=".$rate);	
						   
					   }else 	if ($this->input->post('btn_postmypayment') == "payment")
					   {
						   
						           		$getpayments = $this->adminusermodel->populateuser($userid);
										
										 $finalvolume=  ($amount/$rate);
																		$finalvolume= $this->formatMoney($finalvolume, true);


							
						       $confirmrecharge = $this->usermodel->populateall('recharge','code',$code);

						   
						    if ($confirmrecharge !=false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>That transaction code exist in our database.It seems like the account had been recharged already or try again</div>');
								
						   //redirect('admin/recharge?randomitemidentifier='.$userid."&finalvolume=".$finalvolume."&amount=".$amount."&description=".$description."&code=".$code."&rate=".$rate);	
														   redirect('getpaymentready?business='.$business."&phone=".$phone."&units=".$units."&amount=".$amount."&description=".$description."&code=".$code."&rate=".$rate);	

						   
						   return false;
						   }											
																		
																		
																		
																		
																		
																		
																		
																		
																		
																		
																		
																		
																		
					$available=$getpayments[0]["totalsms"];
					$finalbalance=$finalvolume+$available;

						   
												$finaldata=array(		
		
			
			
		  	'totalsms'=>$finalbalance,
				 

			
		  
								);
												$data=array(		
		
			
				'companyid'=>$companyid,
				'balance'=>$finalbalance,
		  	'amount'=>$amount,
					  	'units'=>$units,
					  	'balancebefore'=>$available,

				'description'=>$description,
			'code' => $code,		  
		  'dateposted' => $dateposted,    
					 'userid' => $userid, 
	 'rate' => $rate, 
			
		  
								);
						
								$usr_result = $this->usermodel->updatedata($finaldata,'people','id',$userid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
															 $this->usermodel->add($data,'recharge');
						       $myconfirmrecharge = $this->usermodel->populateallarray('postrecharge','code',$code);

								 $rechargeid=$myconfirmrecharge[0]["id"];
								 
								 			$rechargedata=array(		
		
			
			
		  	'status'=>"inactive",
				 

			
		  
								);
					$this->usermodel->updatedata($rechargedata,'postrecharge','id',$rechargeid);

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted the payment..</div>');	
														   redirect('getpaymentready?business='.$business."&phone=".$phone."&units=".$units."&amount=".$amount."&description=".$description."&code=".$code."&rate=".$rate);	
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The payment could not be posted. Try again</div>');
								
														   redirect('getpaymentready?business='.$business."&phone=".$phone."&units=".$units."&amount=".$amount."&description=".$description."&code=".$code."&rate=".$rate);	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

  
			public function searchallattendance()
	{
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallattendance';
		$config['total_rows'] = $this->usermodel->searchallattendance_record_count($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['allattendance'] = $this->usermodel->searchallattendance($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");

	
		 $data["total_rows"] =$config['total_rows'];

		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/allattendance',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
	
	public function viewgrouping()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewgrouping');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('category','companyid',$companyid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
        $data["viewcategory"] = $this->usermodel->displayall($config["per_page"], $page,'category','companyid',$companyid);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewgrouping',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	 public function updatetask()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						$dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		 	 $page = $this->input->post("page");
 	 		 $taskid = $this->input->post("taskid");
 	 		 $category = $this->input->post("category");

 $taskowner = $this->input->post("taskowner");
$subject = $this->input->post("subject");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $contact = $this->input->post("contact");    
		 $status = $this->input->post("status");   
		  $controller = $this->input->post("controller");   
		   $priority = $this->input->post("priority");   
		    $notification = $this->input->post("notification");   
			 $comments = $this->input->post("comments");   
			  $repeated = $this->input->post("repeated");   
			     
			    $exactdate = $this->input->post("exactdate");   
				  
  			    $myview = $this->input->post("myview");   

				
			  		  $this->form_validation->set_rules("taskowner", "Task Person", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsuppliers', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetask') == "task")
					   {
												$data=array(		
			'updatedby'=>$userid,
			
				'taskowner'=>$taskowner,
			'subject'=>$subject,
		  	'fromdate'=>$fromdate,
			
			
			'exactdate'=>$exactdate,
			'todate' => $todate,		  
		  'contact' => $contact,    
		 'status' => $status,   
		  'controller' => $controller,   
		   'priority' => $priority,   
		    'notification' => $notification,   
			 'comments' => $comments,   
			  
			      'repeated' => $repeated,  
			    'category' => $category,  
			   
				
			
			
			
								);
						$usr_result = $this->usermodel->updatedata($data,'tasks','id',$taskid);
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the Task..</div>');	
											if($page >=1){
														redirect($myview.'/'.$page);		
	
								}else{
													redirect($myview);	
	
								}																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Task  was not updated.. Try again</div>');
									if($page >=1){
														redirect($myview.'/'.$page);		
	
								}else{
													redirect($myview);	
	
								}	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	

 public function updatesaleproduct1()
    {


		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		     $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $qty = $this->input->post("qty");
			  $reorderevel = $this->input->post("reorderevel");
			 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
				 $expdate = $this->input->post("expdate");
				 				 $invoice = $this->input->post("invoice");
 $view = $this->input->post("myview");

			  			
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");
			  		  $this->form_validation->set_rules("category", "Product category", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproduct') == "product")
					   {
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
			
			
			'dateposted'=>$dateposted,
				
			 'tax_included'=>$tax_included,
			'store'=>$store,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				
			'qty'=>$qty,
			
		'expdate'=>$expdate,
		
			'reorderevel'=>$reorderevel,
			
			
								);
						$usr_result = $this->usermodel->updatedata($data,'products','id',$productid);

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> Product  updated  ..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
										
											redirect($view);	

													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not Updated.. Try again</div>');
									
redirect($view);
								
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	 public function updateproduct()
    {
		
$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
		 		 $name = $this->input->post("name");
		   	  $status = $this->input->post("status");

		   	  $description = $this->input->post("description");
			  		   	  $imgid = $this->input->post("imgid");

		     $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $qty = $this->input->post("qty");
			  $reorderevel = $this->input->post("reorderevel");
			 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
				 $expdate = $this->input->post("expdate");
				 				 $orderamount = $this->input->post("orderamount");
			$view = $this->input->post("view");
			 $type = $this->input->post("type");
			  			 $shortname = $this->input->post("shortname");
					  	 $uom = $this->input->post("uom");
					  	 $producttype = $this->input->post("producttype");
					  	 $maincode = $this->input->post("maincode");
													$expenseaccount = $this->input->post("expenseaccount");
						 			 			 $assetaccount = $this->input->post("assetaccount");
						 			 			 $salesaccount = $this->input->post("salesaccount");

									 			 $vattype = $this->input->post("vattype");
									 			 $taxtype = $this->input->post("taxtype");
			 			 $reorderquantity = $this->input->post("reorderquantity");
			 			 $hscode = $this->input->post("hscode");

						
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");
			  		  $this->form_validation->set_rules("category", "Product category", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		 if($type=="product"){
		 $this->load->view('userdata/viewproducts', $data);
  
						   }else{
		 $this->load->view('userdata/viewstore', $data);
   
							   
						   }
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproduct') == "product")
					   {
						   
						   
						
								
						
						   
						   
						   
						   
						   
						   
						     if($type=="product"){
							$productname = $this->usermodel->geteproductbyid($code);
										$myproductid =$productname[0]["id"];
						   }else{
							$productname = $this->usermodel->getestorebyid($code);
														$myproductid =$productname[0]["id"];
							   
						   }
						   
						
						  if (($productname!=false)&& ($myproductid!=$productid))
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Product not added!</strong> That product code already  exist. Try again adifferent code.</div>');

						  
							redirect($view);						   
						   return false;
						   }
						   		$productlistdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
								'hscode'=>$hscode,
				'tax_included'=>$tax_included,

				'category'=>$category,
		  	'description'=>$description,
					  	'orderamount'=>$orderamount,
						'reorderquantity'=>$reorderquantity,

						'uom'=>$uom,
								'producttype'=>$producttype,
									'taxtype'=>$taxtype,
									'status'=>$status,


			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'vattype'=>$vattype,

			'supplier'=>$supplier,

		
			
								);
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  			'expenseaccount'=>$expenseaccount,
						 'salesaccount'=>$salesaccount,
						 'assetaccount'=>$assetaccount,
						'vattype'=>$vattype,
									'taxtype'=>$taxtype,


						
			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'uom'=>$uom,
			 'tax_included'=>$tax_included,
			'store'=>$store,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				'status'=>$status,
										'reorderquantity'=>$reorderquantity,

												'producttype'=>$producttype,

			'qty'=>$qty,
											'hscode'=>$hscode,

		'expdate'=>$expdate,
		
			'reorderevel'=>$reorderevel,
			'orderamount'=>$orderamount,
				

								);
								
							
							
								
								   if($type=="product"){
						$usr_result = $this->usermodel->updatedata($data,'products','id',$productid);
  ///
						   }
					 $this->usermodel->updatedata($productlistdata,'productlist','code',$code);

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
									 	
  $myproduct = $this->usermodel->populatealldatanoarray('productlist','code', $maincode,'companyid', $companyid);

														if(is_array($myproduct)) {
														//$updateArray = array();
														   foreach($myproduct as $row)
														   {

														    $mycode=trim($row->code);
														
												
															 $myid=trim($row->id);
														 

															 	$updateArray[] =array(	
																'id'=>$myid,													
																'code'=>$code,
																//'imgid'=>$imgid,
																);	

														   }

														$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');
																}
													
	
								
												 

								
								
								      				
														 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
								$imgiddata=array(					
				'imgid'=>$imgid
						);
			 					 $this->usermodel->updatedata($imgiddata,'products','code',$code);


						
						
																$this->uploadimages($imgid,$companyid,$branchid,$userid);

					}
								
						
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
											if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}					
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not Updated.. Try again</div>');
								
								 	if($page!=0){
													redirect($view.'/'.$page);
	
								}else{
													redirect($view);
	
								}
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	






	 public function updatesaleproduct()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
		 		 $name = $this->input->post("name");
		   	  $status = $this->input->post("status");

		   	  $description = $this->input->post("description");
			  
		     $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $qty = $this->input->post("qty");
			  $reorderevel = $this->input->post("reorderevel");
			 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
				 $expdate = $this->input->post("expdate");
				 				 $orderamount = $this->input->post("orderamount");
			$view = $this->input->post("view");
			 $type = $this->input->post("type");
			  			 $shortname = $this->input->post("shortname");
					  	 $uom = $this->input->post("uom");
					  	 $branch = $this->input->post("branch");
					  	 $producttype = $this->input->post("producttype");

						
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");
			  		  $this->form_validation->set_rules("category", "Product category", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsales', $data);
   
							   
						
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproductsales') == "myproduct")
					   {
						   
						$productname = $this->usermodel->geteproductbyid($code);
									
						 
			   
						
						  if (($productname==false))
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Product not added!</strong> That product code already  exist. Try again adifferent code.</div>');

						  
							redirect($view);						   
						   return false;
						   }
						   		$productlistdata=array(		
'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
			
			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'uom'=>$uom,
			 'tax_included'=>$tax_included,
			'store'=>$store,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				'status'=>$status,
												'producttype'=>$producttype,

			'qty'=>$qty,
			
		'expdate'=>$expdate,
		
			'reorderevel'=>$reorderevel,
			'orderamount'=>$orderamount,
			'supplier'=>$supplier,

		
			
								);
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
			
			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'uom'=>$uom,
			 'tax_included'=>$tax_included,
			'store'=>$store,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				'status'=>$status,
												'producttype'=>$producttype,

			'qty'=>$qty,
			
		'expdate'=>$expdate,
		
			'reorderevel'=>$reorderevel,
			'orderamount'=>$orderamount,
			
								);
								
  
						
						$usr_result =$this->usermodel->updateproductlist($productlistdata,$code,$branch); 

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
	
														$usr_result = $this->usermodel->updatedata($data,'products','code',$code);
	

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
									
	
							
																redirect($view);	
												
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not Updated.. Try again</div>');
								redirect($view);	

								
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	




	 public function updateproductlist()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 	
		   	  $status = $this->input->post("status");

		 
			  
		     $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $qty = $this->input->post("qty");
			  $reorderevel = $this->input->post("reorderevel");
			 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
				 $expdate = $this->input->post("expdate");
				 				 $orderamount = $this->input->post("orderamount");
  $view = $this->input->post("view");
			 $type = $this->input->post("type");
			 			 $vattype = $this->input->post("vattype");

			 
						
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
		

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		 $this->load->view('userdata/viewproductlist', $data);
  
				
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproductlist') == "product")
					   {
						   
						   
						     
							$productname = $this->usermodel->getproductlistbyid($productid);
										$myproductid =$productname[0]["id"];
						  
						
						  if (($productname!=false)&& ($myproductid!=$productid))
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Product not added!</strong> That product code already  exist. Try again adifferent code.</div>');

						  
							redirect($view);						   
						   return false;
						   }
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
			
			'dateposted'=>$dateposted,
				
			 'tax_included'=>$tax_included,
			'store'=>$store,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				'status'=>$status,
				'vattype'=>$vattype,

			'qty'=>$qty,
			
		'expdate'=>$expdate,
		
			'reorderevel'=>$reorderevel,
			'orderamount'=>$orderamount,
			
								);
								 
						$usr_result = $this->usermodel->updatedata($data,'productlist','id',$productid);
  
						  

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
											if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}					
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not Updated.. Try again</div>');
								
								 	if($page!=0){
													redirect($view.'/'.$page);
	
								}else{
													redirect($view);
	
								}
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	public function addstock()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	 		
			
			 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $code =  htmlspecialchars(trim($this->input->post("code")));
$qty = trim($this->input->post("qty"));
	
				$description = trim($this->input->post("description"));


				$deduction = trim($this->input->post("deduction"));
			$invoice = trim($this->input->post("invoice"));

	
			$name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = ($this->input->post("total"));
			  

			  $view = $this->input->post("view");
			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");

		   	  $from = ($this->input->post("from"));
					   	  $supplier = 1;
					   	  $buyingprice = 1;

				
			 	$count =count((array)$total);
					
	  	
						   
			
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			
					   //validation succeeds
					   if ($this->input->post('btn_uaddstock') == "stock")
					   {
						      for($i=0; $i< $count; $i++) {
 
				        		$productname = $this->usermodel->populateallarray('products','code', $code);

			
				        //$productname = $this->usermodel->geteproductbyid($code);
								
						
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						   			


									 
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 
					  	$taxtype=$productname[0]['taxtype']; 

			
			$item_id=$productname[0]['id'];
			
				$producttype=$productname[0]['producttype']; 	
			
			$supplier=$productname[0]['supplier']; 
			$buyingprice=$productname[0]['buyingprice']; 
			$sellingprice=$productname[0]['sellingprice']; 
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
								$status=$productname[0]['status']; 

			$myfinalqty=$productname[0]['qty']; 

		
			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
 
  
  
  
  		
  

  
  
  	
						//$productlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from[$i]);
						 

						     if ($this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from[$i]) ==false)
						   {
							      
									  
									  if($deduction=="Yes"){
									     if($total[$i]>$myfinalqty ){
			     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> The available quantity ('.$myfinalqty.') is less than what you want to dispatch('.$total[$i].').  Try a gain a lower number or add more stock first.</div>');
						  
						  
								
							redirect($view);
	   return false;
   }
									  }
  
									  
							   								$newproductlist=array(		
	'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'shortname'=>$shortname,

			'status'=>$status,
				 	'branch'=>$branchid,
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,

				'producttype'=>$producttype,
								'branch'=>$from[$i],

			'qty'=>$total[$i],
			
					'taxtype'=>$taxtype,

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

								);
							   
							   
							   
							   
				   
							   
			$myusr_result = $this->usermodel->add($newproductlist,'productlist');
			
if($deduction=="Yes"){
	$myfinalqty=($myfinalqty-$total[$i]); 

}else{
		$myfinalqty=($myfinalqty); 

	
}


												$productdata=array(		
												'qty'=>$myfinalqty,
													);
								
								 $this->usermodel->updateproduct($productdata,$code);
								


		$mydata=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'total'=>$total[$i],
			
						'companyid'=>$companyid,
'type'=>$from[$i],
	'branchid'=>$branchid,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  'sellingprice'=>$sellingprice,
		    'buyingprice' => $buyingprice, 
			      'description'=>$description,
				'stockto'=>$from[$i],
				'stockfrom'=>'Main',
								'invoice_number'=>$invoice,
	'invoice_number'=>$invoice,

					

			'balance'=>$total[$i],
					'item_id1'=>0,
			
								);
								$usr_result = $this->usermodel->add($mydata,'newstock');
								  

						
							
						  
						
						   }else{
							   
							   
							   
				
							   
							   
							   
							   
							   
							   
							   
						   
						   
						   
						   
   
			    
					
						  
						   
						   
						  	
	
						  if($deduction=="Yes"){
									     if($total[$i]>$myfinalqty ){
			     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> The available quantity ('.$myfinalqty.') is less than what you want to dispatch('.$total[$i].').  Try a gain a lower number or add more stock first.</div>');
						  
						  
								
							redirect($view);
	   return false;
										 }
						  }
						 $realproductlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from[$i]);
					if( $realproductlist!=FALSE){
						
				
						   		  $available=$realproductlist[0]['qty']; 
						$finalqty=($available+$total[$i]); 
						
						
						
						   

												$data=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'total'=>$total[$i],
								 	'branchid'=>$branchid,

			
						'companyid'=>$companyid,
	//'description'=>$from[$i],
					'type'=>$from[$i],
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  			'invoice_number' => $invoice,		  
'sellingprice'=>$sellingprice,
		    'buyingprice' => $buyingprice, 
			     'description'=>$description,
				'stockto'=>'branch',
				'stockfrom'=>'Main',
'stockto'=>$from[$i],
				  
			
			'balance'=>$finalqty,
					'item_id1'=>$available,
			
			
								);
								
								
												$productdata=array(		
												'qty'=>$finalqty,
													);
								
								
						
				
				
		
							$usr_result = $this->usermodel->add($data,'newstock');
							
																
if($deduction=="Yes"){
								$myfinalqty=($myfinalqty-$total[$i]); 

}else{
								$myfinalqty=($myfinalqty); 

}


												$myproductdata=array(		
												'qty'=>$myfinalqty,
													);
								
								 $this->usermodel->updateproduct($myproductdata,$code); 

								
							 $this->usermodel->updateproductlist($productdata,$code,$from[$i]); 
						
 //  exit;
 
 	 // echo $from[$b];
												}
										  	}
							  }
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
					   
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Stock Added </div>');	
									redirect($view);						   
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
								
									redirect($view);						   
								
								
								
									 }
					   }
					   else
					   {
							redirect('login');
					   }
					   
					   
			}									
					   
		}
	   
   
	
	
		
	
		public function addbulkprojecttransfer()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $code="";
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
 	 		
 //$code =  htmlspecialchars(trim($this->input->post("code")));
 
 
 		 
 			$mycode = explode(':=',$this->input->post("code"));

 
  $newcode = htmlspecialchars(trim($mycode[0]));

 
 
 
 
$qty = trim($this->input->post("qty"));
	
				$description = trim($this->input->post("description"));



	 		$mystatus = trim($this->input->post("status"));

			$name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = $this->input->post("total");
			  		   	  //$tobranch = $this->input->post("tobranch");
		   	  $latest = $this->input->post("total");



$mytobranch = explode(':=',$this->input->post("tobranch"));

 
  $tobranch = htmlspecialchars(trim($mytobranch[0]));


			  $view = $this->input->post("view");



	 if( $total < 0){
							 
							  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You can not dispatch negative quantity ('.$total.') . Try again</div>');
								
													redirect($view);	
								 
								 return false;
							 
							 
							 }









			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");
						 $mycategory = $this->input->post("category");

		   	  $from = $this->input->post("from");
						  // 	  $toproduct = $this->input->post("toproduct");
							  
							 	$mynewproduct = explode(':=',$this->input->post("toproduct"));

 
  $newproduct = htmlspecialchars(trim($mynewproduct[0])); 
							  
							  
$finalybuyingprice=0;
									   	  $invoice = $this->input->post("invoice");
									   	  $compare = $this->input->post("compare");
  
  $currenttuqty=0;
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_movestockinbulk') == "stock")
					   {
						   
						   
				   $sellingprice=0;		 
	   $frombalance=0;
					   $tobalance=0;
					   
					   $serial="";
					   $serialid="";
					   if(($mystatus=="serial") && ($latest==1)){
					

						 						 $myserialname = $this->usermodel->geteproductlistbyserial($newcode,$from);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
   
						  $bprice=$myserialname[0]['buyingprice']; 
						  $sprice=$myserialname[0]['sellingprice']; 
						
							
							
							
						   }else{
													  $code= $newcode;   
   
						   }
						   
						   
						   
					
					   }else{
						  $code= $newcode;   
						   
					   }
			
						if ($from =="Main")
						   {
							$productname = $this->usermodel->populateallarray('products','code', $code);
   
							   
						   }else{
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);

							   
							}
						   
						   
						 // $sprice=$myserialname[0]['sellingprice']; 

			
						
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						   			



						 
	
									 
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 

								  	$taxtype=$productname[0]['taxtype']; 

			$item_id=$productname[0]['id'];
			
				
			
			$supplier=$productname[0]['supplier']; 
			$buyingprice=$productname[0]['buyingprice']; 
			$sellingprice=$productname[0]['sellingprice']; 
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
								$status=$productname[0]['status']; 

			 $myfinalqty=$productname[0]['qty']; 
$currenttuqty=$productname[0]['qty'];
			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
  

  
  	   if($total>$myfinalqty ){
			     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> The available quantity ('.$myfinalqty.') is less than what you want to dispatch('.$total.').  Try a gain a lower number or add more stock first.</div>');
						  
						  
								
							redirect($view);
	   return false;
   }
  


  
  


							
									$myfinalqty=($myfinalqty-$total); 


												$productdata=array(		
												'qty'=>$myfinalqty,
													);
								
								
												
								
								   
						if ($from =="Main")
						   {
								$myusr_result =  $this->usermodel->updateproduct($productdata,$code);
				
							   
						   }else{
							$myusr_result =  $this->usermodel->updateproductlist($productdata,$code,$from); 

							   
							}
							
							
						     if ($myusr_result ==TRUE) //active user record is present
							{
								 
							
								 	   if(($mystatus=="serial") && ($latest==1)){
							
							//
								 $serialdata=array(		
												'branch'=>$tobranch,
													) ;
								 
								 	    $sellingprice=  $sellingprice;
										$buyingprice=  $buyingprice;
								 
									
								
										$this->usermodel->updatedata($serialdata,'serials','id',$serialid);
								 
									   }
								 



if($currenttuqty!=""){
	$currenttuqty=$currenttuqty;
}else{
		$currenttuqty=0;

}

   $frombalance=0;
					   $tobalance= $currenttuqty+$latest;


		$mydata=array(		
			'userid'=>$userid,
							'invoice'=>$invoice,
	'item_id1'=>$currenttuqty,
				'item_id'=>$code,
			'total'=>$total,
					'balance'=>$myfinalqty,
						'companyid'=>$companyid,
'type'=>$tobranch,

			'date'=>$dateposted,
			//'supplier' => $supplier,		  
		    'sellingprice' => $sellingprice, 
		    'buyingprice' => $buyingprice, 
			      'description'=>$description,
				//'stockto'=>$tobranch,
				'stockfrom'=>$from,
				'serial'=>$serial,
			 					'branchid'=>$branchid,
	'category'=>$mycategory,
			
				'projectid'=>$tobranch,

			
								);
								
								$usr_result = $this->usermodel->add($mydata,'newstock');
								
								
								
								
								
							
								
								  if($mycategory=="Project"){
									  
								
	  						 $getcurrentprojectdata = $this->usermodel->populatealldataarray('projectsbudget','code', $code,'projectid', $tobranch);
	  		  	 $myprojectid=$getcurrentprojectdata[0]['id']; 
				

	  	$usedqty=$getcurrentprojectdata[0]['usedqty']; 
		$usedamount=$getcurrentprojectdata[0]['usedamount']; 
		$finalusedqty=	$usedqty+$total;
		$finalusedamount=	($usedamount+($total*$buyingprice));
		
		$mybalance=$getcurrentprojectdata[0]['expamount']-$finalusedamount; 
		
				$balanceqty=$getcurrentprojectdata[0]['qty']-$finalusedqty;
				
				 $projectdata=array(		
												'balance'=>$mybalance,
												'usedamount'=>$finalusedamount,
												'usedqty'=>$finalusedqty,
												'balanceqty'=>$balanceqty,
													) ;
								 
								 
									
								
										$this->usermodel->updatedata($projectdata,'projectsbudget','id',$myprojectid);
		
		
	  
  }
  

								
								
								
								
								
								
								
								
								
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								redirect($view);
									return false;							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
							redirect($view);	
							return false;							
							}
							   
							
						  
						
						   
						   
						   
						   
				


		
		
					   else
					   {
							redirect('login');
					   }
	    
    }
 
}
	}
	
	
	
	
	
	
		public function addbulkproductsreceiving()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $code="";
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
 	 		
 //$code =  htmlspecialchars(trim($this->input->post("code")));
 
 
 		 
 			$mycode = explode(':=',$this->input->post("code"));

 
  $newcode = htmlspecialchars(trim($mycode[0]));

 
 
 
 
$qty = trim($this->input->post("qty"));
	
				$description = trim($this->input->post("description"));



	 		$mystatus = trim($this->input->post("status"));

			$name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = $this->input->post("total");
			  		   	  //$tobranch = $this->input->post("tobranch");
		   	  $latest = $this->input->post("total");



$mytobranch = explode(':=',$this->input->post("tobranch"));

 
  $tobranch = htmlspecialchars(trim($mytobranch[0]));



			  $view = $this->input->post("view");



	 if( $total < 0){
							 
							  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You can not dispatch negative quantity ('.$qty.') . Try again</div>');
								
													redirect($view);	
								 
								 return false;
							 
							 
							 }







			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");
						 $mycategory = $this->input->post("category");

		   	  $from = $this->input->post("from");
						  // 	  $toproduct = $this->input->post("toproduct");
							  
							 	$mynewproduct = explode(':=',$this->input->post("toproduct"));

 
  $newproduct = htmlspecialchars(trim($mynewproduct[0])); 
							  
							  
$finalybuyingprice=0;
									   	  $invoice = $this->input->post("invoice");
									   	  $compare = $this->input->post("compare");
  
  $currenttuqty=0;
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_movestockinbulk') == "stock")
					   {
					 $myfinalqty="";	   
						   
				   $sellingprice=0;		 
	   $frombalance=0;
					   $tobalance=0;
					   
					   $serial="";
					   $serialid="";
					   if(($mystatus=="serial") && ($latest==1)){
					

						 						 $myserialname = $this->usermodel->geteproductlistbyserial($newcode,$from);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
   
						  $bprice=$myserialname[0]['buyingprice']; 
						  $sprice=$myserialname[0]['sellingprice']; 
						
							
							
							
						   }else{
													  $code= $newcode;   
   
						   }
						   
						   
						   
					
					   }else{
						  $code= $newcode;   
						   
					   }
			
						if ($from =="Main")
						   {
							$productname = $this->usermodel->populateallarray('products','code', $code);
   
							   
						   }else{
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);

							   
							}
						   
						   
						 // $sprice=$myserialname[0]['sellingprice']; 

			
						
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						   			


						 
	
									 
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 

								  	$taxtype=$productname[0]['taxtype']; 

			$item_id=$productname[0]['id'];
			
				
			
			$supplier=$productname[0]['supplier']; 
			$buyingprice=$productname[0]['buyingprice']; 
			$sellingprice=$productname[0]['sellingprice']; 
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
								$status=$productname[0]['status']; 
			 $myfinalqty=$productname[0]['qty']; 

			 $currenttuqty=$productname[0]['qty']; 

			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
  

  
  	
						   


  
  


							
									$myfinalqty=($myfinalqty+$total); 


												$productdata=array(		
												'qty'=>$myfinalqty,
													);
								
								
												
								
								   
						if ($from =="Main")
						   {
								$myusr_result =  $this->usermodel->updateproduct($productdata,$code);
				
							   
						   }else{
							$myusr_result =  $this->usermodel->updateproductlist($productdata,$code,$from); 

							   
							}
							
							
						     if ($myusr_result ==TRUE) //active user record is present
							{
								 
							
								 	   if(($mystatus=="serial") && ($latest==1)){
							
							//
								 $serialdata=array(		
												'branch'=>$from,
													) ;
								 
								 	    $sellingprice=  $sellingprice;
										$buyingprice=  $buyingprice;
								 
									
								
										$this->usermodel->updatedata($serialdata,'serials','id',$serialid);
								 
									   }
								 



if($currenttuqty!=""){
	$currenttuqty=$currenttuqty;
}else{
		$currenttuqty=0;

}

   $frombalance=0;
					   $tobalance= $currenttuqty+$latest;


		$mydata=array(		
			'userid'=>$userid,
							'invoice'=>$invoice,
	'item_id1'=>$currenttuqty,
				'item_id'=>$code,
			'total'=>$total,
					'balance'=>$myfinalqty,
						'companyid'=>$companyid,
'type'=>$from,

			'date'=>$dateposted,
			//'supplier' => $supplier,		  
		    'sellingprice' => $sellingprice, 
		    'buyingprice' => $buyingprice, 
			      'description'=>$description,
				'stockto'=>$from,
				'stockfrom'=>$from,
				'serial'=>$serial,
		'branchid'=>$branchid,
	'category'=>$mycategory,
			
				'projectid'=>$from,

			
								);
								
								$usr_result = $this->usermodel->add($mydata,'newstock');
								
								
								
								
								
					
								
								
								
								
								
								
								
								
								
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								redirect($view);
									return false;							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
							redirect($view);	
							return false;							
							}
							   
							
						  
						
						   
						   
						   
						   
				


		
		
					   else
					   {
							redirect('login');
					   }
	    
    }
 
}
	}
	
	
	
	
	
		public function addbulkstock()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $code="";
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
 	 		
 //$code =  htmlspecialchars(trim($this->input->post("code")));
 
 
 		 
 			$mycode = explode(':=',$this->input->post("code"));

 
   $newcode = htmlspecialchars(trim($mycode[0]));

 

 $salestype = trim($this->input->post("salestype"));

 			  $view = $this->input->post("view");
 			  $inputetimsstockio = $this->input->post("inputetimsstockio");

$qty = trim($this->input->post("qty"));
	
				$description = trim($this->input->post("description"));
	 
					


	 		$mystatus = trim($this->input->post("status"));

			$name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = $this->input->post("total");
			  		   	  $tobranch = $this->input->post("tobranch");
		   	  $latest = $this->input->post("total");


			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");
						 $mycategory = $this->input->post("category");

		   	  $from = $this->input->post("from");
						  // 	  $toproduct = $this->input->post("toproduct");
							  
							 	$mynewproduct = explode(':=',$this->input->post("toproduct"));

 
  $newproduct = htmlspecialchars(trim($mynewproduct[0])); 
							  
							  
$finalybuyingprice=0;
									   	  $invoice = $this->input->post("invoice");
									   	  $compare = $this->input->post("compare");
  
  $currenttuqty=0;
  
  	 if( $total < 0){
							 
							  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You can not dispatch negative quantity ('.$qty.') . Try again</div>');
								
													redirect($view);	
								 
								 return false;
							 
							 
							 }
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_movestock') == "stock")
					   {
						

		 		 $PO = $this->usermodel->populateallarray('bulkdispatch','invoice',$invoice);
				$receivestock=$PO[0]['enddate'];
					
						
						  
				   $sellingprice=0;		 
	   $frombalance=0;
					   $tobalance=0;
					    $myserialname =false;
					   $serial="";
					   $serialid="";
					   if(($mystatus=="serial") && ($latest==1)){
					

						 						 
												 $myserialname = $this->usermodel->geteproductlistbyserial($newcode,$from);
  

 //
 
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 

	$bprice=$myserialname[0]['buyingprice']; 
	
	
	
	
						  $sprice=$myserialname[0]['sellingprice']; 
						
							
   $buyingprice=$myserialname[0]['buyingprice'];
   
   
   
   
	$sellingprice=$myserialname[0]['sellingprice'];
						//  $sprice=$myserialname[0]['sellingprice']; 


  		
						   }else{
													  $code= $newcode;   
   
						   }
						   
						   
						   
					
					   }else{
						  $code= $newcode;  
						  
						   
					   }

						if ($from =="Main")
						   {
							$productname = $this->usermodel->populateallarray('products','code', $code);
   
							   
						   }else{
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);

							   
							}
						   	

						   			$frombefore =$productname[0]['qty']; 
									$fromafter=$productname[0]['qty']-$total; 

						   
						   
						   
						   
						  
					
   
			
		
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist from the source. Try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						   			
					


						  if ($from == $tobranch)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The product can not be transfered to the same counter/branch/store. Select different counters and then try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						 
	
	

	
	
	
	
	
	
	
	
									 
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 

								  	$taxtype=$productname[0]['taxtype']; 

			$item_id=$productname[0]['id'];
			
				
			
			$supplier=$productname[0]['supplier']; 
			
						  if ($myserialname !=false){
					$buyingprice=$myserialname[0]['buyingprice'];
					$sellingprice=$myserialname[0]['sellingprice'];
				
					   }else{
						$buyingprice=$productname[0]['buyingprice']; 
						
						
	if($salestype=="wholesale"){
		$sellingprice=$productname[0]['wholesaleprice']; 

	}else{
		$sellingprice=$productname[0]['sellingprice']; 

		
	}
						
						
						
						
					   }
			
			
			


			
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
								$status=$productname[0]['status']; 

			 $myfinalqty=$productname[0]['qty']; 

			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
  

  
  	   if($total>$myfinalqty ){
			     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> The available quantity ('.$myfinalqty.') is less than what you want to dispatch('.$total.').  Try a gain a lower number or add more stock first.</div>');
						  
						  
								
							redirect($view);
	   return false;
   }
  
  
  

  	if ($tobranch =="Main")
						   {
							$productlist = $this->usermodel->populateallarray('products','code', $code);
   
							 		$currenttuqty=$productlist[0]['qty']; 
  
						   }else{
		$productlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $tobranch);

	$currenttuqty=$productlist[0]['qty']; 
							   
							}
						   



  

						     if ($productlist ==false)
						   {
							   
	$newproductlist=array(		
	'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'shortname'=>$shortname,

			'status'=>$status,
			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
								'branch'=>$tobranch,

			'qty'=>$total,
			

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,
			'taxtype'=>$taxtype,

								);
							   
							   
							   
							   
							   
							   
							   
							   
			$this->usermodel->add($newproductlist,'productlist');
}


     if ($productlist ==true)
			 {
					  	$mybuyingprice=$productlist[0]['buyingprice'];
		$mysellingprice=$productlist[0]['sellingprice'];
		$availableqty=$productlist[0]['qty'];
  
					 
					
		if($compare=="Yes") {
							
							

$firtst=($mybuyingprice*$availableqty);
$second=($buyingprice*$latest);
					$averageprice=($firtst+$second)/($availableqty+$latest);
					
					
					$finalybuyingprice= $this->MyformatMoney($averageprice, true);

					//echo $averageprice."iko";
					
					//exit;
					
						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
								







  
							   
							 $nxtqty=$productlist[0]['qty']; 
				   			$newqty=($nxtqty+$total); 

							   $newproductdata=array(		
												'qty'=>$newqty,
												'buyingprice'=>$finalybuyingprice,
													);
								
			 }
							
									$myfinalqty=($myfinalqty-$total); 


												$productdata=array(		
												'qty'=>$myfinalqty,
													);
								
								
												
								
								   
						if ($from =="Main")
						   {
								$myusr_result =  $this->usermodel->updateproduct($productdata,$code);
				
							   
						   }else{
							$myusr_result =  $this->usermodel->updateproductlist($productdata,$code,$from); 

							   
							}
							
							
						     if ($myusr_result ==TRUE) //active user record is present
							{
								 
							
								 	   if(($mystatus=="serial") && ($latest==1)){
							
							//
								 $serialdata=array(		
												'branch'=>$tobranch,
													) ;
								 
								 	    $sellingprice=  $sellingprice;
										$buyingprice=  $buyingprice;
								 
									
								
										$this->usermodel->updatedata($serialdata,'serials','id',$serialid);
								 
									   }
								 

			if ($productlist ==true)
					{
					
						if($receivestock =="No") {
	


	
					if ($tobranch =="Main")
						   {
							 $this->usermodel->updateproduct($newproductdata,$code);
				
							   
						   }else{
							 $this->usermodel->updateproductlist($newproductdata,$code,$tobranch); 

							   
							}
								
					}
							}


if($currenttuqty!=""){
	$currenttuqty=$currenttuqty;
}else{
		$currenttuqty=0;

}

   $frombalance=0;
					   $tobalance= $currenttuqty+$latest;

		
		
			if($receivestock !="No") {
				
				$tobalance=0;
			}
		
		
		$mydata=array(

			'userid'=>$userid,
							'invoice'=>$invoice,
	'item_id1'=>$currenttuqty,
				'item_id'=>$code,
			
					'balance'=>$tobalance,
						'companyid'=>$companyid,
'type'=>$tobranch,
			'date'=>$dateposted,
			//'supplier' => $supplier,		  
		    'sellingprice' => $sellingprice, 
		    'buyingprice' => $buyingprice, 
			      'description'=>$description,
				
				'stockto'=>$tobranch,
				'stockfrom'=>$from,
				  'total'=>$total,
				'serial'=>$serial,
			 	'branchid'=>$branchid,
				'category'=>$mycategory,
				'frombefore'=>$frombefore,
				'fromafter'=>$fromafter,
				  'fromremoved'=>(-$total),
			
								);
						$mydata2=array(

			'userid'=>$userid,
							'invoice'=>$invoice,
	'item_id1'=>$frombefore,
				'item_id'=>$code,
			
					'balance'=>$fromafter,
						'companyid'=>$companyid,
'type'=>$tobranch,
			'date'=>$dateposted,
			'status' => "removed",		  
		    'sellingprice' => $sellingprice, 
		    'buyingprice' => $buyingprice, 
			      'description'=>$description,
				
				'stockto'=>$tobranch,
				'stockfrom'=>$from,
				  'total'=>(-$total),
				'serial'=>$serial,
			 	'branchid'=>$from,
				'category'=>$mycategory,
				'frombefore'=>$frombefore,
				'fromafter'=>$fromafter,
				  'fromremoved'=>(-$total),
			
								);
											
						$usr_result = $this->usermodel->add($mydata,'newstock');

									
		if (($tobranch =="Main")||($from =="Main")){
									
		}else{
			
			
		//$this->usermodel->add($mydata2,'newstock');

	
		 $accountcode = $this->usermodel->populateallarray('products','code', $code);
					$myassetaccount=$accountcode[0]['assetaccount'];
					
 if($myassetaccount!=""){ $assetaccount=$myassetaccount;}else{ $assetaccount=1110; }





		$debittdata=array( 'userid'=>$userid,'account'=>$assetaccount,'debit'=>($total*$buyingprice),'description'=>"Inventory Transfer",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $tobranch,'companyid'=> $companyid,'type'=> "Transfer",'refno'=> $code,'supplier'=> $supplier);
		$creditdata=array( 'userid'=>$userid,'account'=>$assetaccount,'credit'=>($total*$buyingprice),'description'=>"Inventory Transfer",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $from,'companyid'=> $companyid,'type'=> "Transfer",'refno'=> $code,'supplier'=> $supplier);
		$this->usermodel->add($debittdata,'debitcredit');
		$this->usermodel->add($creditdata,'debitcredit');

									
		}
			


if (($tobranch !="Main")||($from !="Main")){
	

								$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if (($etims =="EnableEtims") && ($inputetimsstockio=="Yes")){
								   

//
	  $LATEST = $this->usermodel->last_record("newstock",$companyid,$userid);
	   	$finalid=$LATEST[0]["id"];
$this-> SendStStockIO($code,$total,$finalid,0,"","","13");
							$this->SendStStockMaster($code,$fromafter);

//


							   }						   
				
							}
								
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								redirect($view);
									return false;							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
							redirect($view);	
							return false;							
							}
							   
							
						  
						
						   
						   
						   
						   
				


		
		
					   else
					   {
							redirect('login');
					   }
	    
    }
 
}
	}
	
	public function transferstock()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $code =  htmlspecialchars(trim($this->input->post("code")));
$qty = trim($this->input->post("qty"));
	
	
			$description = trim($this->input->post("description"));


	 
			$name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  

			  $view = $this->input->post("view");
			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");

		   	  $from = trim($this->input->post("from"));
						   	  $branch = trim($this->input->post("branch"));

			

			
				        //$productname = $this->usermodel->geteproductbyid($code);
								//Main Store
								
									
						  if ($from !="Main")
						   {
							$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);

							
						   }else{

	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not transfer  product from main store while in branch.. do this from main store.. Try different branch.</div>');

						  
								redirect($view);
	   return false;
						   }							   
								
								
								
						  if ($from ==$branch)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not transfer same product to same branch/counter. Try different branch.</div>');

						  
								redirect($view);
	   return false;
						   }
						   
						   
						   
						   
						   
						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
								redirect($view);
	   return false;
						   }
						   
						   
						   



	
		 $availableqty=$productname[0]['qty'];
   $finalqty=($availableqty-$total);

		if($total>$availableqty ){
	     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$availableqty.') is less than what you want to add('.$total.').  Try again.</div>');
						 
						 
							redirect($view);
	   return false;
					
					}

   
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 

			
			$item_id=$productname[0]['id'];
			
				
			
			$supplier=$productname[0]['supplier']; 
			$buyingprice=$productname[0]['buyingprice']; 
			$sellingprice=$productname[0]['sellingprice']; 
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
				$status=$productname[0]['status']; 
				$taxtype=$productname[0]['taxtype']; 

							
			
			
		
			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
  					


	 $productdata=array(		
						'qty'=>$finalqty,
						);
  	//
								
						  if ($branch =="Main")
						   {



   				        $MYproductname = $this->usermodel->geteproductbyid($code);
						
							$mainqty=$MYproductname[0]['qty']; 

		
  $finalmainqty=($mainqty+$total);
	 $productmaindata=array(		
						'qty'=>$finalmainqty,
						);
		
								
								$this->usermodel->updateproductlist($productdata,$code,$from); 
		
								 $this->usermodel->updatedata($productmaindata,'products','code',$code);

								
								
								
								
								
								
								
		$mydata=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'total'=>$total,
			'status'=>'transfer',
						'companyid'=>$companyid,
'type'=>$from,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  	 	'branchid'=>$branchid,
		    'buyingprice' => $buyingprice, 
			     
'description'=>$description,
				'stockfrom' => $from,		  
		  
		    'stockto' => $branch, 
				
				

			
			
								);
															$this->usermodel->add($mydata,'newstock');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								redirect($view);
									return false;		
							   exit;
						   }else{
							   
					 $productlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

						     if ($productlist ==false)
						   {
							   
							   								$newproductlist=array(		
	'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'shortname'=>$shortname,
	 
			
			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
								'branch'=>$branch,

			'qty'=>$total,
												'taxtype'=>$taxtype,

		'status'=>$status,
			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

								);
							   
							   
							   
							   
							   
							   
							   
							   
			$myusr_result = $this->usermodel->add($newproductlist,'productlist');

			
			

			
			

							   if ($myusr_result ==TRUE) //active user record is present
							{
								
								
														$this->usermodel->updateproductlist($productdata,$code,$from); 

								
								
						
								
								
								
		$mydata=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'total'=>$total,
			'status'=>'transfer',
						'companyid'=>$companyid,
'type'=>$from,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  
		    'buyingprice' => $buyingprice, 
			     
'description'=>$description,
				'stockfrom' => $from,		  
		  'balance'=>$finalqty,
					'item_id1'=>$availableqty,
				 	'branchid'=>$branchid,

		    'stockto' => $branch, 
				
			
			
			
								);
															$this->usermodel->add($mydata,'newstock');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								redirect($view);
									return false;							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
							redirect($view);	
							return false;							
							}
							   
							
						  
						
						   }
	}
						   
		   
		
			
			

	
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproductsllist', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_uaddstock') == "transfer")
					   {
							




							$data=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'total'=>$total,
			'status'=>'transfer',

			
						'companyid'=>$companyid,
						'stockfrom' => $from,		
'type'=>$from,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		    'buyingprice' => $buyingprice, 
			     
'description'=>$description,
			'sellingprice'=>$sellingprice,
	  
		  				 	'branchid'=>$branchid,

		    'stockto' => $branch, 
			'balance'=>$finalqty,
					'item_id1'=>$availableqty,
			
			
								);
								
								
												$mainproductdata=array(		
												'qty'=>$finalqty,
													);
								
								
						
				
			
		
							$usr_result = $this->usermodel->add($data,'newstock');

			
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
		
										$this->usermodel->updateproductlist($productdata,$code,$from); 

						
							 
							 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);


	
		 $myavailableqty=$myproducts[0]['qty'];
   $nxtfinalqty=($myavailableqty+$total);
	 $nxtproductdata=array(		
						'qty'=>$nxtfinalqty,
						);
								
			
						$this->usermodel->updateproductlist($nxtproductdata,$code,$branch); 

							  
							 
							 
							 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Stock Added </div>');	
									redirect($view);						   
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not added.. Try again</div>');
								
								
									redirect($view);						   
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 
   public function addstockstore()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("qty"));
			 		  	 $name = trim($this->input->post("name"));

		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");

		   	  $from = trim($this->input->post("from"));
			
			
					   	  

			
			
			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		

		 $this->load->view('userdata/viewstore', $data);
   
							   
						   
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_updatestore') == "store")
					   {
								$myproducts = $this->usermodel->populateallarray('store','code', $code);

									  

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
	
	
   
   if($total>$availableqty ){
	     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$availableqty.') is less than what you want to add('.$total.').  Try again.</div>');
						  
						  
						  
								
							redirect($view);
	   return false;
   }
	
							$finaltotalitems=	$qty+ $total;
								
								$data=array(		
			'qty'=>$finaltotalitems,
		  	
			'userid'=>$userid,
								);
								
								
											$stockdata=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>'store',
				'type'=>$mytype,

								);

						

						$usr_result = $this->usermodel->updatedata($data,'store','code',$code);
   
							   
						 

								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						$this->usermodel->add($stockdata,'newstock');

    

								
									
  
						
								
								
								


						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Updated the  product!</div>');
								if($page!=0){
													redirect($view);	
													//redirect('user/viewproducts/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
					if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
	
	
	
	
	
   public function removestock()
    {
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	 $qty = trim($this->input->post("qty"));
			 		  	 $name = trim($this->input->post("name"));
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
		   	  $total = trim($this->input->post("total"));
			  
			 $code = htmlspecialchars(trim($this->input->post("code")));
			  $view = $this->input->post("view");
			 $mytype = $this->input->post("mytype");
						 $type = $this->input->post("type");

		   	  $from = trim($this->input->post("from"));
			
					   	  $comments = trim($this->input->post("comments"));

					   	  

			
					  $this->form_validation->set_rules("code", "code", "trim|required");

			
		  $this->form_validation->set_rules("productid", "productid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
	
		 $this->load->view('userdata/viewproducts', $data);
  
		
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_uaddstock') == "stock")
					   {
								

								
							
								if($from=="store to kitchen"){
        		$myproducts = $this->usermodel->populateallarray('products','code', $code);

									 $buyingprice=$myproducts[0]['buyingprice'];
		  

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
	
	
   
   if($total>$availableqty ){
	     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$availableqty.') is less than what you want to add('.$total.').  Try again.</div>');
						  
						  
						  
								
							redirect($view);
	   return false;
   }
		
   $finalqty=($availableqty-$total);
	 $productdata=array(		
						'qty'=>$finalqty,
						'userid'=>$userid,
						);
								
								
							$usr_result = $this->usermodel->updatedata($productdata,'products','code', $code);

									
								}else{
						 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $from);
			  										$myproductid =$myproducts[0]["id"];

									 $buyingprice=$myproducts[0]['buyingprice'];
		  

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
	
	
   
   if($total>$availableqty ){
	     $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$availableqty.') is less than what you want to add('.$total.').  Try again.</div>');
						  
						  
						  
								
							redirect($view);
	   return false;
   }
		
   $finalqty=($availableqty-$total);
	 $productdata=array(		
						'qty'=>$finalqty,
						'userid'=>$userid,
						);
								
								
							$usr_result = $this->usermodel->updatedata($productdata,'productlist','id', $myproductid);

									
									
									
								}
							
							
							
							
							
							
							
							
							
						
						
								
								
											$stockdata=array(		
			'total'=>$total,
			'date'=>$dateposted,
				'name'=>$name,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$from,
				'type'=>$mytype,
								'comments'=>$comments,
	'buyingprice'=>$buyingprice,
	 	'branchid'=>$branchid,
								);

							

							
							$usr_result =$this->usermodel->add($stockdata,'outgoingstock');

						   
								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
								
									
  
						
								
								
								


						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully ordered the  product!</div>');
								if($page!=0){
													redirect($view);	
													//redirect('user/viewproducts/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The stock was not Updated.. Try again</div>');
								
					if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	

	
	
	
	
	
	
 	
   public function addtaskcomments()
    {
$session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  			  	 $todate = trim($this->input->post("todate"));


		  	 $page = trim($this->input->post("page"));
				$taskid = trim($this->input->post("taskid"));
		   	  $description = trim($this->input->post("description"));
			  		   	  $exactdate = trim($this->input->post("exactdate"));
			  		   	  $taskowner = trim($this->input->post("taskowner"));
			  		   	  $controller = trim($this->input->post("controller"));
			  		   	  $comments = trim($this->input->post("comments"));
						  			  			  $notification = trim($this->input->post("notification"));

						$view = "user/viewtasks";

			  $recommendation = trim($this->input->post("recommendation"));
		   	  $challanges = trim($this->input->post("challanges"));
					   	  $subject = trim($this->input->post("subject"));
								   	  $img_id = trim($this->input->post("img_id"));
								   	  $type = trim($this->input->post("type"));
								   	  $achieved = trim($this->input->post("achieved"));
  			    $myview = $this->input->post("myview");   

								   	  $photo = trim($this->input->post("photo"));

		  $this->form_validation->set_rules("taskid", "taskid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('admindata/viewtasks',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_taskdata') == "task")
					   {
							
  $finaldescription=$description."<p> Challanges are:</p> ".$challanges;
						   	  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$fromemail=$myconfiguration[0]["email"];
		   

						   
						   $confirmsendercontact= $this->usermodel->geteuser($controller);
						      $confirmacontact= $this->usermodel->geteuser($taskowner);
						  $mycontact= $confirmacontact[0]['phone'];
						  						 $cc= $confirmacontact[0]['email'];
						  						  $surname= $confirmsendercontact[0]['firstname']."   ".$confirmsendercontact[0]['surname'];
								$sendersurname= $confirmacontact[0]['surname'];
							 $toemail = $confirmsendercontact[0]['email'];
						//	$this->sendmyMail1();
$emailtype="TaskFeedback";
						
	

								
								$data=array(		
			'taskid'=>$taskid,
		  	'description'=>$description,
			'userid'=>$userid,
			'date'=>$dateposted,
						'recommendation'=>$recommendation,

									'challanges'=>$challanges,
									'companyid'=>$companyid,
									'exactdate'=>$exactdate,
								'achieved'=>$achieved,

									'mykey'=>$notification,


								);
								
								
											$taskdata=array(		
		  	'status'=>"Pending",
					  
				
								);
								
			
								
								
								
								if($type=="DocumentOnly"){
									
									
											 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						
									$documentsdata=array(		
			'img_id'=>$img_id,
			'documentname'=>$subject,
				'idno'=>"",
			
		  	'description'=>$recommendation,
			'category'=>$subject,
			'entrydate'=>$exactdate,
			'dateposted'=>$dateposted,
					'userid'=>$userid,
									'companyid'=>$companyid,

			
								);
							$usr_result = $this->usermodel->add($documentsdata,'documents');
												$this->uploadtaskimages($view, $img_id,$userid,$notification);

						
								
										 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new document!</div>');
								if($page!=0){
																redirect($myview.'/'.$page);		
	
								}else{
		redirect($myview);	
	
								}
							
								
								}
								
								
					}	
								
								
								
								
								
			
						$usr_result = $this->usermodel->add($data,'taskdata');


								
								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					$this->usermodel->updatedata($taskdata,'tasks','notification',$notification);

					
					
					
					
							
												$this->sendTasktoEmail($fromemail,$toemail,$surname,$todate,$sendersurname,$subject,$finaldescription,$cc,$emailtype);

											 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						
									$documentsdata=array(		
			'img_id'=>$img_id,
			'documentname'=>$subject,
				'idno'=>"",
			
		  	'description'=>$recommendation,
			'category'=>$subject,
			'entrydate'=>$exactdate,
			'dateposted'=>$dateposted,
					'userid'=>$userid,
									'companyid'=>$companyid,

			
								);
							$usr_result = $this->usermodel->add($documentsdata,'documents');
						
						
						
						
						$this->uploadtaskimages($view, $img_id,$userid,$notification);
						
					}
					
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added comments!</div>');
								if($page!=0){
																redirect($myview.'/'.$page);		
	
								}else{
		redirect($myview);	
	
								}
							
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The comments was not added.. Try again</div>');
								
					if($page!=0){
																redirect($myview.'/'.$page);		
	
								}else{
		redirect($myview);	
	
								}
								
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
 	
   public function postdailytask()
    {
$session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	
		  	 $status = ($this->input->post("status"));
		  	 $user = trim($this->input->post("user"));

		  	 $page = trim($this->input->post("page"));

				$taskid = ($this->input->post("taskid"));
		   	  $description = ($this->input->post("description"));

			  $recommendation = ($this->input->post("recommendation"));
		   	  $challanges = ($this->input->post("challanges"));
					   	  $comment = ($this->input->post("comment"));
			  		   	  $achieved = ($this->input->post("achieved"));
			 				$mytaskid = ($this->input->post("mytaskid"));
			 				$exactdate = ($this->input->post("exactdate"));
			 				$view = ($this->input->post("view"));

				 	$mykey = $userid.time();

		  $this->form_validation->set_rules("exactdate", "task date", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('userdata/viewtasks',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_postdailytask') == "task")
					   {
								
							
								
								$data=array(		
			'taskid'=>$taskid,
		  	'description'=>$description,
			'userid'=>$user,
			'date'=>$dateposted,
						'mykey'=>$mykey,

						'recommendation'=>$recommendation,
					'branchid'=>$branchid,

									'challanges'=>$challanges,
									'companyid'=>$companyid,

								);
								
			
						$usr_result = $this->usermodel->add($data,'taskdata');

								
								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{

							
							
							$count =count((array)$achieved);
		  for($i=0; $i< $count; $i++) {
		  
		  
		  
						 $insertdata[]=array(
					 'achieved'=>$achieved[$i],
					'taskid'=>$mytaskid[$i],
					'comment'=>$comment[$i],
					'userid'=>$user,
					'branchid'=>$branchid,
					'mykey'=>$mykey,

					'companyid'=>$companyid,
					'exactdate'=>$exactdate,
					'createdate'=>$dateposted,

					'status'=>$status[$i],

						);
						
		  
		  }	
								$this->db->insert_batch('dailytasks', $insertdata); 
				
							
							
							
							
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added comments!</div>');
								if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);	
	
								}
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The comments was not added.. Try again</div>');
								
					if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
													redirect($view);	
	
								}	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
 	
   public function updatefeedback()
    {
$session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	

		  	 $myview = trim($this->input->post("myview"));
				 $taskid = trim($this->input->post("taskid"));
								$comments = trim($this->input->post("comments"));
								$status = trim($this->input->post("status"));
								 $mykey = trim($this->input->post("mykey"));
							
								$achieved = trim($this->input->post("achieved"));

		   	  $description = trim($this->input->post("description"));
			  
			  $recommendation = trim($this->input->post("recommendation"));
		   	  $challanges = trim($this->input->post("challanges"));
			
			 $companyid = $data['companyid'];
	  $fromdate = $this->input->post("fromdate");

	  $todate = $this->input->post("todate");
	  $user = $this->input->post("user");
		  	  $branchid = $this->input->post("branchid");
	  $type = $this->input->post("type");

	  	  $period = $this->input->post("period");

			
			
			
		  $this->form_validation->set_rules("status", "status", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('admindata/viewmydailyupdates',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_updatefeedback') == "task")
					   {
						   	$taskdata=array(		
		  
					  	'comments'=>$comments,
					  	'status'=>$status,
		'achieved'=>$achieved,
			'updatedby'=>$userid,
			'updateddate'=>$dateposted,
						'recommendation'=>$recommendation,

									'challanges'=>$challanges,
								

								);
					
								$data=array(		
		  	'description'=>$description,
					  	//'comments'=>$comments,
					  	'approval'=>$status,

			'updatedby'=>$userid,
			'updateddate'=>$dateposted,
						'achieved'=>$achieved,

								//	'challanges'=>$challanges,
									'companyid'=>$companyid,

								);
								
			

													$usr_result = $this->usermodel->updatedata($data,'dailytasks','id',$taskid);
							if($taskid !=""){

	
															$usr_result=$this->usermodel->updatedata($taskdata,'taskdata','id',$taskid);

								}
				
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									
							
								

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully updated Feedback!</div>');
							
							
							
					$data['fromdate']=$fromdate;
			$data['todate']=$todate;
			$data['type']=$type;

			$data['period']=$period;
			
			$data['branchid']=$branchid;
			$data['user']=$user;
			$data['companyid']=$companyid;
	
			if($period !=""){
				
				
					redirect('user/viewmytaskreport?fromdate='.$fromdate.'&todate='.$todate.'&type='.$type.'&period='.$period.'&branchid='.$branchid.'&user='.$user.'&companyid='.$companyid);	

			redirect("user/viewtaskreport",$data);	

			}else{
											redirect($myview);	

			}
			

							


								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Feedback was not added.. Try again</div>');
								
																		redirect($myview);	
	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
 	
   public function adddealsfollowups()
    {
$session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	 					 $currentdate=date("Y-m-d H:i:s");
//
// 


	  $mycontact = explode(':=',$this->input->post("contact"));

 
  $contact = htmlspecialchars(trim($mycontact[0]));	



				$type = trim($this->input->post("type"));

				$dateposted = trim($this->input->post("dateposted"));
		   	  $nextdate = trim($this->input->post("nextdate"));
			  						$starttime	 = $this->input->post("starttime"); 

			  $myrecommendation = trim($this->input->post("recommendation"));
		   	  $challanges = trim($this->input->post("challanges"));
					   	 // $level = trim($this->input->post("level"));
					   	  $feedback = trim($this->input->post("feedback"));
					   	  //$followupid = trim($this->input->post("followupid"));
$followupid="";
			
		
		  $this->form_validation->set_rules("contact", "contact details", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('userdata/viedeals',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_followups') == "followup")
					   {
					
						   
						
						   
						   
						   	   
						  $nextdate= $dateposted." ".$starttime.":00";

						  
						   
						   
								     $BUSINESSfeeback= explode("-",$myrecommendation);
									  $recommendation = trim($BUSINESSfeeback[0]);

									  $challanges = trim($BUSINESSfeeback[1]);
						  
						   
						   
						 
							 $followup=$this->usermodel->populateallarray('deals','contact', $contact);

							 
			$finalid=$followup[0]['nextstep'];	
			$followupid=$followup[0]['id'];	
			
			
if($followup==false){

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Follow-up was not posted becuase this customer has not been added as new deal first. You can only do follow up to existing deals only. Try it as new deal.. Try again</div>');
													redirect("user/viedeals");	
													return false;
	
}
	


					
			$currentno= $this->usermodel->countfollowup($finalid,$companyid)+1	;

$level="Followup ".$currentno;
					$data=array(		
			'followupid'=>$followupid,
					  	'level'=>$level,
					  	'feedback'=>$feedback,
											  	'companyid'=>$companyid,
											  	'branchid'=>$branchid,
											  	'finalid'=>$finalid,

			'dateposted'=>$currentdate,

		  	'nextdate'=>$nextdate,
			'userid'=>$userid,
			'date'=>$dateposted,
						'recommendation'=>$recommendation,
												'type'=>$type,


									'challanges'=>$challanges,

								);
								
			
			
				
			
			
			
						$usr_result = $this->usermodel->add($data,'followups');

								
								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											$salesupdate=array(		
					  	
							

								'due_date'=>$nextdate,
			
						


								);
								
								$updatedealsdata=array(		
					  	'stage'=>$level,
					  	'allsteps'=>$feedback,
							
												  	'status'=>$action,

								'todate'=>$nextdate,
			
						'comments'=>$recommendation,


								);
								
								
									if($type=="Invoice"){
									

							 
							 $this->usermodel->updatedata($salesupdate,'sales','invoice',$followupid);
									
								}else{
							 $this->usermodel->updatedata($updatedealsdata,'deals','id',$followupid);

								}


			
								
								
								
								
								
								
								

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully posted followup !</div>');
							
													redirect("user/viedeals");	
	
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Follow-up was not posted.. Try again</div>');
													redirect("user/viedeals");	
	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
 	
   public function addfollowups()
    {
$session_data = $this->session->userdata('logged_in');

   	  	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	 					 $currentdate=date("Y-m-d H:i:s");

// 

	$todate = trim($this->input->post("todate"));
				$type = trim($this->input->post("type"));

				$dateposted = trim($this->input->post("dateposted"));
				$followupid = trim($this->input->post("followupid"));
								$currentid = trim($this->input->post("currentid"));

		   	  $starttime = trim($this->input->post("starttime"));
			  
			  $recommendation = trim($this->input->post("recommendation"));
		   	  $challanges = trim($this->input->post("challanges"));
					   	  $level = trim($this->input->post("level"));
					   	  $feedback = trim($this->input->post("feedback"));
					   	  $action = trim($this->input->post("action"));
						

			
		  $this->form_validation->set_rules("followupid", "followupid", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('admindata/viewfollowups',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_followups') == "followup")
					   {
														  $nextdate= $todate." ".$starttime.":00";
;
								
								
								
								
								
							//	echo $type;
								if($type=="Deal"){
									
 $followup=$this->usermodel->populateallarray('deals','id', $followupid);

							 
			$finalid=$followup[0]['nextstep'];
							 
		
									
								}else{
									$finalid=$followupid;	
								}
					
								$data=array(		
			'followupid'=>$followupid,
					  	'level'=>$level,
					  	'feedback'=>$feedback,
											  	'companyid'=>$companyid,
											  	'branchid'=>$branchid,
											  	'finalid'=>$finalid,
	'status'=>$action,
			'dateposted'=>$currentdate,

		  	'nextdate'=>$nextdate,
			'userid'=>$userid,
			'date'=>$currentdate,
						'recommendation'=>$recommendation,
												'type'=>$type,


									'challanges'=>$challanges,

								);
								
			
			
				
			
			
			
						$usr_result = $this->usermodel->add($data,'followups');

								
								 
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											$salesupdate=array(		
					  	
							

								'due_date'=>$nextdate,
			
						


								);

								
								$updatedealsdata=array(		
					  	'stage'=>$level,
					  	'allsteps'=>$feedback,
												  	'status'=>$action,


								'todate'=>$nextdate,
							'userid'=>$userid,
						'comments'=>$recommendation,


								);
								
								
									if($type=="Invoice"){
									

							 
							 $this->usermodel->updatedata($salesupdate,'sales','invoice',$followupid);
									
								}else{
							 $this->usermodel->updatedata($updatedealsdata,'deals','id',$followupid);

								}
									$followupdata=array(		
					  	
							

								'completed '=>"yes",
			
						


								);
									

							 $this->usermodel->updatedata($followupdata,'followups','id',$currentid);

			
								
								
								
								
								
								
								

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully posted followup !</div>');
							
													redirect('user/viewfollowups?randomitemidentifier='.$followupid.'&type='.$type.'&currentid='.$currentid);	
	
								

								 
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Follow-up was not posted.. Try again</div>');
													redirect('user/viewfollowups?randomitemidentifier='.$followupid.'&type='.$type.'&currentid='.$currentid);	
	
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	 public function addsalary()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				  $myid = $this->input->post("myid");

			  $year = $this->input->post("year");
		 		 $month = $this->input->post("month");
				  $type = $this->input->post("type");
		 		 $designation = $this->input->post("designation");
		 		 $allowance = $this->input->post("allowance");

		   	  $paytype = $this->input->post("paytype");
			  
		     $nohours = $this->input->post("nohours");
			 	 $salary = $this->input->post("salary");
				
			$nodays = $this->input->post("nodays");
			  $nodaysyearly = $this->input->post("nodaysyearly");
			  $annualsalary = $this->input->post("annualsalary");
			  $monthlysalary = $this->input->post("monthlysalary");
			  $dailysalary = $this->input->post("dailysalary");
			  $comments = $this->input->post("comments");
			  $vat = $this->input->post("vat");
			 $payee = trim($this->input->post("payee"));
				$nssf = trim($this->input->post("nssf"));
				
				
				  $nihf = $this->input->post("nihf");
			 $other = trim($this->input->post("other"));
				$loan = trim($this->input->post("loan"));
				
			
			  		  $this->form_validation->set_rules("salary", "salary", "trim|required");
			  		  $this->form_validation->set_rules("type", "Payment type", "trim|required");
			  		  $this->form_validation->set_rules("month", "month", "trim|required");
			  		  $this->form_validation->set_rules("year", "year", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpayee");

		
		 $this->load->view('userdata/payroll', $data);
		$this->load->view("template/footerpayee");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addpayroll') == "payroll")
					   {
												$data=array(		
			'userid'=>$userid,
			'type'=>$type,
				'allowance'=>$allowance,
				'designation'=>$designation,
		  	'paytype'=>$paytype,
			
			
			'createdate'=>$dateposted,
				
			 'salary'=>$salary,
			'nohours'=>$nohours,
			'nodays'=>$nodays,
			'nodaysyearly'=>$nodaysyearly,
			'annualsalary'=>$annualsalary,
				'monthlysalary'=>$monthlysalary,
				'dailysalary'=>$dailysalary,
				
			'comments'=>$comments,
			'vat'=>$vat,
				 'nihf'=>$nihf,
			'other'=>$other,
			'loan'=>$loan,
					
			'month'=>$month,
			'year'=>$year,
			'employeeid'=>$myid,
						'companyid'=>$companyid,

								);
														$usr_result = $this->usermodel->add($data,'payroll');

					

							
							//check if userallowance and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  salary..</div>');	
										
												redirect('user/payroll?randomitemidentifier='.$myid);	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The salary  was not added.. Try again</div>');
								
												redirect('user/payroll?randomitemidentifier='.$myid);	
	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	 public function postcomplain()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				  $itemid = $this->input->post("itemid");

			  $description = $this->input->post("description");
		 		 
			  $sms = $this->input->post("sms");

			  		  $this->form_validation->set_rules("description", "Comment", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmorecomplains', $data);
		$this->load->view("template/footerpayee");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postcomment') == "comment")
					   {
												$data=array(		
			'userid'=>$userid,
			'description'=>$description,
				
			'taskid'=>$itemid,
			'date'=>$dateposted,
			
						'companyid'=>$companyid,

								);
														$usr_result = $this->usermodel->add($data,'complaindata');

					

							
							//check if userallowance and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
											$followupdata=array(		
					  	
							

								'status '=>"Replied",
			
						


								);
									

							 $this->usermodel->updatedata($followupdata,'complain','id',$itemid);

									 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  message..</div>');	
								
								 if($sms=="Yes"){
													
													
							$approver=$this->usermodel->populateallarray('complain','id', $itemid);

			 $contact=$approver[0]['serial'];
			$firstname=$approver[0]['name'];


	   
	   	$message="Dear ".$firstname.", ".$description;

  
							$myview="user/complain";				  
			
													
									//$myview="user/viewmorecomplains?randomitemidentifier=".$itemid;				  
		 // $this->addallpushedsms($message,$contact,$myview);
		  $this->pushedsmswithview($message,$contact,$myview);	

									 
									 
								 }else{
									 
									 
									 
					
										
												redirect('user/viewmorecomplains?randomitemidentifier='.$itemid);	
												
												
								 }
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Message  was not added.. Try again</div>');
								
												redirect('user/viewmorecomplains?randomitemidentifier='.$itemid);	
	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    public function addproduct()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			 	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 	 $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				 
		 		 $imgid = $this->input->post("imgid");
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
		 		 $name = $this->input->post("name");

		   	  $status = $this->input->post("status");
			  		   	  $branch = $this->input->post("branch");
			  		   	  $producttype = $this->input->post("producttype");
			  		   	  $hscode = $this->input->post("hscode");
///
		    
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $myqty = $this->input->post("qty");
			  $reorderevel = $this->input->post("reorderevel");
			  $expdate = $this->input->post("expdate");
			  			  $orderamount = $this->input->post("orderamount");

			  $imgid = $this->input->post("imgid");
			     $view = $this->input->post("view");
			 $type = $this->input->post("type");
			 			 $vattype = $this->input->post("vattype");
			 			 $reorderquantity = $this->input->post("reorderquantity");

			 			 $shortname = $this->input->post("shortname");
				$uom = $this->input->post("uom");

$retailmargin = $this->input->post("retailmargin");
			 			 $description = $this->input->post("description");
						 
						 			 			 $expenseaccount = $this->input->post("expenseaccount");
						 			 			 $assetaccount = $this->input->post("assetaccount");
						 			 			 $salesaccount = $this->input->post("salesaccount");
									 $taxtype = $this->input->post("taxtype");


													$datasaved=0;

								$qty=0;
						 if($branch!="no"){

						 $qty=0;
								
							}else{
							$qty=$myqty;	
							}
				
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");
			  		  $this->form_validation->set_rules("category", "Product category", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");
  if($type=="product"){
		 $this->load->view('userdata/viewproducts', $data);
  
						   }else{
		 $this->load->view('userdata/viewstore', $data);
   
							   
						   }
		
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addproduct') == "product")
					   {
						   
						  
						  
						  
						   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								$itemcode="";
							   if ($etims =="EnableEtims"){
														   
														   
													

					//$itemcode="KE2NTBA0000005";
							
							
							   
						   $myhscode = explode(':=',$this->input->post("hscode"));
							$hscode = htmlspecialchars(trim($myhscode[0]));
						   
						   
							
							
							
							
							
							
							
						   	$itemclassification = $hscode;
						   
						   //$countryoforigin = $this->input->post("countryoforigin");
						  // $itemtype = $this->input->post("itemtype");
						   //$packagingunit = $this->input->post("packagingunit");
						  // $salesunit = $this->input->post("salesunit");
						   
						   
						   
						   	$MYcountryoforigin = explode(':=',$this->input->post("countryoforigin"));
							$countryoforigin = htmlspecialchars(trim($MYcountryoforigin[0]));
						   
						   	$MYitemtype = explode(':=',$this->input->post("itemtype"));
							$itemtype = htmlspecialchars(trim($MYitemtype[0]));
						   
						   $MYpackagingunit = explode(':=',$this->input->post("packagingunit"));
							$packagingunit = htmlspecialchars(trim($MYpackagingunit[0]));
						   
						   
						   $MYsalesunit = explode(':=',$this->input->post("salesunit"));
							$salesunit = htmlspecialchars(trim($MYsalesunit[0]));
						   
						     
						   $MYsalesunit = explode(':=',$this->input->post("salesunit"));
							$salesunit = htmlspecialchars(trim($MYsalesunit[0]));
						   
						   
						     
						   $myitemstatus = explode(':=',$this->input->post("itemstatus"));
							$itemstatus = htmlspecialchars(trim($myitemstatus[0]));
						   
						   $myitemtax= explode(':=',$this->input->post("itemtax"));
							 $itemtax = htmlspecialchars(trim($myitemtax[0]));
				
						   
						  $myitemcode=$countryoforigin.$itemtype.$packagingunit.$salesunit;
						   	 $mylastrecord=0;
		
			$lastrecord = $this->usermodel->last_productbyid($companyid);
			if($lastrecord !=false){
				 $mylastrecord=$lastrecord[0]["id"]+1;
			}else{
				
				 $mylastrecord=$mylastrecord+1;
			}
				
						 
						 
				

									 $itemcode = $myitemcode . sprintf("%07d", $mylastrecord)	;
   
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
						   }											
							
						  
						 $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		 
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);



if($onlineoffline=="OSCU"){
            $apiUrl = ''.$etimsurl.'/etims-api/saveItem';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/saveItems';

			 }
			    
	// API endpoint URL

            // Data to send in the JSON format
         $data = [
		   "tin" => $kra_pin,
            "bhfId" => $branch_id,
 
            "itemCd" => $itemcode,
            "itemClsCd" => $itemclassification,
            "itemTyCd" => $itemtype,
            "itemNm" => $name,
            "itemStdNm" => $name,
            "orgnNatCd" => $countryoforigin,
            "pkgUnitCd" => $packagingunit,
            "qtyUnitCd" => $salesunit,
            "taxTyCd" => $itemtax,
            "btchNo" => 2,
            "bcd" =>$code,
            "dftPrc" => $sellingprice,
            "grpPrcL2" => $sellingprice,
            "grpPrcL3" => $sellingprice,
            "grpPrcL4" => $sellingprice,
            "grpPrcL5" => null,
            "addInfo" => null,
            "sftyQty" => $reorderevel,
            "isrcAplcbYn" => "N",
            "useYn" => "Y",
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


	
				
				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
						



	if ($resultCd == '000') {	
						
							$datasaved=1;
						}else {

							$datasaved=0;
						}							
			





						
					if( $myqty > 0){
						
			//$this->SendStStockMaster($code,$myqty);

					if($onlineoffline=="OSCU"){
        $apiUrl = ''.$etimsurl.'/etims-api/saveStockMaster';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/stockMaster/saveStockMaster';

			 }
			    	
						
		
        // API endpoint URL

        // Data to send in the JSON format
        $data = [
		  "tin" => $kra_pin,
                "bhfId" => $branch_id,
            "itemCd" => $itemcode,
            "rsdQty" => $myqty,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);
						
			$ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);




					        // Check for cURL errors
            if (curl_errno($ch)) {


						
				
				
				
           } else {
				
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



					
		
							}		   
									



  $LATEST = $this->usermodel->last_record("products",$companyid,$userid);
	   	$finalid=$LATEST[0]["id"];
	 
		//echo$finalid=$latestid+1;
		

$this-> SendStStockIO($code,$myqty,$finalid,0,"","","06");





									
										   
						}				   
										   
								   
						}

					 }		   
										   
						   
				}					   
							   					   
						   
						   
						   
						   
						   if($itemcode !=""){
							  $hscode=$itemcode; 
						   }
						   
						   

						   
						   
						   
						   
						   
						   if($type=="product"){
							$productname = $this->usermodel->geteproductbyid($code);
  
						   }else{
							$productname = $this->usermodel->getestorebyid($code);
   
							   
						   }
						   
						
						  if ($productname!=false)
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Product not added!</strong> That product code already  exist. Try again adifferent code.</div>');

						  
							redirect($view);						   
						   return false;
						   }
						   
						   
			$updatedata=array(		
				'qty'=>0,
						 );  
						 
						 
						 
						 											  if ($etims =="EnableEtims"){

						$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'is_serialized'=>$datasaved,
						'shortname'=>$shortname,

					  	'uom'=>$uom,
									'taxtype'=>$taxtype,
									'hscode'=>$hscode,

						'status'=>$status,
						'allow_alt_description'=>$retailmargin,

			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
								'producttype'=>$producttype,
				'reorderquantity'=>$reorderquantity,

				'promoprice'=>$promoprice,
				
			'qty'=>$qty,
			
		
			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
		
		
		

			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,
						'expenseaccount'=>$expenseaccount,
						 'salesaccount'=>$salesaccount,
						 'assetaccount'=>$assetaccount,
											'vattype'=>$vattype,
											
									
		'itemclassification'=>$itemclassification,

		
		'country'=>$countryoforigin,
			'itemtype'=>$itemtype,
			'packagingunit'=>$packagingunit,
			'salesunit'=>$salesunit,
				   	
					 'itemstatus'=>$itemstatus,
						'itemtax'=>$itemtax,
	
											
											
											 	
											
											
											

								);
								



																	  }else{
						   
						   
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	//'shortname'=>$shortname,
						'shortname'=>$shortname,

					  	'uom'=>$uom,
									'taxtype'=>$taxtype,
									'hscode'=>$hscode,

						'status'=>$status,

									'allow_alt_description'=>$retailmargin,

			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
								'producttype'=>$producttype,
				'reorderquantity'=>$reorderquantity,

				'promoprice'=>$promoprice,
				
			'qty'=>$qty,
			
		
			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
		
		
		

			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,
						'expenseaccount'=>$expenseaccount,
						 'salesaccount'=>$salesaccount,
						 'assetaccount'=>$assetaccount,
											'vattype'=>$vattype,
											
		
											
											
											
											
											
											 	
											
											
											

								);
								
								
								
								
									  }
									  
									  
									  
									  
									  
									  
									  
									  
									  
				
							  if ($etims =="EnableEtims"){

$branchdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
								'branch'=>$branch,
								'producttype'=>$producttype,
								'vattype'=>$vattype,
	'is_serialized'=>$datasaved,
		  	'description'=>$description,
					  	'shortname'=>$shortname,

						'status'=>$status,

			
			'dateposted'=>$dateposted,
				'uom'=>$uom,

			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				
			'qty'=>$myqty,
										
				'hscode'=>$hscode,

		
			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

						'taxtype'=>$taxtype,
						
												'allow_alt_description'=>$retailmargin,

	
											
						'itemclassification'=>$itemclassification,

		
		'country'=>$countryoforigin,
			'itemtype'=>$itemtype,
			'packagingunit'=>$packagingunit,
			'salesunit'=>$salesunit,
				   	
					 'itemstatus'=>$itemstatus,
						'itemtax'=>$itemtax,
	
																
					
						
						
						
						
						
						
						
						

								);
								
								
								



							  }else{
									  					  
									  
									  
								
								$branchdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
								'branch'=>$branch,
								'producttype'=>$producttype,
								'vattype'=>$vattype,

		  	'description'=>$description,
					  	'shortname'=>$shortname,
						'allow_alt_description'=>$retailmargin,

						'status'=>$status,

			
			'dateposted'=>$dateposted,
				'uom'=>$uom,

			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				
			'qty'=>$myqty,
										
				'hscode'=>$hscode,

		
			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

						'taxtype'=>$taxtype,
						

						
						
						
						

								);
								
								
								
								
		
								
							  }










							
								
								
								
								
								
								
								
								
								   if($type=="product"){
							$usr_result = $this->usermodel->add($data,'products');
							if($branch=="no"){
							// $this->usermodel->add($branchdata,'productlist');

								
								
							} else if($branch=="all"){
								
								
								   	$branches  = $this->usermodel->populatealldatanoarray('branch','companyid', $companyid,'status',"active" );
						
									if(is_array($branches)) {

									   foreach($branches as $branchesrow){
									   
									   
									   
									    $mybranchid=trim($branchesrow->id);
									
									   
									     if ($etims =="EnableEtims"){
											 
											 
										
											 
									   
									   
														$mybranchdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
								'branch'=>$mybranchid,
								'producttype'=>$producttype,
								'vattype'=>$vattype,
									'hscode'=>$hscode,

		  	'description'=>$description,
					  	'shortname'=>$shortname,

						'status'=>$status,

									'allow_alt_description'=>$retailmargin,

			'dateposted'=>$dateposted,
				'uom'=>$uom,

			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
						'allow_alt_description'=>$retailmargin,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				
			'qty'=>$myqty,
										

						'reorderquantity'=>$reorderquantity,

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,
					
	
											
		'itemclassification'=>$itemclassification,
		'country'=>$countryoforigin,
			'itemtype'=>$itemtype,
			'packagingunit'=>$packagingunit,
			'salesunit'=>$salesunit,
				   	
					 'itemstatus'=>$itemstatus,
						'itemtax'=>$itemtax,

								);
								
								
								 }else{
											 
											 
									
														$mybranchdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
								'branch'=>$mybranchid,
								'producttype'=>$producttype,
								'vattype'=>$vattype,
									'hscode'=>$hscode,

		  	'description'=>$description,
					  	'shortname'=>$shortname,

						'status'=>$status,
						'allow_alt_description'=>$retailmargin,

			
			'dateposted'=>$dateposted,
				'uom'=>$uom,

			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				
			'qty'=>$myqty,
										

						'reorderquantity'=>$reorderquantity,

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

								);
										 
											 
											 
								 }
								
					 $this->usermodel->add($mybranchdata,'productlist');

											
									   }
											
									   }
								
								
								
								
								
								
								
								
							}else{
								
								
							 $this->usermodel->add($branchdata,'productlist');

								
								
							
								
							}
  
						   }
   							
								//$usr_result3 = $this->usermodel->updatedata($updatedata,'products','code',$code);

							   
						   
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
														 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
																$this->uploadimages($imgid,$companyid,$branchid,$userid);

					}
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
										 redirect($view);				
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not added.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
    public function addasset()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 			
		 	 $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
				 
		 		 $imgid = $this->input->post("imgid");
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
		 		 $name = $this->input->post("name");

		   	  $status = $this->input->post("status");
			  		   	  $branch = $this->input->post("branch");
			  		   	  $serialno = $this->input->post("serialno");
			$invoice = $this->input->post("invoice");

		    
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $mode = $this->input->post("mode");
			 // $assetvalue = $this->input->post("assetvalue");
			  $start_date = $this->input->post("start_date");
			  $expdate = $this->input->post("expdate");
			  			  $assetcondition = $this->input->post("assetcondition");
			  $qty = $this->input->post("qty");

			  $imgid = $this->input->post("imgid");
			     $view = $this->input->post("view");
			 $type = $this->input->post("type");
			 			 $shortname = $this->input->post("shortname");
								 			 $uom = $this->input->post("uom");

			 			 $description = $this->input->post("description");
						 						 			 			 $depreciationpercent = $this->input->post("depreciationpercent");

						 			 			 $expenseaccount = $this->input->post("expenseaccount");
						 			 			 $assetaccount = $this->input->post("assetaccount");
						 			 			 $accumulateaccount = $this->input->post("accumulateaccount");

												 $salesaccount = $this->input->post("salesaccount");

							 $accumdepreciation = $this->input->post("accumdepreciation");
						 			 			 $depreciation = $this->input->post("depreciation");
										 			 			 $action = $this->input->post("action");
										 			 			 $myid = $this->input->post("myid");

			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");
 
		 $this->load->view('userdata/viewassets', $data);
  
						
		
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addasset') == "asset")
					   {
						   
						   	if($action=="insert"){
															$productname = $this->usermodel->populateall("assets","code",$code);

  if ($productname!=false)
						   {
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Product not added!</strong> That asset code already  exist. Try again adifferent code.</div>');

						  
							redirect($view);						   
						   return false;
						   }
						   
							}		
								
   
						
						
							$assetvalue=$buyingprice-$accumdepreciation;

						   
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'shortname'=>$shortname,
					  	'uom'=>$uom,

						'status'=>$status,

			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
						'invoice'=>$invoice,

				'mode'=>$mode,
								'serialno'=>$serialno,
								'depreciationpercent'=>$depreciationpercent,

				'assetvalue'=>$assetvalue,
				
			'qty'=>$qty,
			
					'assetaccount'=>$assetaccount,

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'start_date'=>$start_date,
			'expdate'=>$expdate,
						'assetcondition'=>$assetcondition,
						'expenseaccount'=>$expenseaccount,
						 'accumulativeaccount'=>$accumulateaccount,
						 'depreciation'=>$depreciation,
									 'accumdepreciation'=>$accumdepreciation,
										'salesaccount'=>$salesaccount,
								'branch'=>$branch,


								);
								
								
								
								
								
								if($action=="insert"){
								$usr_result = $this->usermodel->add($data,'assets');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'assets','id',$myid);

								}
								

							   
						   
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									
								
								if($action=="insert"){
								//$usr_result = $this->usermodel->add($data,'assets');

									
							
								
								if($status=="New"){
									
									
									
					$debitdata=array( 'userid'=>$userid,'account'=>$assetaccount,'debit'=>$buyingprice,'description'=>"Asset Bought",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'type'=>'asset','refno'=>$code);

					
							$creditdata=array( 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$buyingprice,'description'=>"Asset Bought",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'type'=> "asset",'refno'=> $code);
							
							
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							$susr_result = $this->usermodel->add($creditdata,'debitcredit');

									
									
								}else{
									
										$debitdata=array( 'userid'=>$userid,'account'=>$assetaccount,'debit'=>$buyingprice,'description'=>"Asset Opening Balance Equity",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'type'=>'asset','refno'=>$code);

					
							$creditdata=array( 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$buyingprice,'description'=>"Asset Opening Balance Equity",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'type'=> "asset",'refno'=> $code);
							
							
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							$susr_result = $this->usermodel->add($creditdata,'debitcredit');
									
									
									
									
									
									
									
									$olddebitdata=array( 'userid'=>$userid,'account'=>$expenseaccount,'debit'=>$accumdepreciation,'description'=>"Asset Expensed",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset");


					$oldcreditdata=array( 'userid'=>$userid,'account'=>$accumulateaccount,'credit'=>$accumdepreciation,'description'=>"Accumulative  Amount",'code'=>$invoice,'crateddate'=>$start_date,'branch' => $branch,'companyid'=> $companyid,'refno'=> $code,'type'=> "asset");

					
							$this->usermodel->add($olddebitdata,'debitcredit');	
									$this->usermodel->add($oldcreditdata,'debitcredit');
									
								}
								
								
								}
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  asset..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
										 redirect($view);				
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Asset  was not added.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
    public function addvaluation()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 		 	$data['branchid'] = $session_data['branchid'];
	 $branch = $data['branchid'];
		 						  		   	  $serialno = $this->input->post("serialno");

		 	 $insuredname = $this->input->post("insuredname");

			 	 $insurer = $this->input->post("insurer");
				 
		 		
			 $inspectedby = htmlspecialchars(trim($this->input->post("inspectedby")));
		 		 $contact = $this->input->post("contact");
		 		 $policyno = $this->input->post("policyno");

		   	  $instructions = $this->input->post("instructions");
			  		   	
			$invoice = $this->input->post("invoice");

		    
			$registrationno = $this->input->post("registrationno");
			  $make = $this->input->post("make");
			  $model = $this->input->post("model");
			  $colour = $this->input->post("colour");
			  $yom = $this->input->post("yom");
			  $fueltype = $this->input->post("fueltype");
			  			  $engineno = $this->input->post("engineno");
			  $chassisno = $this->input->post("chassisno");

		
			     $view = $this->input->post("view");
			 $mileage = $this->input->post("mileage");
			 			 $enginerating = $this->input->post("enginerating");
								 			 $countryoforigin = $this->input->post("countryoforigin");

			 			 $locationofinspection = $this->input->post("locationofinspection");
						 						 			 			 $coachwork = $this->input->post("coachwork");

						 			 			 $mechanical = $this->input->post("mechanical");
						 			 			 $electrical = $this->input->post("electrical");
						 			 			 $tyres = $this->input->post("tyres");

												 $assessedvalue = $this->input->post("assessedvalue");

							 $features = $this->input->post("features");
						 			 			 $anittheft = $this->input->post("anittheft");
										 			 			 $action = $this->input->post("action");
										 			 			 $myid = $this->input->post("myid");
																 
																 			$windscreenvalue = $this->input->post("windscreenvalue");
						 			 			 $radiovalue = $this->input->post("radiovalue");
						 			 			 $remarks = $this->input->post("remarks");
						 			 			 $date = $this->input->post("date");
												 						 			 			 $expirydate = $this->input->post("expirydate");

												 												 						 			 			 $generalcondition = $this->input->post("generalcondition");


			  		  $this->form_validation->set_rules("make", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("inspectedby", "Product inspectedby", "trim|required");
			  		  $this->form_validation->set_rules("policyno", "Product policyno", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");
 
		 $this->load->view('userdata/viewassets', $data);
  
						
		
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addvaluation') == "valuation")
					   {
						   
					
   
						
						

						   
												$data=array(	

												 
			'windscreenvalue'=>$windscreenvalue,
				'radiovalue'=>$radiovalue,
				'remarks'=>$remarks,
					 	'date'=>$date,
					  													
			'userid'=>$userid,
			'inspectedby'=>$inspectedby,
				'policyno'=>$policyno,
				'contact'=>$contact,
		  	'locationofinspection'=>$locationofinspection,
					  	'enginerating'=>$enginerating,
					  	'countryoforigin'=>$countryoforigin,
					  	'mileage'=>$mileage,
						'expirydate'=>$expirydate,

						'generalcondition'=>$generalcondition,

			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'registrationno'=>$registrationno,
			'make'=>$make,
						'invoice'=>$invoice,

				'model'=>$model,
								'serialno'=>$serialno,
								'coachwork'=>$coachwork,

				'colour'=>$colour,
				
			'chassisno'=>$chassisno,
			
					'electrical'=>$electrical,

			'insurer'=>$insurer,
			'insuredname'=>$insuredname,
	
			'yom'=>$yom,
			'fueltype'=>$fueltype,
						'engineno'=>$engineno,
						'mechanical'=>$mechanical,
						 'tyres'=>$tyres,
						 'anittheft'=>$anittheft,
									 'features'=>$features,
										'assessedvalue'=>$assessedvalue,
								'branchid'=>$branch,

								);
								
								
								
								
								
								if($action=="insert"){
								$usr_result = $this->usermodel->add($data,'evaluation');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'evaluation','id',$myid);

								}
								

							   
						   
							
							//check if userpolicyno and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									
								
									
							
								
							
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Valuation..</div>');	
										//$this->uploadlostfoundimage($insurer) ;
										 redirect($view);				
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Valuation  was not added.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
    public function addAssessment()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 		 	$data['branchid'] = $session_data['branchid'];
	 $branch = $data['branchid'];
		 						  		   	  $latentdameges = $this->input->post("latentdameges");

		 	 $insuredname = $this->input->post("insuredname");

			 	 $insurer = $this->input->post("insurer");
				 
		 		
			 $garagedetails = htmlspecialchars(trim($this->input->post("garagedetails")));
		 		 $preaccident = $this->input->post("preaccident");
		 		 $policyno = $this->input->post("policyno");

		   	  $instructions = $this->input->post("instructions");
			  		   	
			$invoice = $this->input->post("invoice");

		    
			$registrationno = $this->input->post("registrationno");
			  $make = $this->input->post("make");
			  $model = $this->input->post("model");
			  $colour = $this->input->post("colour");
			  $yom = $this->input->post("yom");
			  $assessmentdate = $this->input->post("assessmentdate");
			  			  $engineno = $this->input->post("engineno");
			  $chassisno = $this->input->post("chassisno");

		
			     $view = $this->input->post("view");
			 $mileage = $this->input->post("mileage");
			 			 $repairer = $this->input->post("repairer");
								 			 $deliverymode = $this->input->post("deliverymode");

			 			 $claimno = $this->input->post("claimno");

						 			 
						 			 			 $tyres = $this->input->post("tyres");

									
										 			 			 $action = $this->input->post("action");
										 			 			 $myid = $this->input->post("myid");
																 
																 						 			 			 $instructionsby = $this->input->post("instructionsby");

						 			 			 $date = $this->input->post("date");
												 						 			 			

			  		  $this->form_validation->set_rules("make", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("garagedetails", "Product garagedetails", "trim|required");
			  		  $this->form_validation->set_rules("policyno", "Product policyno", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");
 
		 $this->load->view('userdata/viewassets', $data);
  
						
		
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addAssessment') == "Assessment")
					   {
						   
					
   
						
						

						   
												$data=array(	

																		 	'instructions'=>$instructions,
	 
							 	'instructionsby'=>$instructionsby,

					 	'date'=>$date,
					  													
			'userid'=>$userid,
			'garagedetails'=>$garagedetails,
				'policyno'=>$policyno,
				'preaccident'=>$preaccident,
		  	'claimno'=>$claimno,
					  	'repairer'=>$repairer,
					  	'deliverymode'=>$deliverymode,
					  	'mileage'=>$mileage,


			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'registrationno'=>$registrationno,
			'make'=>$make,
						'invoice'=>$invoice,

				'model'=>$model,
								'latentdameges'=>$latentdameges,

				'colour'=>$colour,
				
			'chassisno'=>$chassisno,
			

			'insurer'=>$insurer,
			'insuredname'=>$insuredname,
	
			'yom'=>$yom,
			'assessmentdate'=>$assessmentdate,
						'engineno'=>$engineno,
						 'tyres'=>$tyres,
					
								'branchid'=>$branch,

								);
								
								
								
								
								
								if($action=="insert"){
								$usr_result = $this->usermodel->add($data,'assessment');

									
							
								}else{
									
								$usr_result = $this->usermodel->updatedata($data,'assessment','id',$myid);

								}
								

							   
						   
							
							//check if userpolicyno and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									
								
									
							
								
							
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  assessment..</div>');	
										//$this->uploadlostfoundimage($insurer) ;
										 redirect($view);				
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Assessment  was not added.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
			public function postsuggestion()
	{ 
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/postsuggestion');
		$this->load->view("template/footerpage");
	}
	
		
	public function allmydata()
	{ 
		
	$session_data = $this->session->userdata('logged_in');

     $data['username'] = $session_data['username'];
 	$data['id'] = $session_data['id'];
 		$data['firstname'] = $session_data['firstname'];
 			$data['surname'] = $session_data['surname'];
 		
 			
 	$username= $data['username'] ;
	$id= $data['id'] ;
	

$data['province'] = $this->provincemodel->populateprovince();

	$data['county'] = $this->countymodel->populatecounty();
	$data['nation'] = $this->nationmodel->populatenation();


	
	$biodata['bio']= $this->systemusermodel->populatebiodata($id);

	$this->load->view("template/headerpagemin");
	
		
		 $this->load->view('userdata/biodata', $biodata,$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		public function mysuggestion()
		
	{ 
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $this->load->view("template/headerpagemin");
		
	
		$data['suggestion'] = $this->systemusermodel->populatesuggestion($userid);

				$this->load->view('userdata/mysuggestion',$data);
		$this->load->view("template/footerpage");
	}
	
			
			public function adverts()
	{ 
		$session_data = $this->session->userdata('logged_in');

   
		 $this->load->view("template/headerpagemin");
		
	
		$data['adverts'] = $this->systemusermodel->populateadverts();

				$this->load->view('userdata/adverts',$data);
		$this->load->view("template/footerpage");
	}
	
	  public function editmember() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['member'] = $this->usermodel->populatemember($itemid);
   	$data['mycategory'] = $this->usermodel->populatecategory($userid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/editmember', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
    public function editcomputer() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

   	//$data['mycategory'] = $this->usermodel->populatecategory($userid);
					 $data['member'] = $this->usermodel->populateallarray('peopleregistration','id', $itemid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/editcomputer', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
	  public function updatedata() {
  
		$session_data = $this->session->userdata('logged_in');

    $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

					 $data['member'] = $this->usermodel->populateallarray('people','id', $userid);
						 
   	$data['mycategory'] = $this->usermodel->populatecategory($userid);

	
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		
		 $this->load->view('userdata/editreseller', $data);
		$this->load->view("template/footerpage");
		
	
  }
  
  
  
  
  	  public function payroll() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['payroll'] = $this->usermodel->populatemember($itemid);
        		$data['payment'] = $this->usermodel->populateallarray('payroll','employeeid', $itemid);

   	$data['mycategory'] = $this->usermodel->populatecategory($userid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/payroll', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
   public function downloadstore() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."store.csv";

        $query = "SELECT code,name,description,qty,	buyingprice,	sellingprice, wholesaleprice	,reorderevel,category,supplier FROM store WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
  
  
  
   public function downloadsproducts() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."products.csv";

        $query = "SELECT code,name,description,qty,	buyingprice,	sellingprice, wholesaleprice	,reorderevel,category,supplier FROM products WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
  
  
  
    public function downloadcproductscategory() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."productscategory.csv";

        $query = "SELECT id,	name,	description	,status,	maincategory FROM  productcategory WHERE companyid='$companyid' ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
  
	  public function viewconfiguration() {
		  		$session_data = $this->session->userdata('logged_in');

   if (!($session_data)){

    
      show_error('No identifier provided', 500);
    }
    else {

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
        
	
        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

        	

    	$this->load->view("template/headerpagemin", $data);
$data['userid']=$userid;
		$data['companyid']=$companyid;
		 $this->load->view('userdata/configuration', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  


	
	 public function updateconfiguration()
    {
		
		
		
		
	

			$session_data = $this->session->userdata('logged_in');
  $data['id'] = $session_data['id'];
	 $userid = $data['id'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
				  $feedback = $this->input->post("feedback");		

			  $companyid = $this->input->post("companyid");		
  $businessname = $this->input->post("businessname");

  //$businessname = htmlentities($businessname);
 // $businessname = htmlentities($businessname);
 //$businessname = htmlspecialchars($businessname, false);
//$businessname = htmlspecialchars_decode($businessname);
//exit;
//$businessname = htmlspecialchars($businessname, ENT_COMPAT, 'UTF-8', false);


    //$this->form_validation->set_rules('businessname', 'businessname', 'trim|required|xss_clean');
   //print "<p>This is a paragraph.</p>".$businessname;
  // exit;
 		  $etimsonline = $this->input->post("etimsonline");		

 		  $barcode = $this->input->post("barcode");		

		  $display2 = $this->input->post("display2");		
 $display1 = $this->input->post("display1");
	  $signature = $this->input->post("signature");
	  $menutype = $this->input->post("menutype");

	  $email = $this->input->post("email");
	  $contact = $this->input->post("contact");		  
		  $contact2 = $this->input->post("contact2");    
		 $address = $this->input->post("address");   
		  $location = $this->input->post("location");   
		   $contactperson = $this->input->post("contactperson");   
		    $country = $this->input->post("country");   
			 $currencysymbol = $this->input->post("currencysymbol");   
			  $image_id = $this->input->post("image_id");   
			   $tax1 = $this->input->post("tax1");   
			    $tax1rate = $this->input->post("tax1rate");   
				 $tax2 = $this->input->post("tax2");   
				  
				 $website = $this->input->post("website"); 
				 $tax2rate = $this->input->post("tax2rate"); 
				 				 $tillno = $this->input->post("tillno"); 
				 				 $path = $this->input->post("path"); 

			 $salesmethod = $this->input->post("salesmethod"); 
			 				 $sendfeedback = $this->input->post("sendfeedback"); 

				
								 $receiptdescription = $this->input->post("receiptdescription"); 
								 $invoicedetails = $this->input->post("invoicedetails"); 
											 $mode = $this->input->post("mode");

				
											 $view = $this->input->post("view");

				 $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $starttime = $this->input->post("starttime");    
		 $duetime = $this->input->post("duetime");   
				
						 $defautpage = $this->input->post("defautpage");   
						 $ecommerce = $this->input->post("ecommerce");   

				
				
				 $description = $this->input->post("description");
	  $returnpolicy = $this->input->post("returnpolicy");		  
		  $paymenttypes = $this->input->post("paymenttypes");    
		 $logo = $this->input->post("logo");   
				
				 $maindiscount = $this->input->post("maindiscount");   
			    
		  						 $display = $this->input->post("display");   

								 				 $receipt = $this->input->post("receipt"); 

												 
												 					  
									    $username = $this->input->post("username");
								$password = $this->input->post("password");		  
							$from = $this->input->post("from");    
						$code = $this->input->post("code"); 
					$apikey = $this->input->post("apikey"); 
									  $smscompany = $this->input->post("smscompany"); 

									  
									  					$landingpage = $this->input->post("landingpage"); 

									   $newuser = $this->input->post("newuser"); 
									  $newpassword = $this->input->post("newpassword"); 
									  
									   $senderid = $this->input->post("senderid"); 
									  
									  
									  
				
						$dublicate = $this->input->post("dublicate"); 
												 
						$leftoverview = $this->input->post("leftoverview"); 
												 
						$rightoverview = $this->input->post("rightoverview"); 						 
										 
							


						$statushappyhour = $this->input->post("statushappyhour"); 
												 
						$endhappyhourse = $this->input->post("endhappyhourse"); 
												 
						$starthappyhour = $this->input->post("starthappyhour"); 						 
										 
												 
								





							
												 
												 
					$assetaccount = $this->input->post("assetaccount"); 
												 
										$salesaccount = $this->input->post("salesaccount"); 
												 
						$expenseaccount = $this->input->post("expenseaccount"); 						 
								$receiptlogo = $this->input->post("receiptlogo"); 						 
								$hscode = $this->input->post("hscode"); 						 
				$smslogin = $this->input->post("smslogin"); 						 

				$bankcode = $this->input->post("bankcode"); 						 


	  $restricttill = $this->input->post("restricttill");		

	  $servicecharge = $this->input->post("servicecharge");		
 $displayservicecharge = $this->input->post("displayservicecharge");
 $currency = $this->input->post("currency");





			  		  $this->form_validation->set_rules("businessname", "First name", "trim|required|xss_clean");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/configuration', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateconfig') == "config")
					   {
						   
						 
						   
												$data=array(	

		  	'etimsonline'=>$etimsonline,
												
				  	'smslogin'=>$smslogin,

																 
		  	'expenseaccount'=>$expenseaccount,
				'salesaccount'=>$salesaccount,
			'assetaccount' => $assetaccount,
			'hscode' => $hscode,		 							 
			
							'ecommerce' => $ecommerce,		 							 

						'currency' => $currency,		 							 

	'statushappyhour'=>$statushappyhour,
				'starthappyhour'=>$starthappyhour,
			'endhappyhourse' => $endhappyhourse,
							'receiptlogo' => $receiptlogo,	
			
							'sendfeedback' => $sendfeedback,	
							'landingpage' => $landingpage,	
							'restricttill' => $restricttill,		 							 
							
'menutype' => $menutype,		 							 

'salesmethod' => $salesmethod,		 							 
	 
		  	'code'=>$code,
				'username'=>$username,
			'password' => $password,		  
		  'from' => $from,   
		  'apikey' => $apikey,    
		  									  'defautpage'=>$defautpage,

									  'senderid'=>$senderid,
				'dublicate'=>$dublicate,

				'newpassword'=>$newpassword,
							'newuser'=>$newuser,
														'signature'=>$signature,

							'smscompany'=>$smscompany,
									'path'=>$path,

							'todate'=>$todate,

				'starttime'=>$starttime,
			'duetime'=>$duetime,
		  	'fromdate'=>$fromdate,
			'rightoverview'=>$rightoverview,
							'leftoverview'=>$leftoverview,
		
		
															'sendfeedback'=>$sendfeedback,

													'feedback'=>$feedback,

		
											'receipt'=>$receipt,

											'mode'=>$mode,

									'view'=>$view,

							'barcode'=>$barcode,

				'businessname'=>$businessname,
			'tillno'=>$tillno,
		  	'email'=>$email,
				'description'=>$description,
			'returnpolicy' => $returnpolicy,		  
		  'paymenttypes' => $paymenttypes,    
				  'bankcode' => $bankcode,    

			
			'updatedat'=>$dateposted,
			'contact' => $contact,		  
		  'contact2' => $contact2,    
		 'address' => $address,   
		  'location' => $location,   
		   'contactperson' => $contactperson,   
		    'country' => $country,   
			 'currencysymbol' => $currencysymbol,   
			  
			   'tax1' => $tax1,   
			    'tax1rate' => $tax1rate,  
				'tax2' => $tax2,   
				  
				 'website' => $website, 
				 'tax2rate' => $tax2rate, 
				 'userid' => $userid, 
		'display1' => $display1,
		'display2' => $display2,
		'maindiscount' => $maindiscount,
		'receiptdescription' => $receiptdescription,	
				'invoicedetails' => $invoicedetails,	
	  'display' => $display,
			'servicecharge'=>$servicecharge,
				'displayservicecharge'=>$displayservicecharge,

								);
						
								$usr_result = $this->usermodel->updatedata($data,'smsconfig','id',$companyid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
 $file= $_FILES["logo"]['name'];


if($file!=""){
		
		$config['upload_path'] = is_dir($file).'uploads/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('logo')) {               
             $this->data['error'] = $this->upload->display_errors();
            
        } else {
			
        $this->db->set('logo',$new_name );
         $this->db->where('id', $companyid);
         $this->db->update('smsconfig');
        
        }  


}
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated  the Company settings..</div>');	
						 redirect('user/viewconfiguration');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Company settings  was not updated.. Try again</div>');
								
								 redirect('user/viewconfiguration');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
  
   public function addsmsinfo()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $contact = trim($this->input->post("contact"));

		   	  $comment = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $mymessage = htmlspecialchars($comment);
			 

			 
			 
			 
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsms') == "sms")

					   {
						   
				
			

			
			$myArray = explode(',', $contact);
		
					
							 $configrow = $this->usermodel->confirmasmsccount($companyid);

					$companyid=$configrow[0]['id'];
					$user=$configrow[0]['newuser'];
					$senderID=$configrow[0]['senderid'];
					$password=$configrow[0]['newpassword'];	
				$signature=$configrow[0]['website'];	

				
				
									
											        		$totalsmsrow = $this->usermodel->populateallarray('people','id',$userid);

									$totalsms=$totalsmsrow[0]['totalsms'];
									$userid=$totalsmsrow[0]['id'];
										$mycompanyid=$totalsmsrow[0]['companyid'];

$json = '{"messages":[';
$count = 0;
$ttamount = 0;
$mybalance = 0;
$mybulkId=0;
$smsqty="";
 $finaltotalsms=0;
//$receipients = array('2547186673910', '2547164133860');
$numbers = null;
$totalcost = null;
$receiverids = array();

			
								
								foreach($myArray as $allcontacts){
	
										$contacts=$allcontacts;
											
											
												   $countmessage =strlen($mymessage);
					 $COST="";
					 //	$ttamount=0;

					
				 if($countmessage<=144){
				$finaltotalsms=$totalsms-1;
					$COST=1;
					$ttamount=$ttamount+1;
						$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 $finaltotalsms=$totalsms-2;
					$COST=2;
					$ttamount=$ttamount+2;
				 }else if($countmessage<=464){
					$COST=3;
					$ttamount=$ttamount+3;
					$finaltotalsms=$totalsms-3;
				 }
				 else if($countmessage<=624){
					$COST=4;
					$ttamount=$ttamount+4;
					$finaltotalsms=$totalsms-4;
				 }
				 else if($countmessage<=784){
					 $COST=5;
					 $ttamount=$ttamount+5;
					$finaltotalsms=$totalsms-5;
				 }		
													//	$totalcost .= $ttamount;
				 
						

														 if ($contacts !== '') {
														if ($numbers != null) {
															$numbers .= ',';
														}
														$numbers .= $contacts;
	
														}
														
    $sms_body = $mymessage;
	    //$sms_body = $comment . ' ' . $key;

  
    if ($count > 0) {
        $json .= ',';
    }
    $json .= json_encode(array('from' => $senderID, 'to' => $contacts, 'text' => $sms_body));
    $count++;

	
	}
									
									
	

		if($ttamount > $totalsms){
			$diffent=$ttamount-$totalsms;
			
			
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>You have less credit ('.$totalsms .') instead of  ('.$ttamount .') KShs . You need to recharge a minimum of '.$diffent .' for you to send all the messeges </div>');
						redirect('user/viewsms');
						return false;
				
		}
			
				
					
		 $mybalance=$totalsms-$ttamount;

		

$json .= ']}';

$auth = $user . ':' . $password;
$auth_base = base64_encode($auth);
$headers = array();
$headers[] = "content-type: application/json";
$headers[] = "authorization: Basic $auth_base";
$headers[] = "accept: application/json";
$message = 'Test long messages 10';


$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/single");
curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/multi");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');


$output = curl_exec($ch);

$err = curl_error($ch);

curl_close($ch);



$finalcode = curl_exec($ch);

$result = json_decode($output);





if(!isset($result->messages)){
$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or Login details.Try again </div>');
						redirect('user/viewsms');
						return false;
						}
$messages = $result->messages;

$db_data = '';
$insertdata = array();

foreach ($messages as $key => $value) {
    $to = ($value->to);
    $status = ($value->status);
    $groupID = $status->groupId;
    $groupName = $status->groupName;
    $name = $status->name;
    $description = $status->description;
    $smsCount = $value->smsCount;
    $messageId = $value->messageId;

    $messagesObject = json_decode($json)->messages; //Here you're able to get a custom message for each recepient. If you customized a message for each recepient that is :)-

    if ((int) $groupID === 1) {
        //Messages were went successfully::Do whatever you like with sent messages
        //Have a look  at $myJson variable below, it has the data you would like to use
    } else {
        //This are messages that failed::Do whatever you like, eg resend
        //Have a look  at $myJson variable below, it has the data you would like to use
    }

    //Data to store in db::In my case I'm sending this to my custom sms api thus its formatted as json object
    $myJson = json_encode(array(
        'TOKEN' => 'This would be a token from my sms api',
        'PHONE_NUMBER' => $to,
        'STATUS' => $groupName,
        'MESSAGE_ID' => $messageId,
        'MESSAGE' => $messagesObject[$key]->text,
        'COUNT' => $smsCount,
        'DESCRIPTION' => $description
    ));
	
	if($key > 0) {
		$db_data .= ',';
	}

	
	if($count==1){

	$mybulkId=0;
	$smsqty="Single";

		

	}else{
		$bulkId = $result->bulkId;
				$mybulkId=$bulkId;
					$smsqty="Mass";


	}
		
$insertdata[]=array(	
			'contact'=>$to,
		
			'message'=>($mymessage),
			'cost'=>$smsCount,
		  	'status'=>$groupName,
			'bulkId'=>$mybulkId,
			'response'=>$description,
			'postedtime'=>$postedtime,

			'companyid'=>$companyid,
			'userid'=>$userid,
				
				'qty'=>$smsqty,

								);	
   
}
 $updatedata=array(		
		
	'totalsms'=>$mybalance,
	
								);
$usr_result =$this->db->insert_batch('sms', $insertdata); 


        if($this->db->affected_rows() > 0)
	{
					   	$this->usermodel->updatedata($updatedata,'people','id',$userid);
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');	
	}else{
		
		
	$error= mysql_error();	
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or '.$error. '.Try again </div>');
						redirect('user/viewsms');
					
		
	}

		
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
	public function searchsms()
	{ 
	 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($companyid);
$smscompany=$confirmsmsaccount_result[0]['smscompany'];




	
	  $fromdate = $this->input->post("fromdate");
	  $download = $this->input->post("download");
	  

	  
	  $todate = $this->input->post("todate");
	 

				$this->load->view("template/headerpagemin");
						  
			$data['links']="";
			if($download=="yes"){
				
				
				  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."sent sms.csv";
		
								
							
									
 		$query = "SELECT * FROM sms WHERE postedtime BETWEEN '$fromdate'  and '$todate' and userid ='$userid' ";
	
														


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);
return false;
				
			}
				

	
		$query = $this->usermodel->searchsms($fromdate,$todate,$companyid,$userid);

		
		
		$data['viewsms'] = $query['records'];
$data['total_rows'] = $query['count'];

$mytotal_amount = $this->usermodel->countamount($userid);

	$total_amount=$mytotal_amount[0]['totalsms'];	
			$data["total_amount"] =$total_amount;


					
if($smscompany=="Infobip"){
				$this->load->view('userdata/viewsmsinfo',$data);

}else		if($smscompany=="Africaistalking"){
				$this->load->view('userdata/viewsmsafricaistalking',$data);

}else{
				$this->load->view('userdata/viewsms',$data);

	
}
		
		$this->load->view("template/footerpage");
	}
	
	
	
  
  
  
  
		
		
		
		
  public function addsmsafricaistalking()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $contact = $this->input->post("contact");

			  
			   $mymessage = $this->input->post("message");
			  	$message = htmlspecialchars($mymessage);
				
				
			  $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
		    
	
				
			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");
				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsmsafricaistalking', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsmsmain') == "sms")

					   {
						   
						   	   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
						   
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=trim($confirmsmsaccount_result[0]['username']);
$from=trim($confirmsmsaccount_result[0]['from']);
$password=trim($confirmsmsaccount_result[0]['password']);
$apikey=trim($confirmsmsaccount_result[0]['apikey']);
		    $gateway    = new AfricasTalkingGateway($username, $apikey);
		  try 
    { 
     
       $results = $gateway->sendMessage($contact, $message, $from);
                
      foreach($results as $result) {
       
				   
						   
												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$contact,
			
		  	'message'=>$message,
						'companyid'=>$companyid,

			
			'postedtime'=>$dateposted,
				
			
								);
								
								 
							$usr_result = $this->usermodel->add($data,'sms');
						
							 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
							
								$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
				if ($usr_result ==TRUE) //active user record is present
				
							{
								

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	
							redirect('user/viewsms');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS  was not Sent.. Try again</div>');
								
								 redirect('user/viewsms');
		}
      }
	  		 
  
    }
    catch ( AfricasTalkingGatewayException $e )
    {
    // SMS  not Sent to  ".  $recipients .".Error was Encountered  while sending SMS.: ".$e->getMessage().";
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS was not sent!   </strong>   Error was Encountered  while sending SMS.'.$e->getMessage().'.Check your balance or internet availability then try again</div>');
								
								 redirect('user/viewsms');
    }
    // DONE!!! 
if(isset($usr_result)){

 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	

								
								 redirect('user/viewsms');
		

}else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS  was not Sent.. Try again</div>');
								
								 redirect('user/viewsms');
		
	
	
	
}
}
						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

		
		
		
		
		
 
   public function addgroupsmsafricaistalking()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		 			
		 		 $categoryid = $this->input->post("categoryid");

		   	  $mymessage = $this->input->post("message");
			  			  			  		 $message = htmlspecialchars($mymessage);	
		 		 $smscategory = $this->input->post("smscategory");

			  
			  $confirmgroups= $this->usermodel->confirmgroupsaccount($categoryid); 
			  		  $this->form_validation->set_rules("message", "message", "trim|required");
		$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsmsafricaistalking', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			 	if ($this->input->post('btn_groupaddsmsmain') == "oursms")

					   {
						  
			
			
			
				   	 	if ($confirmgroups != false)
								{
							
									
 


//$memberid=$row->memberid;
//$viewmember = $this->usermodel->populatmyemember($memberid);
	//$viewmember = $this->usermodel->getgroupmembers($categoryid);
	
										if($smscategory=="group"){
										$viewmember = $this->usermodel->getgroupmembers($categoryid);

										}else{
									$viewmember = $this->usermodel->getallmobileusers();

										
										}

	
					if(is_array($viewmember)) {

   foreach($viewmember as $c){
			 
				 

              

	   $contact= $c->phone ; 
	   					   
						   
						   
						   	  $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						  	   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
		}
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=trim($confirmsmsaccount_result[0]['username']);
$from=trim($confirmsmsaccount_result[0]['from']);
$password=trim($confirmsmsaccount_result[0]['password']);
$apikey=trim($confirmsmsaccount_result[0]['apikey']);
		    $gateway    = new AfricasTalkingGateway($username, $apikey);
		  try 
    { 
     
       $results = $gateway->sendMessage($contact, $message, $from);
                
      foreach($results as $result) {
       
				   
						   
												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$contact,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'sms');
				if ($usr_result ==TRUE) //active user record is present
							{
						
							
				 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
								$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
	

								 
																						
							}
			
      }
	  		 
  
  
    }
    catch ( AfricasTalkingGatewayException $e )
    {
    // SMS  not Sent to  ".  $recipients .".Error was Encountered  while sending SMS.: ".$e->getMessage().";
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS was not sent!   </strong>   Error was Encountered  while sending SMS.'.$e->getMessage().'.Check your balance or internet availability then try again</div>');
								
								 redirect('user/viewsms');
    }
    // DONE!!! 


	
	 
	 

}



} else {
    echo 'There is no member assigned to this group.';
}
					
	

								
if(isset($usr_result)){

 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	

								
								 redirect('user/viewsms');
		

}else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS  was not Sent.. Try a different group</div>');
								
								 redirect('user/viewsms');
		
	
	
	
}






								
								   }else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There is no any member who is active from the group you have selected.. Try again</div>');
								
								 redirect('user/viewsms');
										}
		
		
}else{
	redirect('login');	
	
	
}
}
	
	}
 
 
		
		
		
		
		public function uploadbulksmsafricaistalking()
        {

          if(isset($_POST["btn_advanceuploadsms"]))
            { 
		
		 $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;
						
						
						
						
		$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $greetings = trim($this->input->post("greetings",true));
		 //$message = trim($this->input->post("message",true));
		 
		 
		 
		   	  $mymessage = $this->input->post("message")	;
			  		 $message = htmlspecialchars($mymessage);
		 
		 
		 		 $smstype = trim($this->input->post("smstype",true));

		$data['id'] = $session_data['id'];
        $finalmessage="";
		$userid = $data['id'];
		
		$postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		
				   	if(($smstype=="one") &&($message=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without typing the message since you have selected one sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
				   	if(($smstype=="many") &&($mymessage=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without message put in the CSV template in column 2 since you have selected many sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
		
		
		
		
		
		
		 try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
		
		
		
		
		
		
		  foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
                  //$inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                 // $inserdata[$i]['Address'] = $emapData['E'];
               
						 	$confirmaccount_result = $this->usermodel->confirmaccount($userid);
					$totalsms=$confirmaccount_result[0]['totalsms'];
					$apiid=$confirmaccount_result[0]['companyid'];
								 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
					$username=$confirmsmsaccount_result[0]['username'];
					$from=$confirmsmsaccount_result[0]['from'];
					 $apikey=trim($confirmsmsaccount_result[0]['apikey']);

					$password=$confirmsmsaccount_result[0]['password'];	
					$totalsent=count((array)$emapData['A']);
					
					 if($smstype=="many"){
					 $mymessage=htmlspecialchars($emapData['B']);

						$finalmessage = $mymessage;
					 } else if($smstype=="onePersonalized"){
						 $mymessage=htmlspecialchars($emapData['B']);
						   $surname=	$emapData['C'];;
						$finalmessage = $greetings." ".$surname.",".$message;
					 }else if($smstype=="manyPersonalized"){
					$mymessage=htmlspecialchars($emapData['B']);

						   $surname=	$emapData['C'];;
					 $finalmessage = $greetings." ".$surname.",".$mymessage;

					 }
					 
					 else{
						$finalmessage = $message; 
					 }
					 
					
						  	   $countmessage =strlen($finalmessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
				 
				 
				 
				 
				 
				 
				 
				 
				 

												if($confirmaccount_result[0]['totalsms']< $COST){
												
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some SMS were not sent. Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
						}
					 $new_date=	date('Y-m-d');
						  $contacts=	$emapData['A'];
						  
						  
						  
		    $gateway    = new AfricasTalkingGateway($username, $apikey);
		  try 
    { 
     
       $results = $gateway->sendMessage($contacts, $finalmessage, $from);
                
      foreach($results as $result) {
	  
	  
	  
	    
						  
						  
							$data=array(		
										'userid'=>$userid,
										
											'contact'=>$emapData['A'],
										
										'message'=>$finalmessage,
										'companyid'=>$companyid,

										
										'postedtime'=>$dateposted,
				
			
											);
					
					
					////
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($finalmessage);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			
				
			   }
	   
			$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	
							redirect('user/viewsms');
	   
	}
    catch ( AfricasTalkingGatewayException $e )
    {
    // SMS  not Sent to  ".  $recipients .".Error was Encountered  while sending SMS.: ".$e->getMessage().";
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS was not sent!   </strong>   Error was Encountered  while sending SMS.'.$e->getMessage().'.Check your balance or internet availability then try again</div>');
								
								 redirect('user/viewsms');
    }
		
                
                   	
              

		  

		  }
		  
		  	
                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }

		  
        
		
		
		
		}
		}
		
				
		
		public function uploadbulksms()
        {

          if(isset($_POST["btn_uploadsms"]))
            { 
		
		 $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;
						
						
						
						
		$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $greetings = trim($this->input->post("greetings",true));
		 //$message = trim($this->input->post("message",true));
		 
		 
		 
		   	  $mymessage = $this->input->post("message")	;
			  		 $message = htmlspecialchars($mymessage);
		 
		 
		 		 $smstype = trim($this->input->post("smstype",true));

		$data['id'] = $session_data['id'];
        $finalmessage="";
		$userid = $data['id'];
		
		$postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		
				   	if(($smstype=="one") &&($message=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without typing the message since you have selected one sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
				   	if(($smstype=="many") &&($message=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without message put in the CSV template in column 2 since you have selected many sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
		
		
		
		
		
		
		 try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
		
		
		
		
		
		
		  foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
                  //$inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                 // $inserdata[$i]['Address'] = $emapData['E'];
               
						 	$confirmaccount_result = $this->usermodel->confirmaccount($userid);
					$totalsms=$confirmaccount_result[0]['totalsms'];
					$apiid=$confirmaccount_result[0]['companyid'];
								 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
					$username=$confirmsmsaccount_result[0]['username'];
					$from=$confirmsmsaccount_result[0]['from'];
					$password=$confirmsmsaccount_result[0]['password'];	
					$totalsent=count((array)$emapData['A']);
					
					 if($smstype=="many"){
					 $mymessage=htmlspecialchars($emapData['B']);

						$finalmessage=$mymessage;
					 } else if($smstype=="onePersonalized"){
						 $mymessage=htmlspecialchars($emapData['B']);
						   $surname=$emapData['C'];
						$finalmessage=$greetings." ".$surname.",".$message;
					 }else if($smstype=="manyPersonalized"){
					$mymessage=htmlspecialchars($emapData['B']);

						   $surname=$emapData['C'];
					 $finalmessage=$greetings." ".$surname.",".$mymessage;

					 }
					 
					 else{
						$finalmessage =$message; 
					 }
					 
					
						  	   $countmessage =strlen($finalmessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
				 
				 
				 
				 
				 
				 
				 
				 
				 

												if($confirmaccount_result[0]['totalsms']< $COST){
												
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some SMS were not sent. Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
						}
					 $new_date=	date('Y-m-d');
						  $contacts=trim($emapData['A']);
						
							
							$data=array(		
										'userid'=>$userid,
										
											'contact'=>$emapData['A'],
																			//	'message'=>mysql_real_escape_string($finalmessage),

										'message'=>$finalmessage,
										'companyid'=>$companyid,

										
										'postedtime'=>$dateposted,
				
			
											);
							//	  $inserdata[$i]['userid'] = $userid;
                  //$inserdata[$i]['contact'] = $emapData['A'];
                 // $inserdata[$i]['message'] = $finalmessage;
                  //$inserdata[$i]['companyid'] = $companyid;
                //  $inserdata[$i]['postedtime'] = $postedtime;
             
		
								
						
		
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($finalmessage) . "&shortcode=".urlencode($from)."&mobile=$contacts";

				//$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($finalmessage) . "&shortcode=" . urlencode($from) . "&mobile=$contacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);



$finalcode="";
   if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 
	



		
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($finalmessage);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			
				
				}	
								
					
                         $i++;
                }               
              
                
		if($finalcode=="Success"){
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$contacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}

               } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
           

		  


		  
		  	}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Error uploading excel file .Try again</div>');
							redirect('user/viewsms');
			
				
			}

		  }
        
		
		
		
		}
		
		
		
		
		
		
		public function uploadbulksms__()
        {

          if(isset($_POST["btn_uploadsms"]))
            { 
		
		 $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;
						
						
						
						
		$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $greetings = trim($this->input->post("greetings",true));
		 //$message = trim($this->input->post("message",true));
		 
		 
		 
		   	  $mymessage = $this->input->post("message")	;
			  		 $message = htmlspecialchars($mymessage);
		 
		 
		 		 $smstype = trim($this->input->post("smstype",true));

		$data['id'] = $session_data['id'];
        $finalmessage="";
		$userid = $data['id'];
		
		$postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		
				   	if(($smstype=="one") &&($message=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without typing the message since you have selected one sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
				   	if(($smstype=="many") &&($mymessage=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without message put in the CSV template in column 2 since you have selected many sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
		
		
		
		
		
		
		 try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
		
		
		
		
		
		
		  foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
                  //$inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                 // $inserdata[$i]['Address'] = $emapData['E'];
               
						 	$confirmaccount_result = $this->usermodel->confirmaccount($userid);
					$totalsms=$confirmaccount_result[0]['totalsms'];
					$apiid=$confirmaccount_result[0]['companyid'];
								 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
					$username=$confirmsmsaccount_result[0]['username'];
					$from=$confirmsmsaccount_result[0]['from'];
					$password=$confirmsmsaccount_result[0]['password'];	
					$totalsent=count((array)$emapData['A']);
					
					 if($smstype=="many"){
					 $mymessage=htmlspecialchars($emapData['B']);

						$finalmessage = $mymessage;
					 } else if($smstype=="onePersonalized"){
						 $mymessage=htmlspecialchars($emapData['B']);
						   $surname=	$emapData['C'];;
						$finalmessage = $greetings." ".$surname.",".$message;
					 }else if($smstype=="manyPersonalized"){
					$mymessage=htmlspecialchars($emapData['B']);

						   $surname=	$emapData['C'];;
					 $finalmessage = $greetings." ".$surname.",".$mymessage;

					 }
					 
					 else{
						$finalmessage = $message; 
					 }
					 
					
						  	   $countmessage =strlen($finalmessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
				 
				 
				 
				 
				 
				 
				 
				 
				 

												if($confirmaccount_result[0]['totalsms']< $COST){
												
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some SMS were not sent. Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
						}
					 $new_date=	date('Y-m-d');
						  $contacts=	$emapData['A'];;
						  $url = 'http://sms.robisearch.com/sendsms.jsp?';
								$xml_data ='<?xml version="1.0"?><smslist><sms><user>'.$username.'</user><password>'.$password.'</password><message>'.$finalmessage.'</message><mobiles>'.$contacts.'</mobiles><senderid>'.$from.'</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid></sms></smslist>'; 
							
							
							$data=array(		
										'userid'=>$userid,
										
											'contact'=>$emapData['A'],
										
										'message'=>mysql_real_escape_string($finalmessage),
										'companyid'=>$companyid,

										
										'postedtime'=>$dateposted,
				
			
											);
							//	  $inserdata[$i]['userid'] = $userid;
                  //$inserdata[$i]['contact'] = $emapData['A'];
                 // $inserdata[$i]['message'] = $finalmessage;
                  //$inserdata[$i]['companyid'] = $companyid;
                //  $inserdata[$i]['postedtime'] = $postedtime;
             
		
								
						
			$ch = curl_init($url);			
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
			curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
			try{
				
	
			$xml = new SimpleXMLElement($output);
			
			$code="error-code";
			$mydescription="error-description";
			$finalcode=$xml->error->$code;
			$description=$xml->error->$mydescription;
			if($finalcode== 0) {
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($finalmessage);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
				} catch (Exception $e) {
								//echo 'Error occurred during Sending Message: Please check on your internet connection or balance or ',  $e->getMessage(), "\n .Try again ";

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance..Try again</div>');
							redirect('user/viewsms');		
				}	
								
					
                         $i++;
                }               
              
                
                   	if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$contacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewsms');
			
				
			}

               } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
           

		  


		  
		  	}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Error uploading excel file .Try again</div>');
							redirect('user/viewsms');
			
				
			}

		  }
        
		
		
		
		}
		
		
		
		
		
		
		
		
		
   public function uploadbulksmsinfo()
    {
		if(isset($_POST["btn_uploadinfosms"]))

					   {
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


		   	  $comment = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 						 $mymessage = htmlspecialchars($comment);

			 
			
			 
			 
			 
			 
					   //validation succeeds
					
						   
						   
		 $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
			  $config['max_size']  = 40960000;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
			
			
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
		   
		   
                        //$inputFileName =$import_xls_file;
						
						
	
	 $greetings = trim($this->input->post("greetings",true));
		 //$message = trim($this->input->post("message",true));
		 
		 
		 
		 
		 		 $smstype = trim($this->input->post("smstype",true));

		$data['id'] = $session_data['id'];
        $finalmessage="";
		$userid = $data['id'];
		
		$postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		
				   	if(($smstype=="one") &&($mymessage=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without typing the message since you have selected one sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
				   	if(($smstype=="many") &&($mymessage=="")){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload sms without message put in the CSV template in column 2 since you have selected many sms to many people.. Try again</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
		
		
		
		
		
		
		 try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
				
			

			
		
					
							 $configrow = $this->usermodel->confirmasmsccount($companyid);

					$companyid=$configrow[0]['id'];
					$user=$configrow[0]['newuser'];
					$senderID=$configrow[0]['senderid'];
					$password=$configrow[0]['newpassword'];	
				$signature=$configrow[0]['website'];	

									
											        		$totalsmsrow = $this->usermodel->populateallarray('people','id',$userid);

									$totalsms=$totalsmsrow[0]['totalsms'];
									$userid=$totalsmsrow[0]['id'];
										$mycompanyid=$totalsmsrow[0]['companyid'];

$json = '{"messages":[';
$count = 0;
$ttamount = 0;
$mybalance = 0;
$mybulkId=0;
$smsqty="";
 $finaltotalsms=0;
//$receipients = array('2547186673910', '2547164133860');
$numbers = null;
$totalcost = null;
$receiverids = array();





										if(is_array($allDataInSheet)) {

			
		  foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
                  //$inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                 // $inserdata[$i]['Address'] = $emapData['E'];
               
						 	
					$totalsent=count((array)$emapData['A']);
					
					 if($smstype=="many"){
					 $mymessage=htmlspecialchars($emapData['B']);

						$finalmessage = $mymessage;
					 } else if($smstype=="onePersonalized"){
						 $mymessage=htmlspecialchars($emapData['B']);
						   $surname=	$emapData['C'];;
						$finalmessage = $greetings." ".$surname.",".$mymessage;
					 }else if($smstype=="manyPersonalized"){
					$mymessage=htmlspecialchars($emapData['B']);

						   $surname=	$emapData['C'];;
					 $finalmessage = $greetings." ".$surname.",".$mymessage;

					 }
					 
					 else{
						$finalmessage = $mymessage; 
					 }
					   $contacts=	$emapData['A'];
					
						  	   $countmessage =strlen($finalmessage);
			
			

											
										
											
											
					 $COST="";
					 //	$ttamount=0;

					
				 if($countmessage<=144){
				$finaltotalsms=$totalsms-1;
					$COST=1;
					$ttamount=$ttamount+1;
						$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 $finaltotalsms=$totalsms-2;
					$COST=2;
					$ttamount=$ttamount+2;
				 }else if($countmessage<=464){
					$COST=3;
					$ttamount=$ttamount+3;
					$finaltotalsms=$totalsms-3;
				 }
				 else if($countmessage<=624){
					$COST=4;
					$ttamount=$ttamount+4;
					$finaltotalsms=$totalsms-4;
				 }
				 else if($countmessage<=784){
					 $COST=5;
					 $ttamount=$ttamount+5;
					$finaltotalsms=$totalsms-5;
				 }		
													//	$totalcost .= $ttamount;
				 
						

														 if ($contacts !== '') {
														if ($numbers != null) {
															$numbers .= ',';
														}
														$numbers .= $contacts;
	
														}
														
    $sms_body = $finalmessage;
	    //$sms_body = $comment . ' ' . $key;

  
    if ($count > 0) {
        $json .= ',';
    }
    $json .= json_encode(array('from' => $senderID, 'to' => $contacts, 'text' => $sms_body));
    $count++;

	
	}
									
}else{
	$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> There is nobody in the selected group.Please assign somebody to this group first then try again</div>');
							redirect('user/viewsms');	

}	
	

		if($ttamount > $totalsms){
			$diffent=$ttamount-$totalsms;
			
			
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>You have less credit ('.$totalsms .') instead of  ('.$ttamount .') KShs . You need to recharge a minimum of '.$diffent .' for you to send all the messeges </div>');
						redirect('user/viewsms');
						return false;
				
		}
			
				
					
		 $mybalance=$totalsms-$ttamount;

		

$json .= ']}';

$auth = $user . ':' . $password;
$auth_base = base64_encode($auth);
$headers = array();
$headers[] = "content-type: application/json";
$headers[] = "authorization: Basic $auth_base";
$headers[] = "accept: application/json";
$message = 'Test long messages 10';


$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/single");
curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/multi");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');


$output = curl_exec($ch);

$err = curl_error($ch);

curl_close($ch);



$finalcode = curl_exec($ch);

$result = json_decode($output);





if(!isset($result->messages)){
$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or Login details.Try again </div>');
						redirect('user/viewsms');
						return false;
						}
$messages = $result->messages;

$db_data = '';
$insertdata = array();

foreach ($messages as $key => $value) {
    $to = ($value->to);
    $status = ($value->status);
    $groupID = $status->groupId;
    $groupName = $status->groupName;
    $name = $status->name;
    $description = $status->description;
    $smsCount = $value->smsCount;
    $messageId = $value->messageId;

    $messagesObject = json_decode($json)->messages; //Here you're able to get a custom message for each recepient. If you customized a message for each recepient that is :)-

    if ((int) $groupID === 1) {
        //Messages were went successfully::Do whatever you like with sent messages
        //Have a look  at $myJson variable below, it has the data you would like to use
    } else {
        //This are messages that failed::Do whatever you like, eg resend
        //Have a look  at $myJson variable below, it has the data you would like to use
    }

    //Data to store in db::In my case I'm sending this to my custom sms api thus its formatted as json object
    $myJson = json_encode(array(
        'TOKEN' => 'This would be a token from my sms api',
        'PHONE_NUMBER' => $to,
        'STATUS' => $groupName,
        'MESSAGE_ID' => $messageId,
        'MESSAGE' => $messagesObject[$key]->text,
        'COUNT' => $smsCount,
        'DESCRIPTION' => $description
    ));
	
	if($key > 0) {
		$db_data .= ',';
	}

	
	if($count==1){

	$mybulkId=0;
	$smsqty="Single";

		

	}else{
		$bulkId = $result->bulkId;
				$mybulkId=$bulkId;
					$smsqty="Mass";


	}
		
$insertdata[]=array(	
			'contact'=>$to,
		
			'message'=>$finalmessage,
			'cost'=>$smsCount,
		  	'status'=>$groupName,
			'bulkId'=>$mybulkId,
			'response'=>$description,
			'postedtime'=>$postedtime,

			'companyid'=>$companyid,
			'userid'=>$userid,
				
				'qty'=>$smsqty,

								);	
   
}
 $updatedata=array(		
		
	'totalsms'=>$mybalance,
	
								);
$usr_result =$this->db->insert_batch('sms', $insertdata); 


        if($this->db->affected_rows() > 0)
	{
					   	$this->usermodel->updatedata($updatedata,'people','id',$userid);
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');	
	}else{
		
		
	$error= mysql_error();	
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or '.$error. '.Try again </div>');
						redirect('user/viewsms');
					
		
	}

		
		
		
		
		 } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
           
		
		
		
		
					   }
					   else
					   {
							redirect('login');
					   }
	 
  
	}
	}
  
		
		
  
	
	
	
	

   public function addgroupsmsinfo()
    {
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $categoryid = $this->input->post("categoryid");


		   	  $comment = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 //$message = htmlspecialchars($comment);
			 
			 
						 $mymessage = htmlspecialchars($comment);

			 
			 
			 
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("categoryid", "category", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsmsinfo', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_groupaddsms') == "oursms")

					   {
						   
				
			

			
		
					
							 $configrow = $this->usermodel->confirmasmsccount($companyid);

					$companyid=$configrow[0]['id'];
					$user=$configrow[0]['newuser'];
					$senderID=$configrow[0]['senderid'];
					$password=$configrow[0]['newpassword'];	
				$signature=$configrow[0]['website'];	

									
											        		$totalsmsrow = $this->usermodel->populateallarray('people','id',$userid);

									$totalsms=$totalsmsrow[0]['totalsms'];
									$userid=$totalsmsrow[0]['id'];
										$mycompanyid=$totalsmsrow[0]['companyid'];

$json = '{"messages":[';
$count = 0;
$ttamount = 0;
$mybalance = 0;
$mybulkId=0;
$smsqty="";
 $finaltotalsms=0;
//$receipients = array('2547186673910', '2547164133860');
$numbers = null;
$totalcost = null;
$receiverids = array();

			
			
			
										if($smscategory=="group"){
										$myArray = $this->usermodel->getgroupmembers($categoryid);

										}else{
									$myArray = $this->usermodel->getallmobileusers();

										
										}

										//$myArray = $this->usermodel->getgroupmembers($categoryid);

										if(is_array($myArray)) {

								foreach($myArray as $allcontacts){
											$contacts= $allcontacts->phone ;
											
										
											
											
												   $countmessage =strlen($mymessage);
					 $COST="";
					 //	$ttamount=0;

					
				 if($countmessage<=144){
				$finaltotalsms=$totalsms-1;
					$COST=1;
					$ttamount=$ttamount+1;
						$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 $finaltotalsms=$totalsms-2;
					$COST=2;
					$ttamount=$ttamount+2;
				 }else if($countmessage<=464){
					$COST=3;
					$ttamount=$ttamount+3;
					$finaltotalsms=$totalsms-3;
				 }
				 else if($countmessage<=624){
					$COST=4;
					$ttamount=$ttamount+4;
					$finaltotalsms=$totalsms-4;
				 }
				 else if($countmessage<=784){
					 $COST=5;
					 $ttamount=$ttamount+5;
					$finaltotalsms=$totalsms-5;
				 }		
													//	$totalcost .= $ttamount;
				 
						

														 if ($contacts !== '') {
														if ($numbers != null) {
															$numbers .= ',';
														}
														$numbers .= $contacts;
	
														}
														
    $sms_body = $mymessage;
	    //$sms_body = $comment . ' ' . $key;

  
    if ($count > 0) {
        $json .= ',';
    }
    $json .= json_encode(array('from' => $senderID, 'to' => $contacts, 'text' => $sms_body));
    $count++;

	
	}
									
}else{
	$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> There is nobody in the selected group.Please assign somebody to this group first then try again</div>');
							redirect('user/viewsms');	

}	
	

		if($ttamount > $totalsms){
			$diffent=$ttamount-$totalsms;
			
			
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>You have less credit ('.$totalsms .') instead of  ('.$ttamount .') KShs . You need to recharge a minimum of '.$diffent .' for you to send all the messeges </div>');
						redirect('user/viewsms');
						return false;
				
		}
			
				
					
		 $mybalance=$totalsms-$ttamount;

		

$json .= ']}';

$auth = $user . ':' . $password;
$auth_base = base64_encode($auth);
$headers = array();
$headers[] = "content-type: application/json";
$headers[] = "authorization: Basic $auth_base";
$headers[] = "accept: application/json";
$message = 'Test long messages 10';


$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/single");
curl_setopt($ch, CURLOPT_URL, "http://api.infobip.com/sms/1/text/multi");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');


$output = curl_exec($ch);

$err = curl_error($ch);

curl_close($ch);



$finalcode = curl_exec($ch);

$result = json_decode($output);





if(!isset($result->messages)){
$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or Login details.Try again </div>');
						redirect('user/viewsms');
						return false;
						}
$messages = $result->messages;

$db_data = '';
$insertdata = array();

foreach ($messages as $key => $value) {
    $to = ($value->to);
    $status = ($value->status);
    $groupID = $status->groupId;
    $groupName = $status->groupName;
    $name = $status->name;
    $description = $status->description;
    $smsCount = $value->smsCount;
    $messageId = $value->messageId;

    $messagesObject = json_decode($json)->messages; //Here you're able to get a custom message for each recepient. If you customized a message for each recepient that is :)-

    if ((int) $groupID === 1) {
        //Messages were went successfully::Do whatever you like with sent messages
        //Have a look  at $myJson variable below, it has the data you would like to use
    } else {
        //This are messages that failed::Do whatever you like, eg resend
        //Have a look  at $myJson variable below, it has the data you would like to use
    }

    //Data to store in db::In my case I'm sending this to my custom sms api thus its formatted as json object
    $myJson = json_encode(array(
        'TOKEN' => 'This would be a token from my sms api',
        'PHONE_NUMBER' => $to,
        'STATUS' => $groupName,
        'MESSAGE_ID' => $messageId,
        'MESSAGE' => $messagesObject[$key]->text,
        'COUNT' => $smsCount,
        'DESCRIPTION' => $description
    ));
	
	if($key > 0) {
		$db_data .= ',';
	}

	
	if($count==1){

	$mybulkId=0;
	$smsqty="Single";

		

	}else{
		$bulkId = $result->bulkId;
				$mybulkId=$bulkId;
					$smsqty="Mass";


	}
	
		
$insertdata[]=array(	
			'contact'=>$to,
		
			'message'=>$mymessage,
			'cost'=>$smsCount,
		  	'status'=>$groupName,
			'bulkId'=>$mybulkId,
			'response'=>$description,
			'postedtime'=>$postedtime,

			'companyid'=>$companyid,
			'userid'=>$userid,
				
				'qty'=>$smsqty,

								);	
   
}
 $updatedata=array(		
		
	'totalsms'=>$mybalance,
	
								);
$usr_result =$this->db->insert_batch('sms', $insertdata); 


        if($this->db->affected_rows() > 0)
	{
					   	$this->usermodel->updatedata($updatedata,'people','id',$userid);
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');	
	}else{
		
		
	$error= mysql_error();	
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or '.$error. '.Try again </div>');
						redirect('user/viewsms');
					
		
	}

		
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
  
  
  
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function updatebusisinessconfiguration()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['id'] = $session_data['id'];
	 $userid = $data['id'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
	
				$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];	
 $deadlinedetails = $this->input->post("deadlinedetails");

 		  $businesskey = trim($this->input->post("businesskey"));		

		  $deadline = $this->input->post("deadline");		

			 $this->form_validation->set_rules("deadline", "Deadline ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/config', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updabusinessteconfig') == "updatebusinessconfig")
					   {
						   
						 
							  $serial =trim(`wmic bios get serialnumber 2>&1`) ;

								$myfinalserial= explode("SerialNumber",str_replace("", "", $serial));
								 $finalserial = trim($myfinalserial[1]);
 								
							
								  		 
								   $localIP = getHostByName(getHostName());
if($finalserial==""){
$finalserial=$localIP;
}	
								  
								  	
								
								
								$finalserialdecoded =trim($this->encryption->decrypt($businesskey));

	
        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id > ',0);
				
				if($finalserialdecoded !=$finalserial){
					
				
				
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Activation key entered is not correct.. Try again</div>');
								
								 	 redirect('user/config');	
								 return false;
				}
				



				
				//$dbpassword =$this->encryption->decrypt($usr_result[0]->password);
				
				
				
			
		
						   
						   
												$data=array(		
		
							'deadline'=>$deadline,

				'deadlinedetails'=>$deadlinedetails,
			'businesskey'=>$businesskey,
		

		
								);
						
								$usr_result = $this->usermodel->updatedata($data,'smsconfig','id >',0);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated  the Company settings..</div>');	
						 redirect('user/config');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Company settings  was not updated.. Try again</div>');
								
								  redirect('user/config');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	public function updatebusisinessconfiguration1()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['id'] = $session_data['id'];
	 $userid = $data['id'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
	
				$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];	
 
 $deadlinedetails = $this->input->post("deadlinedetails");

 		  $businesskey = trim($this->input->post("businesskey"));		

		  $deadline = $this->input->post("deadline");		



				
				
				
				
			  		  $this->form_validation->set_rules("deadline", "Deadline ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/config', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updabusinessteconfig') == "updatebusinessconfig")
					   {
						   
						   
						   
						   
												$data=array(		
		
							'deadline'=>$deadline,

				'deadlinedetails'=>$deadlinedetails,
			'businesskey'=>$businesskey,
		

		
								);
						
								$usr_result = $this->usermodel->updatedata($data,'smsconfig','id',$companyid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated  the Company settings..</div>');	
						 redirect('user/config');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Company settings  was not updated.. Try again</div>');
								
								 redirect('user/config');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	 public function getstocktakingbyserial() {
   if (!isset($_GET['startdate'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $_GET['branchid'];
	  $startdate =$_GET['startdate'];
	  $closedate = $_GET['closedate'];

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		$data['closedate']=$closedate;
		$data['startdate']=$startdate;

	$data['branchid']=$branchid;
		$data['display']="no";
	
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['viewproducts'] = $this->usermodel->viewstocktakingreportserial($startdate,$companyid,$branchid);
		//var_dump($data['salesreport']);
		//exit;
				$this->load->view('userdata/viewtocktakingreportserial',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
	
	
	  public function editeroles() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['role'] = $this->usermodel->populateallarray('roles','id',$itemid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/editeroles', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
	
	
	  public function editemployee() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['member'] = $this->usermodel->populateallarray('people','id',$itemid);
   	$data['mycategory'] = $this->usermodel->populatecategory($userid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/editemployee', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
		  public function viewfollowups() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $currentid = $_GET['currentid'];

	      $type = $_GET['type'];
//


        		//$data['mytask'] = $this->usermodel->populateall('followups','followupid', $itemid);
   	
						$data['mytask']  = $this->usermodel->populatealldatanoarray('followups','followupid', $itemid,'type', $type);

    	//$this->load->view("template/headerpagemin", $data);
		
	
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		 
		 
		 
		 
		 
		 
		 $data['currentid']=$currentid;
		  
		$data['type']=$type;

$data['itemid']=$itemid;

		
		 $this->load->view('userdata/viewfollowups', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	

	
	
	
	
	
	
	
	
	
	
	
		  public function employeenote() {
			  
			  			  
			  

		$session_data = $this->session->userdata('logged_in');

   $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
 	$data['id'] = $session_data['id'];
         $companyid = $session_data['companyid'];
 	$data['id'] = $session_data['id'];
		 $userid = $data['id'];


			  
			  	
	if (isset($_POST['btn_PostNotes'])){

        
		  	$randomitemidentifier = $this->input->post("randomitemidentifier");			 		 		 
$currentid = $this->input->post("currentid");
	  
    }else  if (isset($_GET['randomitemidentifier'])){
     $randomitemidentifier = $_GET['randomitemidentifier'];
	      $currentid = $_GET['currentid'];
    
    }else{
		
		      show_error('No identifier provided', 500);

		
	}
	
	
			  
			  
			  
			  
			  
			  
			  
			  
			  
			  
			  
			  
			  

//


        		//$data['mytask'] = $this->usermodel->populateall('followups','followupid', $itemid);
   	
						$data['complain']  = $this->usermodel->populatealldatanoarray('complain','companyid', $companyid,'messageid', $currentid);

    	//$this->load->view("template/headerpagemin", $data);
		
	
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		 
		 
		 
		 	 $data['links']="";
		 
		 	 $data['total_rows']=count((array)$data['complain'] );
		 		 $data['randomitemidentifier']=$randomitemidentifier;

		 $data['currentid']=$currentid;
		  

$data['itemid']=$randomitemidentifier;

		
		 $this->load->view('userdata/employeenote', $data);
		$this->load->view("template/footerpage");
		
	
  }
	
	
	
	
	
	 public function viewrequestmessages() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['message'] = $this->usermodel->populateall('approvals','applicationid', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorerequest', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
	
	
	
	
	
		  public function viewmoretasks() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	  $owner = $_GET['owner'];
	 	$getmaiantask = $this->usermodel->populateallarray('tasks','id',$itemid);

      $notification=$getmaiantask[0]["notification"];
	 
$data["myview"]="Systemusers/viewmoretasks?randomitemidentifier=".$itemid;

        		//$data['mytask'] = $this->usermodel->populateall('taskdata','taskid', $itemid);
					        		$data['mydocuments'] = $this->usermodel->populateall('alldocuments','documentname', $notification);
					$data['mytask']  = $this->usermodel->populatealldatanoarray('taskdata','taskid', $itemid,'userid',$owner);

   	
$page=0;
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
$data['page']=$page;
      $subject=$getmaiantask[0]["subject"];

      $comments=$getmaiantask[0]["comments"];

$data['subject']=$subject;
$data['comments']=$comments;

		
		 $this->load->view('userdata/viewmoretasks', $data);
		$this->load->view("template/footerpage");
		
	}
  }

	
		  public function viewmorecomplains() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
     $itemid = $_GET['randomitemidentifier'];

        		$data['mytask'] = $this->usermodel->populateall('complaindata','taskid', $itemid);
   	

		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorecomplains', $data);
		$this->load->view("template/footerpage");
		
	}
  }
			  public function viewmoreincomingstock() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
$branch = $_GET['branch'];

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

						$data['mystock']  = $this->usermodel->populateallBRANCHSTOC('newstock','item_id', $itemid,'type', $branch);


							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorestock', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
		
	
	
	
	
		  public function printvaluation() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');
	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

   			        		$data['report'] = $this->usermodel->populateallarray('evaluation','invoice', $itemid);


					









					
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/printvaluation', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
	
	
	
	
	
	
		  public function printassessment() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');
	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

   			        		$data['report'] = $this->usermodel->populateallarray('assessment','invoice', $itemid);


					









					
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/printassessment', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
	
	
	
	
	
	
	
	
	
	
			  public function viewmorestock() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');
	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

   			        		$data['mystock'] = $this->usermodel->populateall('newstock','item_id', $itemid);


					









					
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorestock', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
    public function viewbackupnow() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	
	  //
						
															
	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
				$this->load->view("template/tableheader");

		 $this->load->view('userdata/viewbackupnow', $data);
		$this->load->view("template/footerpage");	
						
	
	
}



}






  
  
  
  
  
  
  
  
  
  
  
  
  
  
		  public function backupnow() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	     $location = $_GET['location'];

	      $view = $_GET['view'];
					$database  = $this->usermodel->populatealldataarray('backup','id', $itemid,'status',"active" );
		

if($database !=false){
			    $mypath=$database[0]["path"];
						    $server=$database[0]["server"];

	 // $mypath=$database[0]["path"];
		    $user=$database[0]["user"];
			    $password=$database[0]["password"];
				    $host=$database[0]["host"];
					    $database=$database[0]["database"];
						
						     //$myserver=$database[0]["server"];
							 if($location=="online"){
								 

 $local_file = $mypath.date('Y-m-d').$database."-".date('H').".gz";
    exec('mysqldump --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . ' | gzip > ' . $local_file);

		 
								 
							 }else{
								 
	$local_file = $mypath.date('Y-m-d').$database."-".date('H').".sql";
 exec(''.$server.'mysqldump.exe --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . '  > ' . $local_file);

								 
								 
								 
							 }

								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully backuped the data    $mypath.</div>');	
							redirect($view);																
						
						
}else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Wrong details.Try again</div>');
								
							redirect($view);	
	
}










		
		
	}
  }
  
  
			  public function viewbranchproduction() {
   if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 
		 
		 
     $itemid = $_GET['mycode'];
	     $branch = $_GET['branch'];
 $mycode = $_GET['mycode'];
	      $page = $_GET['page'];
   			        		//$data['uomprice'] = $this->usermodel->populateall('uomproducts','code', $itemid);
					$data['uomprice']  = $this->usermodel->populatealldatarraythree('uomproducts','code', $itemid,'status',"active",'branch',$branchid );
					$data['child']  = $this->usermodel->populatealldatarraythree('uomproducts','code', $itemid,'status',"child",'branch',$branchid); 


//
   			        		$data['viewprice'] = $this->usermodel->populateall('productlist','code', $itemid);
   			        		$data['product'] = $this->usermodel->populateall('products','code', $itemid);


							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
 

$data['page']=$page;
		
		 $this->load->view('userdata/viewbranchproduction', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  		  public function viewetimsbulkupdate() {
 

		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
  
	 
    	$this->load->view("template/headerpagemin", $data);

		
		 $this->load->view('userdata/viewetimsbulkupdate', $data);
		$this->load->view("template/footerpage");
		
	
  }
  		  public function viewprice() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	 if(isset($_GET['branchid'])==true){
	$branchid = $_GET['branchid'];	 
	 }else{
		 	$data['branchid'] = $session_data['branchid'];
        
		 $branchid = $data['branchid'];
	 }
	      

	
	      $page = $_GET['page'];
   			        		//$data['uomprice'] = $this->usermodel->populateall('uomproducts','code', $itemid);
					$data['uomprice']  = $this->usermodel->populatealldatanoarray('uomproducts','code', $itemid,'status',"active" );
					$data['child']  = $this->usermodel->populatealldatanoarraythreechild('uomproducts','code', $itemid,'status',"child" ,'branch',$branchid);


   			        	$data['viewprice'] = $this->usermodel->populateall('productlist','code', $itemid);
   			        	$data['product'] = $this->usermodel->populateall('products','code', $itemid);


							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
 
$data['page']=$page;
		$data['mybranchid']=$branchid;
		
		if((isset($_GET['branchid'])=="all")){
					 $this->load->view('userdata/viewprice', $data);

			
		}else{
					 //$this->load->view('userdata/viewpricebranch', $data);
	 $this->load->view('userdata/viewprice', $data);
		}

		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
			  public function viewetimsupdate() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	
	      $page = $_GET['page'];
   			
   		$data['products'] = $this->usermodel->populateallarray('products','code', $itemid);


							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
 

$data['page']=$page;
		///
		 $this->load->view('userdata/viewetimsupdate', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
			  public function viewswapping() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $code = $_GET['code'];

	      $invoice = $_GET['invoice'];
 $data['viewdistribution'] = $this->usermodel->populateallarray('sales_order','id', $itemid);

 $data['viewproducts'] = $this->usermodel->populateallarray('products','code', $code);

											 

							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
$data['code']=$code;

$data['invoice']=$invoice;
	$data['page']=0;	
		 $this->load->view('userdata/viewswapping', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
			  public function viewdistribution() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $code = $_GET['code'];

	      $page = $_GET['page'];
 $data['viewdistribution'] = $this->usermodel->populateallarray('productlist','id', $itemid);


											 

							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
$data['code']=$code;

$data['page']=$page;
		
		 $this->load->view('userdata/viewdistribution', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  		  public function gatepasschekin() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         	$data['companyid'] = $session_data['companyid'];
			 $companyid = $data['companyid'];
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	     
 $data['gatepass'] = $this->usermodel->populateallarray('gatepass','id', $itemid);


											 

							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;

		
		 $this->load->view('userdata/gatepass', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  	  public function viewmygatepasscheckins() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         	$data['companyid'] = $session_data['companyid'];
			 $companyid = $data['companyid'];
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	     
 $data['callcenter'] = $this->usermodel->populateall('checkin','visitorid', $itemid);


		$data['links']="";
			$data['total_rows']=count((array)$data['callcenter']);							 

							
    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;

		
		 $this->load->view('userdata/viewmygatepasscheckins', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
	
	
	
	
		public function searchallactivities()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallactivities';
		$query = $this->usermodel->searchallactivities($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['loggs'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/activityloggs',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
	
	
	
		public function searchuserloggs()
	{
			 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchuserloggs';
		$query = $this->usermodel->searchuserloggs($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['loggs'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				
			$this->load->view('userdata/loggs',$data);
				
		$this->load->view("template/footerpage");
		
	}
  
  
  
  
		public function downloaduserloggs() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."downloadeduserloggs.csv";
		
								
							
								      //  $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";
	
 									

        $query = "SELECT  people.firstname,timein,timeout,ip FROM loggs  INNER JOIN people on loggs.userid =people.id   ORDER BY loggs.id desc";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
		
  public function downloaduserloggsbydate() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."downloadeduserloggs.csv";
		 $fromdate = $this->input->post("fromdate");
			 $todate = $this->input->post("todate");
								
							
								      //  $query = "SELECT stocktaking.code,name,open,added,	balance,branchid,startdate,closedate FROM stocktaking INNER JOIN products on  stocktaking.code= products.code WHERE stocktaking.startdate ='$startdate' and  stocktaking.type ='Main Store' and stocktaking.companyid='$companyid' ORDER BY products.category ";
	
 									

        $query = "SELECT  people.firstname,timein,timeout,ip FROM loggs  INNER JOIN people on loggs.userid =people.id   WHERE timein BETWEEN '$fromdate'  and '$todate' ORDER BY loggs.id desc";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
		
	
  

			  public function viewproductdetails() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
    	$this->load->view("template/headerpagemin");

		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         	$data['companyid'] = $session_data['companyid'];
			 $companyid = $data['companyid'];
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $code = $_GET['code'];

	      $page = $_GET['page'];
 $data['products'] = $this->usermodel->populateallarray('products','code', $code);
 $data['productlist'] = $this->usermodel->populateallarray('productlist','id', $itemid);
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);


											 

							
    
$data['itemid']=$itemid;
//$data['code']=$code;

$data['page']=$page;
		
		 $this->load->view('userdata/viewproductdetails', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
 public function updatemybranchproduct()
    {
		
$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
			 $code = htmlspecialchars(trim($this->input->post("code")));
		 		 $category = $this->input->post("category");
				 		 		 $myid = $this->input->post("myid");

		 		 $name = $this->input->post("name");
		   	  $status = $this->input->post("status");

		   	  $description = $this->input->post("description");
			  		   	  $imgid = $this->input->post("imgid");

		     $store = $this->input->post("store");
			 	 $tax_included = $this->input->post("tax_included");
							 	 $hscode = $this->input->post("hscode");

			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $wholesaleprice = $this->input->post("wholesaleprice");
			  $promoprice = $this->input->post("promoprice");
			  $qty = $this->input->post("qty");
			  			  $branch= $this->input->post("branch");

			  			 			 $reorderquantity = $this->input->post("reorderquantity");

			  		
			
			  $reorderevel = $this->input->post("reorderevel");
			 $page = trim($this->input->post("page"));
				$productid = trim($this->input->post("productid"));
				 $expdate = $this->input->post("expdate");
				 				 $orderamount = $this->input->post("orderamount");
			$view = $this->input->post("view");
			 $type = $this->input->post("type");
			  			 $shortname = $this->input->post("shortname");
					  	 $uom = $this->input->post("uom");
					  	 $producttype = $this->input->post("producttype");
					  	 $maincode = $this->input->post("maincode");
													$expenseaccount = $this->input->post("expenseaccount");
						 			 			 $assetaccount = $this->input->post("assetaccount");
						 			 			 $salesaccount = $this->input->post("salesaccount");

									 			 $vattype = $this->input->post("vattype");
									 			 $taxtype = $this->input->post("taxtype");
	 $start_date = $this->input->post("start_date");
	 $end_date = $this->input->post("end_date");

					
			  		  $this->form_validation->set_rules("buyingprice", "Buying price", "trim|required");
			  		  $this->form_validation->set_rules("code", "Product Code", "trim|required");
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");
			  		  $this->form_validation->set_rules("category", "Product category", "trim|required");

			 
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		 if($type=="product"){
		 $this->load->view('userdata/viewproducts', $data);
  
						   }else{
		 $this->load->view('userdata/viewstore', $data);
   
							   
						   }
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatemyproduct') == "product")
					   {
						   
						
						 
						   		$productlistdata=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
												'tax_included'=>$tax_included,

								'hscode'=>$hscode,
								'branch'=>$branch,

								'expdate'=>$expdate,

				'category'=>$category,
		  	'description'=>$description,
					  	'orderamount'=>$orderamount,
'reorderevel'=>$reorderevel,
	'store'=>$store,

						'uom'=>$uom,
								'producttype'=>$producttype,
									'taxtype'=>$taxtype,
														'reorderquantity'=>$reorderquantity,
	
	'store'=>$store,
	'status'=>$status,
			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'vattype'=>$vattype,

			'supplier'=>$supplier,
			'qty'=>$qty,
			'end_date'=>$end_date,
			'start_date'=>$start_date,
	
		
			
								);
						   
						   
						   
						   
						   
												$data=array(	
												
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  			'expenseaccount'=>$expenseaccount,
						 'salesaccount'=>$salesaccount,
						 'assetaccount'=>$assetaccount,
						'vattype'=>$vattype,
									'taxtype'=>$taxtype,

						'reorderquantity'=>$reorderquantity,
				'reorderevel'=>$reorderevel,

													'hscode'=>$hscode,
	
			'shortname'=>$shortname,
			'dateposted'=>$dateposted,
			'uom'=>$uom,
			 'tax_included'=>$tax_included,
		
			'supplier'=>$supplier,
			//'buyingprice'=>$buyingprice,
			//'sellingprice'=>$sellingprice,
			//	'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
				'status'=>$status,
				
												'producttype'=>$producttype,

			//'qty'=>$qty,
			
		'expdate'=>$expdate,
		
			
			'orderamount'=>$orderamount,
						
				
					

								);
								
							
								 
  ///

						  
  											$usr_result = 		 $this->usermodel->updatedata($productlistdata,'productlist','id',$productid);

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 				
			 						$usr_result = $this->usermodel->updatedata($data,'products','code',$code);


													
	
								
												 

								
								
								      				
														 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						
						$imgiddata=array(					
				'imgid'=>$imgid
						);
			 						$usr_result = $this->usermodel->updatedata($imgiddata,'products','code',$code);

																$this->uploadimages($imgid,$companyid,$branchid,$userid);

					}
								
						
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										//$this->uploadlostfoundimage($imgid) ;
											if($page!=0){
													redirect($view.'/'.$page);	
	
								}else{
																redirect($view);	
								}					
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not Updated.. Try again</div>');
								
								 	if($page!=0){
													redirect($view.'/'.$page);
	
								}else{
													redirect($view);
	
								}
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
  
  
  
			  public function bulkdispatch() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $invoice = $_GET['invoice'];
	        $type = $_GET['type'];
		   
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
		   		         $status = $_GET['status']; 
  $category = $_GET['category'];
		         $salestype = $_GET['salestype']; 
  
		         $tobranch = $_GET['tobranch']; 
		      $frombranch = $_GET['frombranch']; 
 $data['viewdistribution'] = $this->usermodel->populateallarray('bulkdispatch','invoice', $invoice);
   	///$data['viewincomingstock'] = $this->usermodel->populateall('newstock','invoice', $invoice);
	 	$data['viewincomingstock']  = $this->usermodel->populatealldatanoarraythree('newstock','invoice', $invoice,'itemstatus<>','removed','companyid',$companyid);

									 
				
    	$this->load->view("template/headerpagemin", $data);
$data['invoice']=$invoice;
$data['type']=$type;
$data['salestype']=$salestype;

$data['tobranch']=$tobranch;
$data['frombranch']=$frombranch;
$data['status']=$status;
$data['category']=$category;
if(($category=="Customer") || ($category=="Project")|| ($category=="BulkReceiving") ){
	
			 		 $this->load->view('userdata/bulkprojectdispatch', $data);

	
}else{
	
			 $this->load->view('userdata/bulkdispatch', $data);

	
}

		 

		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  	  public function viewreportbycustomedcategory() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 

		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
     $itemid = $_GET['randomitemidentifier'];
	
	        	$this->load->view("template/headerpagemin", $data);



   			        	
   	
   $type = $_GET['type'];
$data['itemid']=$itemid;

	
	$data['myviewproducts']= $this->usermodel->viewreportbycustomedcategory(0, 0,"products",$companyid,$itemid);
	
	
					$this->load->view('userdata/viewreportbycustomedcategory',$data);


	

		
		$this->load->view("template/footerpage");
	}
	}
 
  
  
  
			  public function viewmainstockreportcategory() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

		 
     $itemid = $_GET['randomitemidentifier'];
	
	        	$this->load->view("template/headerpagemin", $data);



   			        	
   	
   $type = $_GET['type'];
$data['itemid']=$itemid;
$data['branchname']=$branchid;

if( $type=="main"){
	
	$data['viewproducts']= $this->usermodel->populatealldatawhere('products','name','ASC','category',$itemid);
					$this->load->view('userdata/viewmainproductstock',$data);

}else{

	
	
					$this->load->view('userdata/viewmainproductstockmain',$data);

}

								


	

		
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
  
  
			  public function productsdashboard() {
   if (!isset($_GET['branchname'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
     $branchname = $_GET['branchname'];
	
	        	$this->load->view("template/headerpagemin", $data);



   			        	
   	

$data['branchname']=$branchid;


	
	$data['viewproducts']= $this->usermodel->getProductDashboard($branchname,$companyid);
	
	


								


						$this->load->view('userdata/productsdashboard',$data);


		
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
  
  
  
  
		public function downloadproductcategory()
	{ 

	
   if (!isset($_GET['category'])){

    
      show_error('No identifier provided', 500);
    }
    else {





$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00";
	  $totime="23:59:59";
	  $category = $_GET['category'];
$type = $_GET['type'];
	  	  $branch = $_GET['branch'];

				


				
	
	if($type=="main"){
				  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."CATEGORY MAIN STOCK.csv";
        $query = "SELECT code,name,description,qty,	buyingprice,	sellingprice, wholesaleprice	,reorderevel,category,supplier FROM products WHERE category='$category'  order by  category  asc  ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
		     	  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."CATEGORY STOCKLIST.csv";
        $query = "SELECT code,name,description,qty,	buyingprice,	sellingprice, wholesaleprice	,reorderevel,category,supplier,branch FROM productlist WHERE category='$category'  and branch='$branch'  order by  category  asc  ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);;
	}
}
}	
	
	
	
	
  
  
  
  
  
  	  public function viewstockreportcategory() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
					   	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	
	$userid=$data['id'] ;
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

   
 	$data['id'] = $session_data['id'];
        
     $itemid = $_GET['randomitemidentifier'];
	        	$this->load->view("template/headerpagemin", $data);



   			        	
   			        		//$data['viewproducts'] = $this->usermodel->populateall('products','category', $itemid);


					

								   $type = $_GET['type'];
$data['branch']=$branchid;
$data['itemid']=$itemid;
if( $type=="sub"){
	
$data['viewproducts']= $this->usermodel->populatealldatawhere('productlist','name','ASC','category',$itemid);
				$this->load->view('userdata/viewproductstock',$data);

}else{

	
	
				$this->load->view('userdata/viewproductstockmain',$data);

}

								
								
								
								
								
								
								
								
								
								
								
								

	

		
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
				  public function viewmorestockstore() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

				        		$data['mystock'] = $this->usermodel->populatealldatanoarray('newstock','item_id', $itemid,'type', 'store');

   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorestockstore', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	  public function viewmorestockbyinvoiceno() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['mystock'] = $this->usermodel->populateall('newstock','invoice_number', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorestockbyinvoiceno', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
			  public function viewmoredocuments() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $type = $_GET['type'];

if( $type=="task"){
	        		$data['mydocuments'] = $this->usermodel->populateall('alldocuments','documentname', $itemid);

}else{
	
	        		$data['mydocuments'] = $this->usermodel->populateall('alldocuments','img_id', $itemid);

}
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
	$data['type']=$type;	
		 $this->load->view('userdata/viewmoredocuments', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
			  public function viewmoredocs() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['mydocuments'] = $this->usermodel->populateall('alldocuments','img_id', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmoredocs', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
    
    public function viewmoreevaluation() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['application'] = $this->usermodel->populateall('evaluation','invoice', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		$data['total_rows']=count((array)$data['application'] );
		$data['links']="";
		 $this->load->view('userdata/viewmoreevaluation', $data);
		$this->load->view("template/footerpage");
		
	}
  }	
  
  
  
  

    
    public function viewmoreassessment() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['application'] = $this->usermodel->populateall('assessment','invoice', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		$data['total_rows']=count((array)$data['application'] );
		$data['links']="";
		 $this->load->view('userdata/viewmoreassessment', $data);
		$this->load->view("template/footerpage");
		
	}
  }	
  
  
  
  
  
  
  
  
  
  
	
			  public function viewmorerequestdocuments() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['mydocuments'] = $this->usermodel->populateall('documents','img_id', $itemid);
   	

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmorerequestdocuments', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
		
public function uploadpurchasesmaster()
        {

          if(isset($_POST["btn_uploadpurchasesmaster"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				 	 
		
			
		   $currenttime = date('Y-m-d H:i:sa');
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	   $vatrate=$configuration[0]['tax1rate'];
	  
	  
	  $dateposted = date('Y-m-d H:i:s');
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
											$paymenttype = trim($this->input->post("paymenttype"));

     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				    $SUPPLIERIDS = $emapData['A'];
					$REFNO = $emapData['C'];
				  					   
					
							 if($SUPPLIERIDS !=""){
								 
								 
								 $myuser=$this->usermodel->geteuser($SUPPLIERIDS);
    $pin=$myuser[0]['idno'];
  

							}else {
  	  $pin = "n/a";

								}   
						   
						   
				
				  
				  
				  
					if(($SUPPLIERIDS!="")&&($REFNO!="")){
						
				
        $fromdate = date("Y-m-d H:i:s", strtotime($emapData['D']));
                   
						
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
                               'userid'=>$userid,
							     'supplier' => $emapData['A'],
                                 'ordernumber' => $emapData['B'],
 							      'invoice' => $emapData['C'],
								 
								 'fromdate' => $fromdate,
									 'branchid' => $branchid,  

						    'branchto' => $emapData['E'], 
							'companyid' => $companyid,
								'description' => $emapData['F'],
									  	'status'=>$paymenttype,
									'createdate'=>$dateposted,
							'approvalstatus'=>"Approved",

									'pin'=>$pin,
 									  'vatrate' => $vatrate, 
 									
                                );
                    
        
	
	
	
	   $i++;
	
                   	} 

              							$usr_result = $this->usermodel->add($mydata,'purchaseorder');

					}               

                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Purchases data!</div>');
								
								 redirect('user/viewpurchases');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Purchases were not uploaded..Try again</div>');
								
								 redirect('user/viewpurchases');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


	
	
	
	
public function uploadexpenses()
        {

          if(isset($_POST["uploadnewexpenses"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				 	 
		
		
		   $currenttime = date('Y-m-d H:i:sa');
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	   $vatrate=$configuration[0]['tax1rate'];
	  	  $type = $this->input->post("type");

	  
	  $dateposted = date('Y-m-d H:i:s');
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
											$paymenttype = trim($this->input->post("paymenttype"));

     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				    $SUPPLIERIDS = $emapData['A'];
					$REFNO = $emapData['C'];
				  					   
					
							 if($SUPPLIERIDS !=""){
								 
								 
								 $myuser=$this->usermodel->geteuser($SUPPLIERIDS);
    $pin=$myuser[0]['idno'];
  

							}else {
  	  $pin = "n/a";

								}   
						   
					


	
 

		
				  
				  	 $finalsalesid = $userid.time()+$i;

				  
					if(($SUPPLIERIDS!="")&&($REFNO!="")){
						
$Sorteddate = str_replace('/', '-', $emapData['F'] );
$fromdate = date("Y-m-d H:i:s", strtotime($Sorteddate));                   
					
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
                               'userid'=>$emapData['K'],
							     'supplier' => $emapData['A'],
                                 'idno' => $emapData['B'],
 							      'bankname' => $emapData['C'],
								   'amount' => $emapData['D'],
								  'dateposted' => $dateposted,
								'invoice' => $finalsalesid,
								  'type' => $type,
								 'datespent' => $fromdate,
									 'branchid' => $emapData['J'], 

						    'user' => $emapData['E'], 
							'companyid' => $companyid,
								'controller' => $emapData['G'],
									'description' => $emapData['H'],
									  	'status'=>$emapData['I'],
		
 									
                                );
                    
        
	
	
	
	   $i++;
	
                   	} 
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					

              							$usr_result = $this->usermodel->add($mydata,'expenses');
										
										
										
										
										
										
										
										
												
									if($emapData['L'] !=""){
										
$debitdata=array( 'userid'=>$emapData['K'],'account'=>$emapData['L'],'debit'=>$emapData['D'],'description'=>$emapData['H'],'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $emapData['J'],'companyid'=> $companyid,'transactioncode'=> $emapData['B'],'supplier'=>$emapData['A']);


$creditdata=array( 'userid'=>$emapData['K'],'account'=>$emapData['C'],'credit'=>$emapData['D'],'description'=>$emapData['H'],'code'=>$finalsalesid,'crateddate'=>$fromdate,'branch' => $emapData['J'],'companyid'=> $companyid,'transactioncode'=>  $emapData['B'],'supplier'=>$emapData['A']);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
									}
				
										
										
										
										
										
										
										
										
										
										
										
										

					}               

                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded expenses data!</div>');
								
								 redirect('user/viewexpenses');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Expenses were not uploaded..Try again</div>');
								
								 redirect('user/viewexpenses');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Something went wrong. Expenses were not uploaded..Try again</div>');
								
								 redirect('user/viewexpenses');	
				
				
			}
        }


	
	
	
	
	
	
	
	
	
	
	
public function uploadmembers()
        {

          if(isset($_POST["btn_uploadmembers"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:sa');
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

      $dublicate=$configuration[0]["dublicate"];
	
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				    $myname = $emapData['B'];
					$myphone = $emapData['D'];
					if(($myname!="")&&($myphone!="")){
						
				
                
                //  $inserdata[$i]['org_name'] = $emapData['A'];
                 // $inserdata[$i]['org_code'] = $emapData['B'];
                 // $inserdata[$i]['gst_no'] = $emapData['C'];
                 // $inserdata[$i]['org_type'] = $emapData['D'];
                  //$inserdata[$i]['Address'] = $emapData['E'];
               
                   
							$group="";
							  if($emapData['K']==""){
							$group="member";

							  }else{
							$group=$emapData['K'];

							  }
	  
						  $phone=($emapData['D']);
						$categoryid=($emapData['I']);
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
                               
                                 'firstname' => $emapData['B'],
 							      'lastname' => $emapData['C'],

 									'phone' => $emapData['D'],
									'email' => $emapData['E'],
									'idnumber' => $emapData['F'],
									'idno' => $emapData['G'],
									'gender' => $emapData['H'],
									'company' => $emapData['J'],
									'kra' => $emapData['L'],
									'nssf' => $emapData['M'],
									'nhif' => $emapData['N'],
									
									
									
									
									
									'bankcode' => $emapData['O'],
									'branchcode' => $emapData['P'],
									'bankaccount' => $emapData['Q'],
									'salary' => $emapData['R'],

									
									
									
									'category' => $group,
									'userid' => $userid,
 									'companyid' => $companyid,
									 'createdate' => $currenttime,
									 'group' => $categoryid,
									 'address_1' => $emapData['S'],
									 'savedpoints' => $emapData['T'],

									 

 									
 									
                                );
                    
                        $usr_result = $this->usermodel->uploadmembers($mydata,$dublicate);
							if ($usr_result ==TRUE) //active user record is present
							{						
   if($phone!="" || $categoryid!=""){
	   $mymember = $this->usermodel->getmymemberid($phone,$companyid);
     
   $memberid=$mymember[0]['id'];
   
   					 
	
       $data = array(
	   	'userid'=>$userid,
			'status'=>'1',
		  	'categoryid'=>$categoryid,
			'createdate'=>$new_date,
			
			'companyid'=>$companyid,
		'memberid' =>$memberid,
             );
							}
	$myusr_result = $this->usermodel->uploadallgroupmembers($data);
	
	}
	
	
	
	
	
	
	   $i++;
	
                   	}  }               
              
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Member data!</div>');
								
								 redirect('user/viewmember');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some Contacts might have been added since they already exist or No data was saved.Try again</div>');
								
								 redirect('user/viewmember');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


public function uploadmembers2()
        {

          if(isset($_POST["btn_uploadmembers"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		
		
					   	if($companyid==2){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not upload bulk /group contacts/members because you have note subcribe to unlimited/premium account. You are still using test account . You can contact us through :0780655987 or info@robisearch.com for full/unlimited (premium) account setup to enjoy more Services</div>');
							
								 redirect('user/viewmember');
								 return false;
								 
		}
			
		
		
		
		
		
		
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						  $group="";
							  if($emapData[7]==""){
							$group="member";

							  }else{
							$group=$emapData[7];

							  }
						  $new_date=	date('Y-m-d');
                            $data = array(
                            
                               
                                 'firstname' => $emapData[1],
 							       'lastname' => $emapData[2],

 									'phone' => $emapData[3],
									'email' => $emapData[4],
									'country' => $emapData[5],
									'idno' => $emapData[6],
									'gender' => $emapData[7],
									'category' => $group,
									'userid' => $userid,
 									'companyid' => $companyid,
 									
 									
                                );
                    
                        $usr_result = $this->usermodel->uploadmembers($data);
                     }
					
                    fclose($file);
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Member data!</div>');
								
								 redirect('user/viewmember');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
							}

                  }
            }
        }
	
	
	
	
	
	
	
	
	
	 public function editsale() {
 
 
							 
						
   $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $productdiscountaction=$this->usermodel->populatuserpermissionsdataarray('sales','productdiscount',$userid);
	 
			$salebelowsprice=$this->usermodel->populatuserpermissionsdataarray('sales','salesbeyondbprice',$userid);
			$salebelowbprice=$this->usermodel->populatuserpermissionsdataarray('sales','salebelowbprice',$userid);

									 // var_dump($salebelowsprice);
									 // exit;
							 
							 
							 
							 							 $message = $this->input->post("message");

							 
							 
							  $latest = $this->input->post("myqty");
							 
							
							 									// $vat = $this->input->post("vat");

							 
							 $taxindicator = $this->input->post("taxindicator");

														 $discounttype = $this->input->post("discounttype");

							  $discount = 0;
							 $finalvat = 0;
							  $mydiscount = $this->input->post("discount");

							  $type = $this->input->post("type");
							  $sprice = $this->input->post("sprice");
		 		 $view = $this->input->post("view");
		 		 $uom = $this->input->post("uom");
				  $uomqty = $this->input->post("uomqty");
				  $taxtype =trim($this->input->post("taxtype"));

		 		 $transactionid = $this->input->post("myid");
				 $myinvoice = $this->input->post("myinvoice");
$data['salesid'] = $myinvoice;

	$finaluomprice=0; 
		$finaluomqty=0;
		$ttoldqty=0;





		
		
		
			  
	  if($myproducts=$this->usermodel->getesoldproductraw($transactionid)){
		//$myproducts=$this->usermodel->getesoldproductraw($transactionid);
		  
	  }else{
		  	 
		$myproducts=$this->usermodel->getesoldproduct($transactionid);

		  
		  }
	  
		
		
	
		
		
		
		
		//
		
		$mysprice=$myproducts[0]['sprice'];
		$salestype=$myproducts[0]['salestype'];
				$latestuom=$myproducts[0]['uom'];
$oldmessage=$myproducts[0]['address'];
		$mycode=$myproducts[0]['code'];
			$mybranch=$myproducts[0]['branch'];
		$oldqty=$myproducts[0]['qty'];
		
			$oldtaxindicator=$myproducts[0]['taxindicator'];
			$tax=$myproducts[0]['tax'];
			$tax2=$myproducts[0]['tax2'];
			$vattype=$myproducts[0]['vattype'];
						$discount=$myproducts[0]['discount'];
						$myinvoice=$myproducts[0]['myinvoice'];

			$taxable=$myproducts[0]['taxable'];
//$taxtype=$myproducts[0]['taxtype'];
$oldtaxtype=trim($myproducts[0]['taxtype']);

						  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

			
				
				
				 
				
				
				
			
			
		
		if(($oldqty==$latest) &&($sprice==$mysprice)&& ($taxindicator==$oldtaxindicator)  &&($uom==$latestuom)  &&($message==$oldmessage) && ($mydiscount==$olddiscount) && ($taxtype==$oldtaxtype))  {
			
		
							redirect($view ,$data);
								return false;
		}
		
		if(($latest==0) ||($latest=="")) {
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Quantity can not be 0 or null  </div>');
								redirect($view ,$data);
		
								

								return false;
		}
		
		
	
			if($uom!=$latestuom)  {
			
			$productname = $this->usermodel->populatealldataarray('uomproducts','code', $mycode,'uom', $uom);
		
		$finaluomprice=$productname[0]['price'];
		$finaluomqty=$productname[0]['qty'];
				$sprice=$this->formatMoney(($finaluomprice /$finaluomqty), true);
$finallatest=$latest*$finaluomqty;
$latest=$latest*$finaluomqty;


		}else{
					//$amount=(($sprice)* ($latest))-$discount;
	
								$finallatest=$latest;

		}
		
		
		
		
	
			
		
					 $productname = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $mybranch);

		 $productname[0]['qty'];
	
		
		$oldsellingprice=$productname[0]['sellingprice']; 
		
				$oldbuyingprice=$productname[0]['buyingprice']; 
								$currentoldqty=$productname[0]['qty']; 

					
			  $inventorytype=trim($productname[0]['producttype']); 
			      $tax_included=trim($productname[0]['tax_included']);
	    $tax_vattype=trim($productname[0]['vattype']);
			  
			  
			  
			  
			  
			    if($taxindicator=="yes"){
					   
				   
					   if(($tax_included !="")|| ($tax_included !=0)){
					   
					   
		if(($oldtaxtype=="Inclusive")&& ($taxtype=="Exclusive")){
				

				$mytaxx=1+($tax_included/100);
				 $sprice=($sprice*$mytaxx);
								
						
								
			
			
			
		}
						   
		if(($oldtaxtype=="Exclusive")&& ($taxtype=="Inclusive")){
				
		 $mytaxx=1+($tax_included/100); 
			 $sprice=($sprice/$mytaxx);
			
			
			
			
		}
		if(($oldtaxtype=="Exclusive")&& ($taxtype=="Exclusive")){
				
		 $mytaxx=1+($tax_included/100); 
			 $sprice=($sprice*$mytaxx);
			
			
			
			
		}
		
				   }
				   }	
				
			  
	
			    

			  
if( $inventorytype=="Inventory"){



	$ttoldqty=$currentoldqty+$oldqty;
   if($ttoldqty < $latest ){
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$currentoldqty.') is less than what you want sell('.$latest.').  Try again.</div>');
			   //if($currentoldqty<$latest ){
			  
						  
						  
						  
								
								redirect($view ,$data);
	   return false;
   }
	}

		if(($sprice<$oldsellingprice) && ($productdiscountaction==false)) {
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set selling price('.$oldsellingprice.'). Try again </div>');
								redirect($view ,$data);
		
		
		
								//

								return false;
		}
		if(($sprice<$oldsellingprice) && ($salebelowsprice==false)) {
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set selling price and you do not have the right. Try again </div>');
								redirect($view ,$data);
		
								

								return false;
		}
		
		
		
		
			if(($sprice<$oldbuyingprice) && ($salebelowbprice==false)) {
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set buying price and you do not have the right. Try again </div>');
								redirect($view ,$data);
		
								

								return false;
		}
		
		
	if($mydiscount!=$olddiscount){
		
if($discounttype ==""){
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>You must select Discount type first e.g Amount or Parcentage then  try edit discount again .</div>');
			
			  
						  
						  
						  
								
						redirect($view ,$data);
	   return false;
   }	 
					  }	
		
	if($mydiscount!=$olddiscount){
		
				if($discounttype=="PC"){
			$mydiscountMain=(($sprice* ($mydiscount/100))   * $latest  );
			$discount= $this->formatMoney($mydiscountMain, true);			
				$mydiscountMainNow=(($sprice* ($mydiscount/100)));	
			
							$sprice=$this->formatMoney(($sprice-$mydiscountMainNow), true);
			}else{
				$mydiscountMain=($mydiscount * $latest);	
				$discount= $this->formatMoney($mydiscountMain, true);
				$sprice=$this->formatMoney(($sprice-$mydiscount), true);

			}
			
		
		}

		
	
		
	
			$answere=$latest-$oldqty;
		$remainingqty=$oldqty-$answere;
		
		 //$productname = $this->usermodel->geteproductbyid($mycode);
			
			
			
	//echo"---".$finaluomprice;		

						
//exit;
			
			
    
   $olduomqty=$productname[0]['uom'];
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$oldqty);
   	//$answere=$latest-$oldqty;
	   	$answere=$finallatest-$oldqty;

		$remainingqty=$availableqty-$answere;
		///
		
		

		

	if($uom != $latestuom)  {
		

					  if($ttoldqty <  $finallatest ){
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$currentoldqty.') is less than what you want sell('.$answere.').  Try again.</div>');
			   //if($currentoldqty<$latest ){
			  
						  
						  
						  
								
						redirect($view ,$data);
	   return false;
   }	 
					  }	





if(($oldqty !=$latest) ||($sprice !=$mysprice)|| ($taxindicator !=$oldtaxindicator) || ($uom!=$latestuom)||($mydiscount!=$olddiscount)|| ($message !=$oldmessage) || ($taxtype!=$oldtaxtype))  {
			
			if($mydiscount!=$olddiscount){
						$amount=(($sprice) * $latest);

			}else{
					$amount=(($sprice)* ($latest))-$discount;
	
				
			}
//$sprice=$sprice-$discount;
	
						
		}
		

		
		
		
		
		
		
		
		
		/*
	if($uom!=$latestuom)  {
									//$amount=(($finaluomprice)* ($latest))-$discount;

							
							//$amount=(($finaluomprice)* ($latest*$finaluomqty));
			$sprice=$this->formatMoney(($finaluomprice /$finaluomqty), true);
$amount=(($sprice)* ($latest));
			//$sprice=$this->formatMoney(($finaluomprice), true);

					$finallatest=$latest*$finaluomqty;
		}
		
*/
















								 $amount=$this->MyformatMoney(($amount), true);
			
						   if ($taxindicator=="no"){
							   
							   	 $finaltax = 0.00;
	
							   	 $finaltax2 = 0.00;
								$vattype = "EXEMPTED";
	 						$taxable = 0.00;
							   
							   
						   }else{
							   
							   
						if(($oldqty==$latest) &&($sprice==$mysprice)&& ($taxindicator==$oldtaxindicator)  &&($uom==$latestuom)  &&($message==$oldmessage) &&($uomqty==$olduomqty))  {
			   
						 
											 $finaltax = $tax;
											  $finaltax2 = $tax2;
												$vattype = $vattype;
												$taxable =$taxable;


										}else{
											
												    $tax_vattype=trim($productname[0]['vattype']);

											 if ($tax_vattype !="VATABLE"){
							   
						
							
								$finaltax=0;
							 $finaltax2=0;
							 $vattype = $tax_vattype;
	 						$taxable = $sprice*$finallatest;
							$vatable=$taxable;
							
							
							
							
							
							
							
							
//
						   }else{
							   
										
							
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								  $finaltax2=0;
								$vattype = $tax_vattype;
	 						$taxable = 0.00;
							 }else{
								
								
								
								
								
								
								
								
								 //
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 //$vatable=($sprice  * $finallatest);	
								 
							
				if(($oldtaxtype=="Inclusive")&& ($taxtype=="Exclusive")){
					$vatable=($sprice/$mytax);				
			


				}else if (($oldtaxtype=="Exclusive")&& ($taxtype=="Exclusive")){
	
								
						$vatable=($sprice/$mytax);
					 
			
			
				}
								
								
								
						
								 
								 
								 
								 
								 
								 
								 
								 
								 
								//$getvatable=($sprice);	
								// $getvatable=($sprice*$mytax);	
								// $finaltax=(($getvatable-$sprice)*$finallatest);
						
						$finaltax=(($sprice-$vatable)*$finallatest);
							
								// $sprice= $this->formatMoney($getvatable, true);

									}else{
	
								 $mytax=1+($tax_included/100); 
								  $vatable=(($sprice/$mytax) *$finallatest );
								   $finaltax=(($sprice*$finallatest)-$vatable);

									}
								 
							
								 
								 
								//$vattype = $tax_vattype;

								// $mytax=1+($tax_included/100); 
								// $vatable=($sprice/$mytax);
								
								
								 //$myfinaltax=(($sprice-$vatable)*$latest);

								
								
								
								
								//$finaltax= $this->formatMoney($finaltax, true);
							$finalvat = $finaltax;
							
							$taxable=$vatable;
							$display2=$myconfiguration[0]["display2"]; 

	if($display2=="yes"){

	

$tax2rate=$myconfiguration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sprice*$finallatest)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	 $vatable= $this->formatMoney($ttoltaxable, true);





	}else{
	
		//$taxable= $this->formatMoney($vatable, true);
$finaltax=$finaltax;
$vatable=$vatable;
 $finaltax2=0;
	}
					


			

							 }
											}
										}
										}
		
			
	
	////
				
		$finalmessage='';

	if($uom!=$latestuom)  {

if($message !=''){
$finalmessage=round($latest)." ".$uom;
}else{
$finalmessage=$message.round($latest)." ".$uom;


}	
	}else{
	$finalmessage=$message;
	
		
	}
















	
   	$salesdata=array(		
	
	
		
				//'stockbefore' => $available, 
							'stockafter' => $remainingqty, 
	
	
	
													'qty'=>$finallatest,
													'discount'=>$discount,
													'taxtype'=>$taxtype,

												//'qty'=>$latest,
												'uomqty'=>$uomqty,
													'amount'=>$amount,
														'address'=>$finalmessage,
											'tax' => ($this->formatMoney($finaltax , true)),
											'tax2' => $finaltax2,
														'taxindicator'=>$taxindicator,
													'vattype'=>$vattype,
													'taxable'=>($this->formatMoney($vatable , true)),
													'sprice'=>$sprice,
												'uom'=>$uom,

													);
			//
			
	
				  $myusr_result ="";
	  if($this->usermodel->updatesalesorderraw($salesdata,$transactionid)){
		  $myusr_result =TRUE; 
		  
	  }else{
		  	  if($this->usermodel->updatesalesorder($salesdata,$transactionid)){
				 $myusr_result =TRUE;   
				  
			  }else{
				  
				 $myusr_result =false;   
			  }

		  
		  }

							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							$productdatastocks=array(		
												'qty'=>$remainingqty,
												'sellingprice'=>$sprice,
													);

	 
								$productdata=array(		
												'qty'=>$remainingqty,
													);
							$this->usermodel->updatedata($productdatastocks,'newstock','invoice',$myinvoice);

								 //$this->usermodel->updateproduct($productdatastocks,$myinvoice); 
									 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$mybranch);

								
								
						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully </div>');
								//redirect('user/viewsales',$data);
					
															redirect($view ,$data);

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not Updated  </div>');
				
										redirect($view ,$data);
			
							
							}
  
  
  
  
  
  
  
  
  
  
  
  
	}
	
	
	public function editreceivedproducts() {
 
   if (!$this->input->post('btn_editreceivedproduct') == "myedit"){
			
		
					   
      show_error('No identifier provided', 500);
    }
    else {
		
		
					   	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	
	$userid=$data['id'] ;
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
		$buyingprice=0;
		$latest=0;
							 $mylatest = trim($this->input->post("myqty"));
							  $myid = trim($this->input->post("myid"));
						

						$mybuyingprice = trim($this->input->post("buyingprice"));
							$sellingprice = trim($this->input->post("sellingprice"));
		 		 $transactionid = trim($this->input->post("itemid"));
				
				
						 		 $mybranch = trim($this->input->post("branch"));

				 $invoice_number = trim($this->input->post("salesid"));

				 				 $compare = trim($this->input->post("compare"));
								 				 				 $tax = trim($this->input->post("tax"));
																 
										
						 		 $enddate = trim($this->input->post("enddate"));
						 		 $batchno = trim($this->input->post("batchno"));
//
//
//
							 $discount = trim($this->input->post("discount"));
							 
																 
						 		 $uomqty = trim($this->input->post("uomqty"));
								 
				// $uom = trim($this->input->post("uom"));	


		
	$myuom = explode(':',$this->input->post("uom"));

   $uom = trim(($myuom[0]));
   $mymainuom = explode('=',$myuom[1]);
   $correctqty = trim(($mymainuom[0]));
  $mybprice = trim(($mymainuom[1]));


  if ($mylatest < 0)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not receive or adjust any purchase to negative(-) stock. Try again.</div>');

						  
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   return false;
						   }


 				
												 

$finalybuyingprice=0;

		
$myfinalybuyingprice=0;

					$myreceivedproducts=$this->usermodel->geteeceivedproduct($myid);
			
			$totalqty=$myreceivedproducts[0]['total'];
			$oldtax=$myreceivedproducts[0]['tax'];


			$mycode=$myreceivedproducts[0]['item_id'];
			
			$oldsellingprice=$myreceivedproducts[0]['sellingprice'];
			$oldbuyingprice=$myreceivedproducts[0]['buyingprice'];
			$olddiscount=$myreceivedproducts[0]['discount'];

	
					  	if(((double)$mybprice!=0) && ((double)$correctqty!=0)){
				//echo "iko sawa";
				
				$latest=(double)$uomqty*(double)$correctqty ;
				
				
			
			$buyingprice= $this->MyformatMoney(((double)$mybprice/(double)$correctqty), true);
			}else{
								//echo "iko mbaya";
			

	
	$latest=$mylatest;
		$buyingprice=(double)$mybuyingprice;
				
			}
	
				$branch=$myreceivedproducts[0]['type'];
				if($mybranch=="Main"){
											 $myproducts = $this->usermodel->populateallarray('products','code', $mycode);

				}else{
										 $myproducts = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);
	
				}

		$mybuyingprice=$myproducts[0]['buyingprice'];
		$mysellingprice=$myproducts[0]['sellingprice'];
		 $availableqty=$myproducts[0]['qty'];
	
		$oldqty=$myreceivedproducts[0]['total'];

				$oldbatchno=$myreceivedproducts[0]['batchno'];

		$oldenddate=$myreceivedproducts[0]['enddate'];






if($this->input->post('btn_editreceivedproduct') == "assignitems") {
				
					if( $mybranch=="Main"){
											 $myproducts1 = $this->usermodel->populateallarray('products','code', $transactionid);

				}else{
										 $myproducts1 = $this->usermodel->populatealldataarray('productlist','code', $transactionid,'branch', $branch);
	
				}

				
						$mysellingprice=$myproducts1[0]['sellingprice'];

				
				
						 $myavailableqty=$myproducts1[0]['qty'];

				
				 $myavailableqty=$myproducts1[0]['qty'];
				  $myfinalqty=((double)$totalqty+(double)$myavailableqty);


		

			$qtyDATAs=array(		
			

										
																  
									'itemstatus' => "etimsready", 
									'item_id'=>$transactionid,
										'sellingprice'=>$mysellingprice,

									'balance' => $myfinalqty, 
										);
										
										
			$usr_result=$this->usermodel->updateReceivings($qtyDATAs,$myid); 

		
				$newqtyDATA=array(		
						
										'qty'=>$myfinalqty,
										);
		
			if( $mybranch=="Main"){
					$usr_result = $this->usermodel->updatedata($newqtyDATA,'products','code',$transactionid);

				}else{
		$usr_result = $this->usermodel->updatedatabytwo($newqtyDATA,'productlist','code',$transactionid,'branch',$branch);
	
					
				}
			
		
		
		
		
		
		
		
		
						 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong>Items assigned  successfully </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
					



			}






						 
						if(($compare=="Yes")||($compare=="Direct")) {
							
							
					$myfinalybuyingprice=((double)$mybuyingprice+(double)$buyingprice)/2;
					
$firtst=((double)$mybuyingprice*((double)$availableqty-(double)$latest));
$second=((double)$buyingprice*(double)$latest);
					$averageprice=((double)$firtst+(double)$second)/((double)$availableqty);
					
					
					$finalybuyingprice= $this->MyformatMoney($averageprice, true);

					//echo $averageprice."iko";
					
					//exit;
					
						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
	
		if($compare=="Direct"){
			$finalybuyingprice=$buyingprice;
	
			
		}
		
		$answere=(double)$availableqty-(double)$oldqty;
		
		
		if($buyingprice!=$mybuyingprice){
			$buyingpriceDATA=array(		
						
										'buyingprice'=>$finalybuyingprice,
									
										);
$usr_result=$this->usermodel->updateReceivings($buyingpriceDATA,$myid); 
$this->usermodel->updatedata($buyingpriceDATA,'products','code',$mycode);
	
		 $this->usermodel->updatedatabytwo($buyingpriceDATA,'productlist','code',$mycode,'branch',$branch);
	
	
	
	$confirmuomproducts = $this->usermodel->populatealldataarray('uomproducts','uom', $mycode,'companyid', $companyid);
if($confirmuomproducts !=false){
	
	$uomfinalprice=((double)$finalybuyingprice * (double)$confirmuomproducts[0]['qty']);

	$buyingpriceDATAUOM=array(		
						
										'brice'=>$uomfinalprice,
									
										);


		$this->usermodel->updatedatabytwo($buyingpriceDATAUOM,'uomproducts','uom',$mycode,'companyid',$companyid);

}
	
	
	
							// $this->usermodel->updateproductlist($buyingpriceDATA,$mycode,$branch); 

	
		}
			if($sellingprice!=$mysellingprice){
			$sellingpriceDATA=array(		
			'sellingprice'=>$sellingprice,
													);
	//$usr_result=$this->usermodel->updateproductbyid($sellingpriceDATA,$transactionid); 
							// $this->usermodel->updateproductlist($sellingpriceDATA,$mycode,$branch); 
							 	//	$usr_result = $this->usermodel->updatedatabytwo($sellingpriceDATA,'productlist','code',$mycode,'branch',$branch);

		//$usr_result = $this->usermodel->updatedata($sellingpriceDATA,'products','code',$mycode);



		}//
		
 $finalqty=((double)$latest+(double)$answere);
		
	if( ($oldqty!=$latest) ||($batchno!=$oldbatchno) || ($enddate!=$oldenddate) || ($oldtax!=$tax) || ($oldbuyingprice!=$buyingprice)|| ($sellingprice!=$oldsellingprice) || ($discount!=$olddiscount) ||($transactionid != $mycode)) {
			
			
			
		
			
			
			
			$qtyDATA=array(		
								'tax'=>$tax,
										'sellingprice'=>$sellingprice,
										'buyingprice'=>$buyingprice,
	'uomqty'=>$uomqty,
		'uom'=>$uom,
										'total'=>$latest,
										'enddate'=>$enddate,
										'discount'=>$discount,

										'batchno'=>$batchno,
										//'item_id'=>$transactionid,

																  

									'balance' => $finalqty, 
										);
										
										
			$usr_result=$this->usermodel->updateReceivings($qtyDATA,$myid); 
			
				
			
			
									$newqtyDATA=array(		
										'expdate'=>$enddate,

										'qty'=>$finalqty,
										);
			
			//$usr_result=$this->usermodel->updateproductbyid($newqtyDATA,$transactionid); 
							// $this->usermodel->updateproductlist($newqtyDATA,$mycode,$branch); 

				if( $mybranch=="Main"){
					$usr_result = $this->usermodel->updatedata($newqtyDATA,'products','code',$mycode);

				}else{
		$usr_result = $this->usermodel->updatedatabytwo($newqtyDATA,'productlist','code',$mycode,'branch',$branch);
	
					
				}
			
			
			
			
		}
	
		

	//$usr_result = $this->usermodel->updateproduct($PRODUCTDATA,$mycode); 
	
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								


	 
								$productdata=array(		
												'qty'=>$remainingqty,
													);
								
								
								
								
						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not Updated  </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							
							}
  
  
  
  
  
  
  
  
  
  
  
  }
	}
	
	public function updatesalesorder() {
 
 
					   	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	
	$userid=$data['id'] ;
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
			
		
					   
     
							 $view = trim($this->input->post("view"));
						$finalsalesid = trim($this->input->post("finalsalesid"));

						
							  $myid = trim($this->input->post("myid"));
							  
							  
					  						$serial = trim($this->input->post("serial"));

							  
							  
						$description = trim($this->input->post("description"));
						$oldamount = trim($this->input->post("oldamount"));

							  


						$buyingprice = trim($this->input->post("buyingprice"));
							$sellingprice = trim($this->input->post("sellingprice"));
		 		 $wholesaleprice = trim($this->input->post("wholesaleprice"));
															 $sales = trim($this->input->post("sales"));
													

											 $branch = trim($this->input->post("branch"));
											 
											 
											 
											 $qty = trim($this->input->post("qty"));
											 
											 
										

				 $code = trim($this->input->post("code"));
				 				 $vattype = trim($this->input->post("vattype"));

				 
				 						  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 
				 				  
		$myproducts=$this->usermodel->getesoldproduct($myid);
		$mysprice=$myproducts[0]['sprice'];
		$salestype=$myproducts[0]['salestype'];
				$latestuom=$myproducts[0]['uom'];
								$taxtype=$myproducts[0]['taxtype'];

$oldmessage=$myproducts[0]['address'];
		$mycode=$myproducts[0]['code'];
			$mybranch=$myproducts[0]['branch'];
		$oldqty=$myproducts[0]['sales'];
					$olddescription=$myproducts[0]['vattype'];

			$oldtaxindicator=$myproducts[0]['vattype'];
			$tax=$myproducts[0]['tax'];
						$tax2=$myproducts[0]['tax2'];


										        $productname = $this->usermodel->geteproductlistbyid($code,$branch);

			
				
			
	
			
		
		if(($oldqty==$qty) &&($sellingprice==$mysprice)&& ($vattype==$oldtaxindicator) && ($description==$olddescription))  {
			
		
							 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  there is no any change done by you. Try again </div>');
							redirect($view);
								return false;
		}
							  
					
				 


							
						
							 
							 $tax_included=trim($productname[0]['tax_included']);
								 $tax_vattype=trim($productname[0]['vattype']);

						 	 $finalvat = 0.00;
							 $finaltax2 = 0.00;
						
	 						$taxable = 0.00;
							
							
						   if ($vattype!="VATABLE"){
							   
							$finalvat = 0.00;
							 $finaltax2 = 0.00;
							$vattype =$vattype;
	 						$taxable = 0.00;
							  
						   }else{
							 
						 
						
								
				
							 if(($tax_included=="")|| ($tax_included==0)){
								$finalvat = 0.00;
							$finaltax2 = 0.00;
							$vattype =$vattype;
	 						$taxable = 0.00;
									
							 }else{
								 
								 
								 
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 $vatable=($sellingprice);	

								  $getvatable=($sellingprice*$mytax);	
								 $myfinaltax=(($getvatable-$sellingprice)*$sales);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{

								 $mytax=1+($tax_included/100); 
								  $vatable=($sellingprice/$mytax);
								   $myfinaltax=(($sellingprice-$vatable)*$sales);

									}
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								// $mytax=1+($tax_included/100); 
								 //$vatable=($sellingprice/$mytax);
								
								
								 //$myfinaltax=(($sellingprice-$vatable)*$sales);

								
								
								$taxable =$this->formatMoney(($vatable*$sales), true);
 
				
	
								
								$finaltax= $this->formatMoney($myfinaltax, true);
							$finalvat = $finaltax;
						$display2=$myconfiguration[0]["display2"]; 
 
	
	if($display2=="yes"){

	
	
$tax2rate=$myconfiguration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$sales)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$taxable= $this->formatMoney($ttoltaxable, true);

	
	
	
	
	
	}else{
	 $finaltax2=0;
		$taxable= $this->formatMoney(($vatable*$sales), true);
	  $finalvat = $finaltax;
	


	}
							

							 }

										
	}
				 
				 
			 
				 											 $amount=$sales*$sellingprice;

				 
				 
			$originalamount = $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);

				 $currentamount=trim($originalamount[0]['amount']);

 
$finalamount=$currentamount+$amount-$oldamount;



				
								$salesorderlist=array(		
												'bprice'=>$buyingprice,
											'sprice'=>$sellingprice,
												'code'=>$code,
						'serial'=>$serial,

												'qty'=>$qty,
												'sales'=>$sales,
												'tax'=>$finalvat,
			'description'=>$description,

						'tax2'=>$finaltax2,

											'vattype'=>$vattype,
											'taxable'=>$taxable,

												'amount'=>$amount,
													);
		
											
											
																		$usr_result = $this->usermodel->updatedata($salesorderlist,'sales_order','id',$myid);
	

					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'purchaseorder','invoice',$finalsalesid);

								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery done. try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  

    
	}
	
	
	
	
	public function updatestocktaking() {
 
  if ($this->input->post('btn_updatestocktaking') == "stocktaking")
					   {
			
		
					   	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	
	$userid=$data['id'] ;
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		
		  $mydate=date("Y-m-d H:i:s");
		  
	
		  							 $mybranch = trim($this->input->post("mybranch"));

     
							 $view = trim($this->input->post("view"));
							 						$code = trim($this->input->post("code"));

						
							  $myid = trim($this->input->post("myid"));
							
														  $description = trim($this->input->post("description"));

						$buyingprice = trim($this->input->post("buyingprice"));

						$open = trim($this->input->post("open"));
							$branchid = trim($this->input->post("branchid"));
		 		 $added = trim($this->input->post("added"));
				 		 $department = trim($this->input->post("department"));
				 		 $sellingprice = trim($this->input->post("sellingprice"));

															 $sales = trim($this->input->post("sales"));

											 $startdate = trim($this->input->post("startdate"));
											
											 
											 $balance = $added-$open;
											 
								$salesorderlist=array(		
									'description'=>$description,

												'added'=>$added,
											'balance'=>$balance,
													'updatedby'=>$userid,
													'closedate'=>$postedtime,
													);
		
								$productdata=array(		
												'qty'=>$added,
								'sellingprice'=>$sellingprice,
								'buyingprice'=>$buyingprice,
									'status'=>"active",
												
													);
											
										$usr_result = $this->usermodel->updatedata($salesorderlist,'stocktaking','id',$myid);



	 $insertstockdata	=array(		
			'total'=>$added,
			'date'=>$postedtime,
				//'name'=>$myname,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				//'description'=>$code,
				'stockfrom'=>$mybranch,
				'stockto'=>'Automatic Stock Taking',
				'type'=>$mybranch,
				'balance'=>$balance,
				'item_id1'=>$added,

				'description'=>$code,

								);
								


							
							if($mybranch=="all"){
								 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$code,'branch',$branchid);
									$this->usermodel->updatedatabytwo($productdata,'products','code',$code,'status<>','inactive');

							}else{
							if($mybranch==0){
												
									$this->usermodel->updatedatabytwo($productdata,'products','code',$code,'status<>','inactive');

											}else{
									///			
								$myusr_result = $this->usermodel->updatedatabytwo($productdata,'productlist','code',$code,'branch',$mybranch);

											}
							}
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							$this->usermodel->add($insertstockdata,'newstock');
									//$usr_result = $this->usermodel->updatedatabytwo($productdata,'productlist','code',$code,$branchid);

																//$this->usermodel->updatedatabytwo($productdata,'productlist','code',$code,'branch',$branchid);


									

	 
								
								
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
	
	
	
	
	
	public function updatepurchaseorder() {
 
  if ($this->input->post('btn_editpurchases') == "myeditpurchase")
					   {
			
		
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

							 $view = trim($this->input->post("view"));
							 
													 $code = trim($this->input->post("code"));

							  $myid = trim($this->input->post("myid"));
						$tax = trim($this->input->post("tax"));

						$buyingprice = trim($this->input->post("buyingprice"));
						$producttype = trim($this->input->post("producttype"));
												$description = trim($this->input->post("description"));


						
  	$enddate = trim($this->input->post("enddate"));
	  $batchno = trim($this->input->post("batchno"));

															 $total = trim($this->input->post("total"));

											 $branch = trim($this->input->post("branch"));
											 
											 
											 
											 $qty = trim($this->input->post("qty"));
									 $to = trim($this->input->post("to"));

											 
											 if($total>$qty){
												 
										$this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
										  <strong>Error!</strong> Delivered quantity cant not  be more than ordered quantity. Try again </div>');
											redirect($view);
												 
												 return false;
											 }

					$checkitem = $this->usermodel->populateallarray('newstock','id', $myid);
	$confirmtotal=$checkitem[0]['total'];

						
				 $amount=$qty*$buyingprice;
		
								$salesorderlist=array(		
												'buyingprice'=>$buyingprice,
											
													     'enddate' => $enddate, 
						'batchno' => $batchno,
																		'tax'=>$tax,
																														'description'=>$description,


												'qty'=>$qty,
												'total'=>$total,
												'amount'=>$amount,
													);
		
											
											
																		$usr_result = $this->usermodel->updatedata($salesorderlist,'newstock','id',$myid);
	

					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
								
								
								
								
								if($enddate !=""){
					
									$newqtyDATA=array(		
										'expdate'=>$enddate,

										);
	
	
	if( $to=="Main"){
					$usr_result = $this->usermodel->updatedata($newqtyDATA,'products','code',$code);

				}else{
		$usr_result = $this->usermodel->updatedatabytwo($newqtyDATA,'productlist','code',$code,'branch',$to);
	
					
				}		

								}				
								
								
								
								
								
								
								
								
								
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Data Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
	
	
	
	
	
	
	
	
     public function closepurchaseorder() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['randomitemidentifier'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['finalsalesid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['purchaseorder'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$stocks  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);



		   $allstock = array();
$finalamount=0;
$finalvat=0;
$finaltaxable=0;
	 if(is_array($stocks)) 

 {
	foreach ($stocks as $rowstocks){
		
		 $amount=($rowstocks->qty * $rowstocks->buyingprice);
		 
		 $finalamount=$finalamount + $amount;
		 $finaltaxable=$finaltaxable+$rowstocks->taxable;
			$ttqty=$ttqty + $rowstocks->total;

			$finalvat=$finalvat + $rowstocks->vat;
	
	}
  	
 }
		

				$amountdata=array(		
					'vat'=>$finalvat,
						'taxable'=>$finaltaxable,
							'qty'=>$ttqty,
												'amount'=>$finalamount,
													);
								
									$usr_result = $this->usermodel->updatedata($amountdata,'purchaseorder','invoice',$invoiceid);





		
											
	

					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
								
								
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Data Updated successfully. </div>');
							redirect("user/allpurchaseorder");						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect("user/allpurchaseorder");
							}
  
  








	
	
	}
  }
  
	
	
	
	
	public function editprices() {
 
   if (!$this->input->post('btn_editprice') == "editprice"){
			
		
					   
      show_error('No identifier provided', 500);
    }
    else {
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
 							 $updatetype = trim($this->input->post("updatetype"));
 							 $branchid = trim($this->input->post("branchid"));

							 $page = trim($this->input->post("page"));
							  $myid = trim($this->input->post("myid"));

						$buyingprice = trim($this->input->post("buyingprice"));
							$sellingprice = trim($this->input->post("sellingprice"));
		 		 $wholesaleprice = trim($this->input->post("wholesaleprice"));
															 $promoprice = trim($this->input->post("promoprice"));
		 		 $retailmargin = trim($this->input->post("retailmargin"));

											 $branch = trim($this->input->post("branch"));
											 $qty = trim($this->input->post("qty"));

				 $code = trim($this->input->post("code"));
				 $updateserial = trim($this->input->post("updateserial"));
$finalsprice=(($buyingprice* ($retailmargin/100))+ $buyingprice);
 $finalsprice=(round($finalsprice)) ;


	$serialdata=array(	
	
	'buyingprice'=>$buyingprice,
	'sellingprice'=>$sellingprice,
	);



				 	$allproducts=array(		
												'buyingprice'=>$buyingprice,
											'sellingprice'=>$sellingprice,
											'wholesaleprice'=>$wholesaleprice,
											'promoprice'=>$promoprice,
											'allow_alt_description'=>$retailmargin,

												'code'=>$code,

												
													);
		
								$productlist=array(		
												'buyingprice'=>$buyingprice,
											'allow_alt_description'=>$retailmargin,
											'promoprice'=>$promoprice,

											'sellingprice'=>$sellingprice,
											'wholesaleprice'=>$wholesaleprice,
												'code'=>$code,
												'qty'=>$qty,

												
													);
		
		
		
		
		
											if($updatetype=="all"){
												$usr_result = $this->usermodel->updatedata($allproducts,'products','code',$code);
											 $this->usermodel->updatedata($allproducts,'productlist','code',$code);
											$this->usermodel->updatedatabytwo($serialdata,'serials','code',$code,'status',"new");



											}else{

											
											
											
											if($branch=="Main Store"){
																			$usr_result = $this->usermodel->updatedata($productlist,'products','id',$myid);
																			$this->usermodel->updatedatabytwo($serialdata,'serials','code',$code,'status',"new",'branch',"Main");

											}else{
																		$usr_result = $this->usermodel->updatedata($productlist,'productlist','id',$myid);
																		$this->usermodel->updatedatabytwo($serialdata,'serials','code',$code,'status',"new",'branch',$branch);


	
											}
}

					
					
					
					
					
					
					
					
					
					



					if($updatetype=="spricemargin"){
							$spricemargin=array(		
												'buyingprice'=>$buyingprice,
											'allow_alt_description'=>$retailmargin,
											'promoprice'=>$promoprice,

											'sellingprice'=>$finalsprice,
											'wholesaleprice'=>$wholesaleprice,
												///'qty'=>$qty,

												
													);
													
													
	
	$usr_result=$this->usermodel->updatedata($spricemargin,'productlist','code',$code);
$usr_result=$this->usermodel->updatedata($spricemargin,'products','code',$code);

						
						
					}





					if($updatetype=="Production"){
				
						
						
						
																	
											if($branch=="Main Store"){
										$mainprductspercentage  = $this->usermodel->populatealldatanoarrayfour('uomproducts','branch', "	Main Store",'status',"child",'unitprice', "Yes",'code',$code);


											}else{
									$mainprductspercentage  = $this->usermodel->populatealldatanoarrayfour('uomproducts','branch', $branch,'status',"child",'unitprice', "Yes",'code',$code);


	
											}

						
					
						
						
		//$mainprductspercentage  = $this->usermodel->populatealldatanoarrayfour('uomproducts','branch', $branchid,'status',"child",'unitprice', "Yes",'code',$code);


if(is_array($mainprductspercentage)) {
	
	 foreach($mainprductspercentage as $rw)
   {
	  $uomidmain=trim($rw->id);
	
	
	 $mmybrice=0;

		$ttbbprice=0;
	
	
									
											if($branch=="Main Store"){
										$stocklist  = $this->usermodel->populatealldatanoarrayfour('uomproducts','branch',"Main Store",'status',"child",'unitprice<>', "Yes",'code',$code);


											}else{
									$stocklist  = $this->usermodel->populatealldatanoarrayfour('uomproducts','branch', $branchid,'status',"child",'unitprice', "Yes",'code',$code);


	
											}
	
	
		
if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	      $allbrice=trim($row->brice);
		  
	   $ttbbprice=$ttbbprice+$allbrice;

		

		
   }
  
   
    $mmybrice=$this->formatMoney((($rw->qty/100)*$ttbbprice),true);
   
	

	
						$productlistuoms=array(		
									'brice'=>$mmybrice,
									

												
												
													);
		
																		$usr_result = $this->usermodel->updatedata($productlistuoms,'uomproducts','id',$uomidmain);
 
	

}



	
}	
}
						
						
						
						
						
						
						
						
						
						
					
											if($branch=="Main Store"){
										$uomproducts = $this->usermodel->populatealldatanoarraythree('uomproducts','code', $code,'status',"child",'companyid',$companyid);


											}else{
	$uomproducts = $this->usermodel->populatealldatanoarraythree('uomproducts','code', $code,'status',"child",'branch',$branchid);


	
											}
			
						
						
						
		
		

$mytotalcost=0;
		$finalmainqty=0;
				$finalbuyingprices=0;
		$usr_result=false;

	if(is_array($uomproducts)){
	

$insertstockdata = array();
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	//$myproductlist = $this->usermodel->populatealldataarray('products','code', $uomcode,'companyid', $companyid);

	//$finalmainqty=$myproductlist[0]['qty']+$total;
$mytotal = $total*$c->brice;
//$availableuomqty=$myproductlist[0]['qty'];

	$finalbuyingprices=	$finalbuyingprices+$c->brice;


}


	$dataproductlist=array(	
												
	'buyingprice'=>$finalbuyingprices,
					

				);
				
				
				
				
							if($branch=="Main Store"){
				
$usr_result=$this->usermodel->updatedata($dataproductlist,'productlist','code',$code);
$usr_result=$this->usermodel->updatedata($dataproductlist,'products','code',$code);

											}else{
				
$usr_result=$this->usermodel->updatedata($dataproductlist,'productlist','code',$code);

	
											}
			
				
				
				
				
				
				
				
				



	}
		//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated the buying price ..</div>');	
							
						
						
						
						
			
						
						
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$branchid);																

	
							
							//redirect($view.$invoice);																
							}else
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The buying price was not updated. May be because you have not changed any information. Try again</div>');
								
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$branchid);																
							}
					   
		
		
		
		
											
											
											}






							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
						$products=$this->usermodel->populateallarray('products','code', $code);
									
						$productname=$products[0]['name'];
								$mycustomer=$this->usermodel->populateallarray('people','id', $userid);
							$exactime = date('Y-m-d H:i:s');


			$myname=$mycustomer[0]['firstname'];
		if($branch=="Main Store"){
		 $actiondone=$myname ." Changed the price of ". $productname." to: buyingprice =". $buyingprice." ,sellingprice =". $sellingprice.", qty= ". $qty.", items with id ". $myid." . in Main level at ".$exactime;

											}else{
		 $actiondone=$myname ." Changed the price of ". $productname." to: buyingprice =". $buyingprice." ,sellingprice =". $sellingprice.", qty= ". $qty.", items with id ". $myid." . in counter (". $branch.")  at ".$exactime;
	
											}
								   $mydata = array(
									
									  'userid' => $userid,
									  	  'companyid' => $companyid,

									  		'ip' => $this->input->ip_address(),		
									
									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
								 			  	 $this->usermodel->add($mydata,'activityloggs');

	 
								
								
								
								
	$confirmuomproducts = $this->usermodel->populatealldataarray('uomproducts','uom', $code,'companyid', $companyid);
if($confirmuomproducts !=false){
	
	$uomfinalprice=($buyingprice * $confirmuomproducts[0]['qty']);

	$buyingpriceDATAUOM=array(		
						
										'brice'=>$uomfinalprice,
									
										);


		$this->usermodel->updatedatabytwo($buyingpriceDATAUOM,'uomproducts','uom',$code,'companyid',$companyid);

}
	
								
								
								
								
								
								
								
						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. You can click back button </div>');
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$branchid);																
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Price not updated! May be because  you have not edited any price or try again </div>');
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$branchid);																
							
							}
  
  
  
  
  
  
  
  
  
  
  
  }
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	public function edituom() {
 
   if (!$this->input->post('btn_edituom') == "edituom"){
			
		
					   
      show_error('No identifier provided', 500);
    }
    else {
									 $mybranchid = trim($this->input->post("mybranchid"));

							 $page = trim($this->input->post("page"));
							  $myid = trim($this->input->post("myid"));

						$price = trim($this->input->post("price"));
							$qty = trim($this->input->post("qty"));
				
				$branch = trim($this->input->post("branch"));
				$unitprice = trim($this->input->post("unitprice"));
	 $uom = trim($this->input->post("uom"));
				 $code = trim($this->input->post("code"));
				 $brice = trim($this->input->post("brice"));
				 $ttbbprice=0;
						 $updatedate=($this->input->post("updatedate"));

				 
				 
				 

if(trim($unitprice)=="Yes"){
	
		$stocklist  = $this->usermodel->populatealldatarrayfour('uomproducts','code',$code,'branch', $branch,'status',"child",'unitprice<>', "Yes");

		///$stocklist  = $this->usermodel->populatealldatarraythree('uomproducts','branch', $branch,'status',"child",'unitprice<>', "Yes");
		
if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	      $allbrice=trim($row->brice);
		  
	   $ttbbprice=$ttbbprice+$allbrice;

		

		
   }
   
    $brice=$this->formatMoney((($qty/100)*$ttbbprice),true);	
 
	

}
	
	
}else if($unitprice=="YesSingle"){
	
	$getprice = $this->usermodel->populateallarray('products','code',$uom);
		      $brice=(($getprice[0]["buyingprice"]/100) * $qty);	


}else{
	
	
	$getprice = $this->usermodel->populateallarray('products','code',$uom);
		       $brice=(($getprice[0]["buyingprice"]) * $qty);
		
}
				 
		
								$productlist=array(		
									'brice'=>$brice,
									'unitprice'=>$unitprice,
												'branch'=>$branch,
		'updatedate'=>$updatedate,
												'price'=>$price,
											'qty'=>$qty,

												
												
													);
		
																		$usr_result = $this->usermodel->updatedata($productlist,'uomproducts','id',$myid);
	
											

					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								


	 
								
								
								
								
						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. </div>');
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
					//&branchid

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM was not updated! May be because  you have not edited any UOM or try again </div>');
							redirect('user/viewprice?randomitemidentifier='.$code.'&page='.$page.'&branchid='.$mybranchid);																
							
							}
  
  
  
  
  
  
  
  
  
  
  
  }
	}



	public function activationfollowup() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
  $transactionid = $_GET['randomitemidentifier'];
$status = $_GET['needed'];
 $view = $_GET['view'];

	
 
 
 
 
 	$updatefollowup=array(		
												'completed'=>"yes",
													);
								
								
 $update=	$this->usermodel->updatedata($updatefollowup,'followups','id',$transactionid);
 
 
 

        	  if( $update ==true){

$this->session->set_flashdata('activemsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status  has been changed succussesfully</div>');
								
								redirect($view );
								}else{


		$this->session->set_flashdata('activemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status has  not been changed.. Try again</div>');
								
	redirect($view );
	}
  }
	}
	
	
	public function activation() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
 $transactionid = $_GET['randomitemidentifier'];
$status = $_GET['needed'];
$itemid = $_GET['itemid'];
		   	 
			  $mystatus="";
			  if( $status =="0"){
				  $mystatus="1"; 
			  }else if( $status =="1"){
				   $mystatus="0"; 
				  
			  }
		    
 $update=$this->usermodel->updatememberstatus($transactionid,$mystatus); 
	

        	  if( $update ==true){

$this->session->set_flashdata('activemsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status of this member has been changed succussesfully</div>');
								
								redirect('user/viewmygrouping?randomitemidentifier='.$itemid );
								}else{


		$this->session->set_flashdata('activemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status of this member has  not been changed.. Try again</div>');
								
								redirect('user/viewmygrouping?randomitemidentifier='.$itemid );
	}
  }
	}
	
	
	public function activatecustomedproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
 $transactionid = $_GET['randomitemidentifier'];
$status = $_GET['needed'];
$itemid = $_GET['itemid'];
		   	 
			  $mystatus="";
			  if( $status =="0"){
				  $mystatus="1"; 
			  }else if( $status =="1"){
				   $mystatus="0"; 
				  
			  }
		    
 $update=$this->usermodel->updatecustomedcategorytatus($transactionid,$mystatus); 
	

        	  if( $update ==true){

$this->session->set_flashdata('activemsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status of this product has been changed succussesfully</div>');
								
								redirect('user/viewmygproductrouping?randomitemidentifier='.$itemid );
								}else{


		$this->session->set_flashdata('activemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> The status of this product has  not been changed.. Try again</div>');
								
								redirect('user/viewmygproductrouping?randomitemidentifier='.$itemid );
	}
  }
	}
	  public function viewmygrouping() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['mygrouping'] = $this->usermodel->populatemembergrouping($itemid, $companyid);
   	$data['itemid'] = $itemid;
	
	$data['member'] = $this->usermodel->populatemember($itemid);
$data['mycategory'] = $this->usermodel->populatecategory($companyid);
		$data['viewcategory'] = $this->usermodel->populatecategory($companyid);
    

		
		 $this->load->view('userdata/viewmygrouping',$data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
	  public function viewmycomputerno() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
   $computerno = $_GET['computerno'];
	$data['itemid'] = $itemid;
		$data['computerno'] = $computerno;
	$data['links'] = "";

    		   $data['viewmycomputerno']= $this->usermodel->populateall('computers','id >',1);
    		   $data['compkeys']= $this->usermodel->populateall('computers','invoice',$itemid);

$total_rows=count((array)$data['viewmycomputerno']);
	$data['total_rows'] =$total_rows;
		 $this->load->view('userdata/viewmycomputerno',$data);

		
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
  
  
	
  
  
  
	  public function viewmygproductrouping() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['mygrouping'] = $this->usermodel->populateproductsrouping($itemid, $companyid);
				
					$data['member'] = $this->usermodel->populateallarray('products','code',$itemid);
   	$data['itemid'] = $itemid;
	

    		   $data['mycategory']= $this->usermodel->populateall('customedproductcategory','companyid',$companyid);


		
		 $this->load->view('userdata/viewmygproductrouping',$data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
	  public function mypayslip() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
	      $slipid = $_GET['slipid'];
		//$this->load->view("template/tableheader");

   	$data['itemid'] = $itemid;
	
	$data['member'] = $this->usermodel->populatemember($itemid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		  $data['payroll'] = $this->usermodel->populateallarray('salary','salaryid',$slipid);
    		   $data['employeepayments']= $this->usermodel->populateall('employeepayments','salaryid',$slipid);


		
		 $this->load->view('userdata/mypayslip',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
  
  
  
  
  
  
	  public function mypayrollsetup() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];
		$this->load->view("template/tableheader");

   	$data['itemid'] = $itemid;
	
	$data['member'] = $this->usermodel->populatemember($itemid);

    		   $data['payrollsetup']= $this->usermodel->populateall('employeecharges','memberid',$itemid);


		
		 $this->load->view('userdata/mypayrollsetup',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	public function viewmyexpense() {
   if (!isset($_GET['pono'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['pono'];
  $finaltotal = $_GET['finaltotal'];
   	$data['pono'] = $itemid;
		$data['finaltotal'] = $finaltotal;
			  // $data['allsales']= $this->usermodel->populateall('sales','invoice',$itemid);

		   $data['viewexpenses']= $this->usermodel->populateall('expenses','idno',$itemid);

    

		
		 $this->load->view('userdata/viewmyexpense',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
		public function changepayment() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['invoice'];

   	$data['itemid'] = $itemid;
			   $data['allsalesdetails']= $this->usermodel->populateallarray('sales','invoice',$itemid);


    

		
		 $this->load->view('userdata/changepayment',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
	
	
	
	 public function viewmembersbygrouping() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
      $groupid = $_GET['randomitemidentifier'];
 $needed = $_GET['needed'];
      $data['mygrouping'] = $this->usermodel->populatememberbygrouping($groupid,$companyid,$needed);









	
$data['mycategory'] = $this->usermodel->populatecategory($userid);
		$data['viewcategory'] = $this->usermodel->populatecategory($userid);
  

		
		 $this->load->view('userdata/viewgroupmember',$data);
		$this->load->view("template/footerpage");
		
	
  }}
	
	
   public function viewmysuggestions() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];

   	$data['postid'] = $itemid;
	
	$data['suggestion'] = $this->systemusermodel->getsuggestionbyid($itemid);

    	$this->load->view("template/headerpagemin", $data);

		
		 $this->load->view('userdata/viewmoresuggestion', $data);
		$this->load->view("template/footerpage");
		
	}
  }
 
 
 
 
 
 
 
   public function addpurchaseorder()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	 $data['branchid'] = $session_data['branchid'];
	 //$branchid = $data['branchid'];
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $mydate=date("Y-m-d H:i:s");
		 
		 				 		 $deliverymethod = $this->input->post("deliverymethod");

				 
			 $mytable = $this->input->post("mytable");
		 	 $branchto = $this->input->post("branchto");

	 $branchid = $this->input->post("branchid");
 
$suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
				 
			$myagent = explode(':=',$this->input->post("agent"));


  $agent = htmlspecialchars(trim($myagent[0]));	 
				 

				 
				 $finalorder="";
				 
				 
				 				 $paymentmethodes = $this->input->post("paymentmethodes");
				 				 $transactionstatus = $this->input->post("transactionstatus");

				 
				 $invoice = $this->input->post("invoice");
			  	 $orderdate = $this->input->post("orderdate");
			  	 $ordernumber = trim($this->input->post("ordernumber"));
			  	 $description = $this->input->post("description");
			  	 $orderedby = $this->input->post("orderedby");
			  	 $shippingto = $this->input->post("shippingto");
			  	 $canceldate = $this->input->post("canceldate");
				 			  	 $vatrate = $this->input->post("vatrate");

			  	 $fob = $this->input->post("fob");
			  	 $amount = $this->input->post("amount");
				  $status = $this->input->post("status");
			
				 $finalamount=0;
				 		 $controller=0;
			
				   //echo $status;
	 //exit;
			  	 $terms = $this->input->post("terms");
				 			  	 $view = $this->input->post("view");

				 			  	 $action = $this->input->post("action");
				 			  	 $deliverydate = $this->input->post("deliverydate");
				 			  	 $mycontroller = $this->input->post("controller");

				 				 			

if(isset($mycontroller)){
		 $controller= $mycontroller;
	
}else{
			 $controller= $controller;

	
}



											$myview = $this->input->post("myview");

				 
				
				 

			  		  $this->form_validation->set_rules("action", "Action type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/purchaseorder', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			if($ordernumber !=""){
			$confirminvoice  = $this->usermodel->populatethreenoarray('purchaseorder','companyid', $companyid,'ordernumber' ,$ordernumber,'supplier',$supplier);

						
						if(($confirminvoice !=FALSE ) && ($action=="insert")){
							$createdate=$confirminvoice[0]["createdate"];
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This purchase with invoice number ('.$ordernumber.').   had  been created  already on ('.$createdate.'). Try again other purchases</div>');
								
							redirect('user/allpurchaseorder');	
								 
								 return false;
							
						}
			
		}
			
			
				if($ordernumber !=""){
			$confirminvoice  = $this->usermodel->populatealldataarrayfour('purchaseorder','companyid', $companyid,'ordernumber' ,$ordernumber,'supplier',$supplier,'invoice <>',$invoice);
//
						
						if(($confirminvoice !=FALSE ) && ($action=="update")){
							$createdate=$confirminvoice[0]["createdate"];
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This purchase with invoice number ('.$ordernumber.').   had  been created  already on ('.$createdate.'). Try again other purchases</div>');
								
							redirect($view.$invoice);																
								 
								 return false;
							
						}
			
		}
		
			
			
			
					   //validation succeeds

					   
					   $finaltotalamount=0;
											  		$viewreceivings= $this->usermodel->populateall('sales_order','invoice',$invoice);
   $currentamount=0;
      $ttbrice=0;

$salesdetails = $this->usermodel->populateallarray('sales','invoice', $invoice);
					$customerid=$salesdetails[0]['customer'];
					   	if(is_array($viewreceivings)) {
				   	 $salesaccount="";	
					 
					 	$costofgoodsold="";	
						$inventoryaccount="";
							 $creditdata = array();
					$finalcode="";			
				  	//$this->usermodel->deletedata($invoice,"code","debitcredit");
												$this->usermodel->deletedatatwo("debitcredit","code",$invoice,"type <>","payment");

					foreach ($viewreceivings as $row){ 
					$myqty= $row->qty;
										$transactionid= $row->id;
										$mybranch= $row->branch;

					$currentamount=((double)$row->qty*(double)$row->sprice);
					$mytotal= $row->amount;
					$finalamount=(double)$finalamount+(double)$row->amount;
					$finaltotalamount=(double)$finaltotalamount+(double)$currentamount;
					
					$accountcode = $this->usermodel->populateallarray('products','code', $row->code);
					$salesaccount=$accountcode[0]['salesaccount'];
					 					   
					  
					  
				  $producttype=trim($accountcode[0]['producttype']); 
				  $costofgoodsold=$accountcode[0]['expenseaccount'];
	   $inventoryaccount=$accountcode[0]['assetaccount'];
	   
	   
	    $mybprice=$row->bprice;
		  $correctqty=$row->qty;
		  $finalbprice=((double)$mybprice*(double)$correctqty);
		  
		  
  if($costofgoodsold!=""){ $costofgoodsold=$accountcode[0]['expenseaccount'];}else{ $costofgoodsold=5500; }
 if($inventoryaccount!=""){ $inventoryaccount=$accountcode[0]['assetaccount'];}else{ $inventoryaccount=1110; }	  
					  
					  
					  
					  
					  
 if($salesaccount!=""){ $salesaccount=$accountcode[0]['salesaccount'];}else{ $salesaccount=4000; }
 if($currentamount>0){
					
 $creditdata[]=array('refno'=>$transactionid, 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$currentamount,'description'=>"Sales order",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid,'balance'=> 0);

						}
						
						
						
						
						
							if(($producttype!="Service") && ($mybprice!="")){
		
		$ttbrice = $ttbrice + $finalbprice;
			 $insertinventorydata=array('refno'=>$transactionid, 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$finalbprice,'description'=>"Inventory sold",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'sales' ,'supplier'=> $supplier);
			if($finalbprice >0){
	 $this->usermodel->add($insertinventorydata,'debitcredit');


}	
					
		
	
	
	}			
	
						
						
						
					}
				
					
						if($finaltotalamount>0){

		$this->db->insert_batch('debitcredit', $creditdata); 
		
		
$debitdata=array( 'userid'=>$userid,'account'=>1100,'debit'=>$finaltotalamount,'description'=>"Sales order (A/R)",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0);

				$this->usermodel->add($debitdata,'debitcredit');

			}
					
					
					}  
					



		if($ttbrice>0){
					$insertcostofgoodsolddata=array( 'userid'=>$userid,'account'=>$costofgoodsold,'debit'=>$ttbrice,'description'=>"Cost of goods sold",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $supplier);
											$usr_result = $this->usermodel->add($insertcostofgoodsolddata,'debitcredit');




}









						
 
					   
					 	if ($this->input->post('btn_receivegoods') == "receivedelivery")
					   {
					   
				  if ($this->input->post('btn_receivegoods') == "receivedelivery"){
					  $status ="closed";
				 
				 
				  }else{
					 $status =  $status ;
 
				  }
				  
				  
				   $confirminvoice=false;
  
  
  
 
				  
				  
				  
				  
				  
				
					   if(  $deliverydate==""){
						   	   $confirminvoice=false;

						    $deliverydate= $mydate;
					   }else{
						   
						      $deliverydate= $deliverydate;
						   	   $confirminvoice=true;

						   
					   }
					   
					  
												$mydeliverydata=array(		
						
							'deliverydate'=>$deliverydate,
					'transactionstatus'=>$status,	
'paymentmethodes'=>$paymentmethodes,	
	 
			  	
			
			
								);
								
					   
								
								$usr_result = $this->usermodel->updatedata($mydeliverydata,'purchaseorder','invoice',$invoice);

								
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Received/Updated the delivery Note ..</div>');	
							
						
						
						

						 if(($confirminvoice)) {
						
							
						redirect("user/viewnewpurchaseorder?randomitemidentifier=".$invoice);																
						 }else{
																redirect("user/receivepurchases?invoice=".$invoice);																
 
							 
						 }
							
							//redirect($view.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The delivery was not updated. May be because you have not changed any information. Try again</div>');
								
							redirect($view.$invoice);																
							}
					   
					   
					   
					   
					   }else if ($this->input->post('btn_purchaseorder') == "mysalesorder")
					   {
				  
						   
						   
						   if($ordernumber!=""){
							   
						  
						     $confirmno = $this->usermodel->populatelatestid('purchaseorder', 'ordernumber',$ordernumber);

						    if($confirmno!=FALSE){
								
  $myordernumber=0;
  	
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',0);
		 	  $format=$smsconfig[0]['website'];	
  $latest = $this->usermodel->populatelatestid('purchaseorder', 'id >',0);
  if($latest==FALSE){
	    $myordernumber=(double)$ordernumber+1;
	  
  }else{
	  $mylatestid=$latest[0]['id']; 
	     $myordernumber= (double)$mylatestid+1; 
  }
  

   
    $finalorder=$format.$myordernumber;
								
								
							}else{
								
								$finalorder=$ordernumber;
							}
							
							}
						   
						   
						
						 		   
												$data=array(		
			'userid'=>$userid,
			'companyid'=>$companyid,
			'branchid'=>$branchid,
			'remarks'=>$mytable,

			'supplier'=>$supplier,
						  	'branchto'=>$branchto,

		  	'description'=>$description,
							'deliverymethod'=>$deliverymethod,

		
			'createdate'=>$dateposted,
						'agent'=>$agent,
						'vatrate'=>$vatrate,
				'paymentmethodes'=>$paymentmethodes,

				'invoice'=>$invoice,
				'fromdate'=>$orderdate,
				'paiddate'=>$canceldate,
			  	'orderdate'=>$orderdate,
			  	'ordernumber'=>$finalorder,
			  	'orderedby'=>$orderedby,
			  	'shippingto'=>$shippingto,
			  	'canceldate'=>$canceldate,
			  	'fob'=>$fob,
			  	'amount'=>$amount,
				'status'=>$status,
			  	'terms'=>$terms,  
						'controller'=>$controller,	   
						 
						   	);
						   
												$updatedata=array(		
			//'userid'=>$userid,
			'companyid'=>$companyid,
						'transactionstatus'=>$transactionstatus,

			//'branchid'=>$branchid,
			'agent'=>$agent,
			'remarks'=>$mytable,

			'supplier'=>$supplier,
			
		  	'description'=>$description,
							'deliverymethod'=>$deliverymethod,
			'controller'=>$controller,

		
			'createdate'=>$dateposted,
			
				'invoice'=>$invoice,
				'fromdate'=>$orderdate,
			  	'branchto'=>$branchto,

			  	'orderdate'=>$orderdate,
			  	'ordernumber'=>$ordernumber,
			  	'orderedby'=>$orderedby,
			  	'shippingto'=>$shippingto,
			  	'canceldate'=>$canceldate,
			  	'fob'=>$fob,
			  	'amount'=>$finalamount,
							  	'paymentmethodes'=>$paymentmethodes,

				'status'=>$status,
			  	'terms'=>$terms,
			
			
								);
								
								
								 if($action=="insert"){
										$usr_result = $this->usermodel->add($data,'purchaseorder');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($updatedata,'purchaseorder','invoice',$invoice);

								}
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								

							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created/updated the   order..</div>');	
							
								
								
									  $sms = $this->input->post("sms");

			if($sms=="yes"){
			$appriver=$this->usermodel->populateallarray('people','id', $userid);
		$myuser=$appriver[0]['firstname'];
		
		
							$mycustomer=$this->usermodel->populateallarray('people','id', $controller);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];
					
								
								
	$correctime = date("d/m/Y H:i", strtotime($dateposted));

  			$message="Dear ".$firstname.", ".$myuser." has made LPO request  on ". $correctime ." regarding ". $description .". Check your the system for approval.";


$myview=$view.$invoice;				  
		  $this->addallpushedsms($message,$contact,$myview);	
						 
							}
						 redirect($view.$invoice);
								
								
								
								
					
							
							//redirect($view.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> This  order  was not created/updated. may be you still have open order. Kindly close it.. Try again</div>');
								
							redirect($view);																
							}
					   
					      }else if ($this->input->post('btn_purchaseorder') == "purchaseorder")
					   {
						   
						   
						   
						   if($ordernumber!=""){
							   
						  
						     $confirmno = $this->usermodel->populatelatestid('purchaseorder', 'ordernumber',$ordernumber);

						    if($confirmno!=FALSE){
								
  $myordernumber=0;
  	
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',0);
		 	  $format=$smsconfig[0]['website'];	
  $latest = $this->usermodel->populatelatestid('purchaseorder', 'id >',0);
  if($latest==FALSE){
	    $myordernumber=(double)$ordernumber+1;
	  
  }else{
	  $mylatestid=$latest[0]['id']; 
	     $myordernumber= (double)$mylatestid+1; 
  }
  

   
    $finalorder=$format.$myordernumber;
								
								
							}else{
								
								$finalorder=$ordernumber;
							}
							
							}
						   
						 $finalamount=0;
				
						   								  			

		$viewreceivings= $this->usermodel->populateall('newstock','invoice',$invoice);
		
		   	if(is_array($viewreceivings)) {
				   
					foreach ($viewreceivings as $row){ 
					$myqty= $row->qty;
					

					$currentamount=((double)$row->qty*(double)$row->buyingprice);
				
					$finalamount=$finalamount+$currentamount;
					
					}
					
					}

						
						 		   
												$data=array(		
			'userid'=>$userid,
			'companyid'=>$companyid,

			'supplier'=>$supplier,
						'branchid'=>$branchid,

		  	'description'=>$description,
							'deliverymethod'=>$deliverymethod,
			  	'paymentmethodes'=>$paymentmethodes,

		
			'updateddate'=>$dateposted,
						'createdate'=>$dateposted,

				'invoice'=>$invoice,
				'fromdate'=>$orderdate,

			  	'orderdate'=>$orderdate,
			  	'ordernumber'=>$finalorder,
			  	'orderedby'=>$orderedby,
			  	'shippingto'=>$shippingto,
				'paiddate'=>$canceldate,
			  	'canceldate'=>$canceldate,
			  	'fob'=>$fob,
			  	'amount'=>$finalamount,
				'status'=>$status,
			  	'terms'=>$terms,  
						   
						 
						   	);
						   
												$updatedata=array(		
			'userid'=>$updatedid,
			'companyid'=>$companyid,

			'supplier'=>$supplier,
			
		  	'description'=>$description,
							'deliverymethod'=>$deliverymethod,
			'branchid'=>$branchid,

					'updateddate'=>$dateposted,

							'fromdate'=>$orderdate,
				'paiddate'=>$canceldate,

				'invoice'=>$invoice,
			  	'orderdate'=>$orderdate,
			  	'ordernumber'=>$ordernumber,
			  	'orderedby'=>$orderedby,
			  	'shippingto'=>$shippingto,
			  	'canceldate'=>$canceldate,
			  	'fob'=>$fob,
							  	'paymentmethodes'=>$paymentmethodes,

			  	'amount'=>$finalamount,
				'status'=>$status,
			  	'terms'=>$terms,
			
			
								);
								
								
								 if($action=="insert"){
										$usr_result = $this->usermodel->add($data,'purchaseorder');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($updatedata,'purchaseorder','invoice',$invoice);

								}
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created/updated the   order..</div>');	
							redirect($view.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> This  order  was not created/updated. may be you still have open order. Kindly close it.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else if ($this->input->post('btn_purchaseorder') == "generatedelivery")
					   {
	

							 		 $mytable= $this->input->post("mytable");

					 			if(trim($mytable) !=""){
																		$ordernumber=	$mytable;	

								}else{
									$ordernumber=	$ordernumber;	
								}
								
								 
					  
					
				
					
							$invoicename = $this->usermodel->populateallarray('sales','invoice', $invoice);
$mycredit=0;
	$mybalance=0;										
											
											   $updatedby="";
			
												$updatedat="";
												if($invoicename== FALSE){
										 $updatedby="";
											$userid=$userid;
												$updatedat="";
$mycredit=0;
$mybalance=$amount;
										}else{
											
											 $updatedby=$userid;
			
										$updatedat=$dateposted;
										$dateposted= $invoicename[0]['dateposted'];	 
											$userid=$invoicename[0]['userid'];
											$correcttotal=$invoicename[0]['total'];
											$mycredit=$invoicename[0]['credit'];
											$mypaid=$correcttotal-$mycredit;
											$mybalance=$amount-$mypaid;
											}
											
											
												$salesdata=array(	
			'userid'=>$userid,
			
				'type'=>"Invoice",
			'customer'=>$supplier,
		  	'cash'=>0.00,
					  	'salestype'=>"Retail",
			   			   
			'branch'=>$branchid,
			'companyid'=>$companyid,
		
			'dateposted'=>$dateposted,
			'total' => $amount,	
			'amount' => "0.00",							
		     'balance' => "-".$mybalance,
		     'invoice' => $invoice,  
		   
			   'due_date' => $canceldate, 
					    					  	'salesperson'=>$agent,	

							'name' => $orderedby,  					   
		    
								  'maincategory' => "1",  

					  'ordersales' =>"printed" , 
			  'description' => $shippingto,    
		  
					   'paymentstatus' =>"No",   

			 	'mytable'=>$ordernumber,
			   'credit' => $mybalance, 
					  
			
			'updatedby'=>$updatedby,
			'updatedat'=>$updatedat,


			
								);
											
											
											if($invoicename== FALSE){
										$usr_result = $this->usermodel->add($salesdata,'sales');

										}else{
											$usr_result = $this->usermodel->updatedata($salesdata,'sales','invoice',$invoice);

											}
											
											
											
								if ($usr_result ==TRUE) //active user record is present
							{
													$mysmsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$pointsdisplay=$mysmsconfig[0]['display'];
			$totalpoints=0;	

if($pointsdisplay != ""){
$userdetails = $this->usermodel->populateallarray('people','id', $supplier);
$oldpoints=$userdetails[0]['savedpoints'];


	$savedpoints=  (double)$finalamount/(double)$pointsdisplay;
	
$totalpoints=(double)$oldpoints+(double)$savedpoints;
	$updatecoinsdata=array(		
											
						'savedpoints'=>$totalpoints,
												
													);
								
								
										$this->usermodel->updatedata($updatecoinsdata,'people','id',$supplier);
							

}
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created/updated the  Delivery/Invoice..</div>');	
							redirect("user/delivergoods?invoice=".$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> This  Delivery/Invoice  was not updated may because there is no data changed.Try again</div>');
								
							redirect($view.$invoice);																
							}
				   
					   
					   }else if ($this->input->post('btn_purchaseorder') == "generatesales")
					   {
					
				
					
							$invoicename = $this->usermodel->populateallarray('sales','invoice', $invoice);

											
											
											   $updatedby="";
			
												$updatedat="";
												if($invoicename== FALSE){
										 $updatedby="";
											$userid=$userid;
												$updatedat="";

										}else{
											
											 $updatedby=$userid;
			
										$updatedat=$dateposted;
										$dateposted= $invoicename[0]['dateposted'];	 
											$userid=$invoicename[0]['userid'];

											}
											
											
											
											
							 		 $mytable= $this->input->post("mytable");

					 			if(trim($mytable) !=""){
																		$ordernumber=	$mytable;	

								}else{
									$ordernumber=	$ordernumber;	
								}
								
										
											
											
											
											
												$salesdata=array(	
			'userid'=>$userid,
						'type'=>$paymentmethodes,

				//'type'=>"Cash",
			'customer'=>$supplier,
		  	//'cash'=>$amount,
			"$paymentmethodes" =>$amount,

			
			//


//
//			
					  	'salesperson'=>$salesperson,	

					  	'salestype'=>"Retail",
			   			   
			'branch'=>$branchid,
			'companyid'=>$companyid,
		
			'dateposted'=>$dateposted,
			'total' => $amount,	
			'amount' => $amount,								
		     'balance' => 0,
		     'invoice' => $invoice,  
		   
			   'due_date' => $canceldate, 
					    
							'name' => $orderedby,  					   
		    
								  'maincategory' => "1",  

					  'ordersales' =>"printed" , 
			  'description' => $shippingto,    
		  
					   'paymentstatus' =>"No",   

			 	'mytable'=>$ordernumber,
			   'credit' => 0, 
								 //  'credit' => $amount, 
  
								
			'updatedby'=>$updatedby,
			'updatedat'=>$updatedat,


			
								);
											
											
											if($invoicename== FALSE){
										$usr_result = $this->usermodel->add($salesdata,'sales');

										}else{
											$usr_result = $this->usermodel->updatedata($salesdata,'sales','invoice',$invoice);

											}
											
											
											
								if ($usr_result ==TRUE) //active user record is present
							{
								
													$mysmsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$pointsdisplay=$mysmsconfig[0]['display'];
			$totalpoints=0;	

if($pointsdisplay != ""){
$userdetails = $this->usermodel->populateallarray('people','id', $supplier);
$oldpoints=$userdetails[0]['savedpoints'];


	$savedpoints=  (double)$finalamount/(double)$pointsdisplay;
	
$totalpoints=(double)$oldpoints+(double)$savedpoints;
	$updatecoinsdata=array(		
											
						'savedpoints'=>$totalpoints,
												
													);
								
								
										$this->usermodel->updatedata($updatecoinsdata,'people','id',$supplier);
							

}

	$updatepaymentmethodes=array(		
											
'paymentmethodes'=>$paymentmethodes,												
												
												);
													
													
				

							 $this->usermodel->updatedata($updatepaymentmethodes,'purchaseorder','invoice',$invoice);

								
							//
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created/updated the  Delivery/Invoice..</div>');	
							redirect($view.$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> This  Delivery/Invoice  was not updated may because there is no data changed.Try again</div>');
								
							redirect($view.$invoice);																
							}
				   
					   
					   }
					   
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
   public function addquatation()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 ///
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		 $deliverymethod = $this->input->post("deliverymethod");
		 		 $fob = $this->input->post("fob");

		 		 $supplier = $this->input->post("supplier");
				 $invoice = $this->input->post("invoice");
			  	 $orderdate = $this->input->post("orderdate");
			  	 $ordernumber = $this->input->post("ordernumber");
			  	 $description = $this->input->post("description");
			  	 $canceldate = $this->input->post("canceldate");
			  	 $amount = $this->input->post("amount");
				 $displayvat = $this->input->post("displayvat");
			  	 $terms = $this->input->post("terms");
				 			  	 $shippingto = $this->input->post("shippingto");
				 			  	 $department = $this->input->post("department");

				 			  	 $view = $this->input->post("view");
				 			  	 $weight = $this->input->post("weight");

				 			  	 $action = $this->input->post("action");
				 			  	 $approvedby = $this->input->post("approvedby");
	 		 $sendsms = $this->input->post("sendsms");
				 
				 				 			  	 $preparedby = $this->input->post("preparedby");
				 				 			  	 $myview = $this->input->post("myview");

				 $mysuppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($mysuppliers[0]));
	  $orderedby = htmlspecialchars(trim($mysuppliers[1]));
			 
				 
			  		  $this->form_validation->set_rules("orderdate", "Select Date Ordered", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/purchaseorder', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_quatation') == "quatation")
					   {
						   
						$mytotal=0;   
					 $ourtotal= $this->usermodel->geteallQUOTES_orderCounter($invoice,$deliverymethod);
	//
									$mytotal= round(($ourtotal[0]["amount"]));
				   
						   
						   			
			$purchaseorderlist =false;
		//	$purchaseorderlist= $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoice,'companyid',$companyid);
		
		   
if(is_array($purchaseorderlist)) {

   foreach($purchaseorderlist as $row)
   {
	  /// $mytotal= $mytotal+$row->amount;
		
		
   }
		
   }
   
   
   
   
   
   
   
   
   		 if($action=="insert"){

  $supplier = htmlspecialchars(trim($mysuppliers[0]));
	  $orderedby = htmlspecialchars(trim($mysuppliers[1]));
			$deliverydate ="New"; 
		}else {
			 $orderedby = $this->input->post("orderedby");
			 $supplier = $this->input->post("supplier");
			 $deliverydate = $this->input->post("deliverydate");


			}
		
						   
						   
						
												$data=array(		
			'userid'=>$userid,
			'companyid'=>$companyid,
			'fob'=>$fob,

			'supplier'=>$supplier,
			
		  	'description'=>$description,

					'deliverydate'=>$deliverydate,

			'createdate'=>$dateposted,
			
				'invoice'=>$invoice,
							  	'displayvat'=>$displayvat,

			  	'orderdate'=>$orderdate,
			  	'ordernumber'=>$ordernumber,
			  	'orderedby'=>$orderedby,
			  	'canceldate'=>$canceldate,
											  	'deliverymethod'=>$deliverymethod,
	'department'=>$department,
							  	'preparedby'=>$preparedby,
							  	'shippingto'=>$shippingto,
								  	'branchid'=>$branchid,
							  	'weight'=>$weight,
							  	'approvedby'=>$approvedby,

			  	'amount'=>$mytotal,
				//'status'=>$status,
			  	'terms'=>$terms,
			
			
								);
								
								
								 if($action=="insert"){
										$usr_result = $this->usermodel->add($data,'quotation');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'quotation','invoice',$invoice);

								}
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> Your Data was successfully Saved..</div>');



		if($sendsms=="yes"){	

		
			$appriver=$this->usermodel->populateallarray('people','id', $userid);
		$myuser=$appriver[0]['firstname'];
		
		
							$mycustomer=$this->usermodel->populateallarray('people','id', $approvedby);

			  $contact=$mycustomer[0]['phone'];
		
			$firstname=$mycustomer[0]['firstname'];
					
								
								
	$correctime = date("d/m/Y H:i", strtotime($dateposted));

  			$message="Dear ".$firstname.", ".$myuser." has made Items request  on ". $correctime ." regarding ". $description .". Check your the system for approval.";

$myviews="user/viewnewquotation?randomitemidentifier=";
$myview=$myviews.$invoice;				  
		  $this->addallpushedsms($message,$contact,$myview);	
						// redirect($view.$invoice);

		}




								
							redirect("user/viewnewquotation?randomitemidentifier=".$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your Data was not successfully Saved. Try again</div>');
								
							redirect("user/allquatation");																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   public function calculatepayee()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $mydeduction = $this->input->post("deduction");

			  		 		 $mynssf = $this->input->post("nssf");
			  		 		 $amount = $this->input->post("amount");

			
		
				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/slaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_paye') == "paye")
					   {
						   
						
						   
						   $scale = array();

	   			        		$mainsacle= $this->usermodel->populatealldatawhere('paye','id','asc','companyid', $companyid);
	 if(is_array($mainsacle)) 

 {
	foreach ($mainsacle as $rowscale){
		
					$scale[]=array(	
			'amt'=>$rowscale->amt,
						'id'=>$rowscale->id,
						'percentage'=>$rowscale->percentage,
			
			
								);	
		
	}
  	
 }
 						   $constans = array();

    			        		$mainconstants= $this->usermodel->populatealldatawhere('constants','id','asc','companyid', $companyid);
	 if(is_array($mainconstants)) 

 {
	foreach ($mainconstants as $rowmainconstants){
		$constans[]=array(	
			'name'=>$rowmainconstants->name,
						'id'=>$rowmainconstants->id,
						'amount'=>$rowmainconstants->amount,
				'category'=>$rowmainconstants->category,
);	}
  	
 }
 
 function getAccountName($category, $constans) {
    $key = array_search($category, array_column($constans, 'category'));
    if ($key !== FALSE) {
        return $constans[$key]['amount'];
						}
					}   
 

 
 
 $realamount = $this->input->post("amount");

  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$salesmethod=$myconfiguration[0]["salesmethod"];
$payee = 0;

$netpaye=0;
$relief = getAccountName("Relief", $constans);
$minimumpaye = getAccountName("MinimumPaye", $constans);
$Pension = getAccountName("Pension", $constans);
$nssf=0;
$nhif=0;


$alldecuctions=0;
	$netsalary=0;
    //
	
	
	$nhifrelief=0;
$houselevyrelief=0;
	$houselevy=0;

	$tireone=0;
$tireoneone=0;
	$Tire1=0;
	$Tire2=0;
	
	


 if($mynssf=="Old"){
	$nssf=getAccountName("NSSF", $constans);
	
}else{
	
	
		
				
		$GETNSSF = $this->usermodel->populatealldatanoarraythreeAsc('nssf','id >',0,'start <',$realamount,'companyid',$companyid);


//$nssf=0;
if(is_array($GETNSSF)){
	
foreach ($GETNSSF as $row){
	
	$total=0;
	
	$start=$row->start;
	$end=$row->end;
	$type=$row->type;
	$tire1tire2=$row->tire1tire2;

	$rate=$row->amount;
	$flatrate=$row->flatrate;
	

	
	$tireoneone=$tireoneone+$row->tire1;

	$t1=(($realamount)* ($rate/100));
	
	$tireone=$tireone+$t1;
	
	if($flatrate=="yes"){
			$total=$tire1tire2;


	}else{
		
		if($realamount  >=  $end ){
				
			
			if($type=="percentage"){
		$total=(($end-$start)* ($rate/100));
		}else{
			
			$total=$tire1tire2;
			
		}
			
			
		}else{
			
			$total=(($realamount-$start)*($rate/100));
			
			
		}
		
		
	}


  $nssf=$nssf+$total;

			}
			
								
		}
	
	
		
	if($tireone < $tireoneone){
		$Tire1=$tireone;
	}else{
	$Tire1=$tireoneone;

		}
		
		$Tire2=$total-$Tire1;
	
	//

	if($mynssf=="Tire1"){
			    $nssf=$Tire1;
				
				
	
	}else{
				$nssf=$nssf;

	}
	//echo $nssf;
	//exit;

}
$hslevyrate = getAccountName("Housing Levy", $constans);
$houselevy=(($realamount)* ($hslevyrate/100));

$hslevyreliefrate = getAccountName("Housing Levy Relief", $constans);
$houselevyrelief=(($hslevyreliefrate/100)* $houselevy);


$OriginalAmount = $this->input->post("amount");

 //$nhifconfig = $this->usermodel->populatedeductions("nhif",$companyid,$realamount);
///$nhif=$nhifconfig[0]["amount"];
 //$nhifrelief=$nhifconfig[0]["nhifrelief"];

$GETSHA = $this->usermodel->populatealldatanoarraythreeAsc('nhif','id >',0,'start <',$realamount,'companyid',$companyid);
$nhiftotal=0;
$nhifrelief=0;

if(is_array($GETSHA)){
	
foreach ($GETSHA as $rows){
	
	$nhiftotal=0;
	
	$start=$rows->start;
	$end=$rows->end;
	$flatratecategory=$rows->category;

	if($flatratecategory=="yes"){
		

	}else{
	
			$nhiftotal=(($realamount)*($rows->amount/100));
					
	
		}
		
		
	}
	}
	
	$nhif=$nhiftotal;
	$nhifrelief=(0.15* $nhif);

$OriginalAmount=$OriginalAmount-$nssf-$nhif-$houselevy;



//$amount=$amount-$nssf;
$amount=$amount-$nssf-$nhif-$houselevy;
	 foreach ($scale as $key => $array) {
        if ($key == 0) {
            $amount_bal = $scale[$key]['amt'];
        }else {
            $amount_bal = $amount - $scale[$key]['amt'];
        }
		
        $scale_amt = $scale[$key]['amt'];
        $percentage = $scale[$key]['percentage'];
        
        if ($amount > 0) {                  
            
            if($key == 0) {
				if($OriginalAmount<$minimumpaye){
					                $payee_charge = round(($OriginalAmount *($percentage/100)),2);

				}else{
					                $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);

				}
				         //   }elseif(($key == 1) || ($key == 2) || ($key == 3)) {

            }elseif(($key == 1)) {
                if($amount < $scale[$key]['amt']) {
                   $payee_charge = round(($amount *($percentage/100)),2); 
                }else {
                    $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);
                }
            }elseif($key == 2) {
				            //}elseif($key == 4) {

                $payee_charge = round((($OriginalAmount - $scale[$key]['amt']) *($percentage/100)),2);
            }
            $payee += $payee_charge;
            //echo $amount.'<br />';
        }else {
            
        }
        $amount = $amount - $scale[$key]['amt'];
    }
	
	//$netpaye=$payee-$relief-$houselevyrelief;
		 $netpaye=$payee-$relief;


	if(	$netpaye<0){
		$netpaye=0;
	}else{
		$netpaye=$netpaye;

	}

	

	$alldecuctions=$netpaye+$nhif+$nssf+$houselevy;
	//$netsalary=$realamount-$alldecuctions-$mydeduction;
		//$alldecuctions=$netpaye;
	$netsalary=$realamount-$netpaye-$mydeduction;

		    									$data['deduction'] = $alldecuctions;
											$data['houselevy'] = $houselevy;
	    									
											$data['houselevyrelief'] = $houselevyrelief;
											
											$data['nssf'] = $nssf;
	    									$data['nhif'] = $nhif;
	    									$data['nhifrelief'] = $nhifrelief;


	    									$data['realamount'] = $realamount;


    									$data['OriginalAmount'] = $OriginalAmount;
    									$data['relief'] = $relief;
										$data['payee'] = $netpaye;

										    $data['mydeduction'] = $mydeduction;

											$this->load->view("template/headerpagemin");
			
		 $this->load->view('userdata/paye', $data);
		$this->load->view("template/footerpage");																
							
						
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   public function calculatemypaye()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
			  		 		 $myid = $this->input->post("myid");

			  		 		 $mynssf = $this->input->post("nssf");

			
		
				
			  		  $this->form_validation->set_rules("nssf", "NSSF TYPE", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/slaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_mypaye') == "paye")
					   {
					$mypays = 0;
					$mydeduction=0;
					$mysalary=0;   

					  $member = $this->usermodel->populateallarray('people','id',$myid);
$mysalary=$member[0]["salary"];	 
 $allmypay = $this->usermodel->populatealldatarraythree('employeecharges','memberid', $myid,'category', "Pay",'status', "Active");

	 if(is_array($allmypay)) 

 {
	foreach ($allmypay as $rowallmypay){
		
	$mypays=$mypays+$rowallmypay->amount;
	
		
	}
  	
 }
 
 $alldeductions = $this->usermodel->populatealldatarraythree('employeecharges','memberid', $myid,'category', "Deduction",'status', "Active");

	 if(is_array($alldeductions)) 

 {
	foreach ($alldeductions as $rowalldeductions){
				$mydeduction=$mydeduction+$rowalldeductions->amount;

					
		
	}
  	
 }
$totalpayments=$mysalary+$mypays;




$amount = $totalpayments;
					   
 $scale = array();

	   			        		$mainsacle= $this->usermodel->populatealldatawhere('paye','id','asc','companyid', $companyid);
	 if(is_array($mainsacle)) 

 {
	foreach ($mainsacle as $rowscale){
		
					$scale[]=array(	
			'amt'=>$rowscale->amt,
			'id'=>$rowscale->id,
			'percentage'=>$rowscale->percentage,
			
			
								);	
		
	}
  	
 }
 						   $constans = array();

    			        		$mainconstants= $this->usermodel->populatealldatawhere('constants','id','asc','companyid', $companyid);
	 if(is_array($mainconstants)) 

 {
	foreach ($mainconstants as $rowmainconstants){
		$constans[]=array(	
			'name'=>$rowmainconstants->name,
						'id'=>$rowmainconstants->id,
						'amount'=>$rowmainconstants->amount,
				'category'=>$rowmainconstants->category,
);	}
  	
 }
 
 function getAccountName($category, $constans) {
    $key = array_search($category, array_column($constans, 'category'));
    if ($key !== FALSE) {
        return $constans[$key]['amount'];
						}
					}   
 

 
 
 $realamount = $totalpayments;

  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$salesmethod=$myconfiguration[0]["salesmethod"];
$payee = 0;

$netpaye=0;
$relief = getAccountName("Relief", $constans);
$minimumpaye = getAccountName("MinimumPaye", $constans);
$Pension = getAccountName("Pension", $constans);
$nssf=0;
$nhifrelief=0;

$nhif=0;
$alldecuctions=0;
	$netsalary=0;
    
 
	$nhifrelief=0;
$houselevyrelief=0;
	$houselevy=0;

	$tireone=0;
$tireoneone=0;
	$Tire1=0;
	$Tire2=0;
	
	


 if($mynssf=="Old"){
	$nssf=getAccountName("NSSF", $constans);
	
}else{
	
	
		
				
		$GETNSSF = $this->usermodel->populatealldatanoarraythreeAsc('nssf','id >',0,'start <',$realamount,'companyid',$companyid);


//$nssf=0;
if(is_array($GETNSSF)){
	
foreach ($GETNSSF as $row){
	
	$total=0;
	
	$start=$row->start;
	$end=$row->end;
	$type=$row->type;
	$tire1tire2=$row->tire1tire2;

	$rate=$row->amount;
	$flatrate=$row->flatrate;
	

	
	$tireoneone=$tireoneone+$row->tire1;

	$t1=(($realamount)* ($rate/100));
	
	$tireone=$tireone+$t1;
	
	if($flatrate=="yes"){
			$total=$tire1tire2;


	}else{
		
		if($realamount  >=  $end ){
				
			
			if($type=="percentage"){
		$total=(($end-$start)* ($rate/100));
		}else{
			
			$total=$tire1tire2;
			
		}
			
			
		}else{
			
			$total=(($realamount-$start)*($rate/100));
			
			
		}
		
		
	}


  $nssf=$nssf+$total;

			}
			
								
		}
	
	
		
	if($tireone < $tireoneone){
		$Tire1=$tireone;
	}else{
	$Tire1=$tireoneone;

		}
		
		$Tire2=$total-$Tire1;
	
	//

	if($mynssf=="Tire1"){
			    $nssf=$Tire1;
				
				
	
	}else{
				$nssf=$nssf;

	}
	//echo $nssf;
	//exit;

}
$hslevyrate = getAccountName("Housing Levy", $constans);
$houselevy=(($realamount)* ($hslevyrate/100));

$hslevyreliefrate = getAccountName("Housing Levy Relief", $constans);
$houselevyrelief=(($hslevyreliefrate/100)* $houselevy);


$OriginalAmount = $totalpayments;
//$OriginalAmount=$OriginalAmount-$nssf;


 //$nhifconfig = $this->usermodel->populatedeductions("nhif",$companyid,$realamount);
//$nhif=$nhifconfig[0]["amount"];
 //$nhifrelief=$nhifconfig[0]["nhifrelief"];

	$GETSHA = $this->usermodel->populatealldatanoarraythreeAsc('nhif','id >',0,'start <',$realamount,'companyid',$companyid);
$nhiftotal=0;
$nhifrelief=0;

if(is_array($GETSHA)){
	
foreach ($GETSHA as $rows){
	
	$nhiftotal=0;
	
	$start=$rows->start;
	$end=$rows->end;
	$flatratecategory=$rows->category;

	if($flatratecategory=="yes"){
		

	}else{
	
			$nhiftotal=(($realamount)*($rows->amount/100));
					
	
		}
		
		
	}
	}
	
	$nhif=$nhiftotal;
	$nhifrelief=(0.15* $nhif);

$OriginalAmount=$OriginalAmount-$nssf-$nhif-$houselevy;

$amount=$amount-$nssf-$nhif-$houselevy;


	 foreach ($scale as $key => $array) {
        if ($key == 0) {
            $amount_bal = $scale[$key]['amt'];
        }else {
            $amount_bal = $amount - $scale[$key]['amt'];
        }
		
        $scale_amt = $scale[$key]['amt'];
        $percentage = $scale[$key]['percentage'];
        
        if ($amount > 0) {                  
            
            if($key == 0) {
				if($OriginalAmount<$minimumpaye){
					                $payee_charge = round(($OriginalAmount *($percentage/100)),2);

				}else{
					                $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);

				}
				            }elseif(($key == 1)) {

            //}elseif(($key == 1) || ($key == 2) || ($key == 3)) {
                if($amount < $scale[$key]['amt']) {
                   $payee_charge = round(($amount *($percentage/100)),2); 
                }else {
                    $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);
                }
				           // }elseif($key == 4) {

            }elseif($key == 2) {
                $payee_charge = round((($OriginalAmount - $scale[$key]['amt']) *($percentage/100)),2);
            }
            $payee += $payee_charge;
            //echo $amount.'<br />';
        }else {
            
        }
        $amount = $amount - $scale[$key]['amt'];
    }
	
	//$netpaye=$payee-$relief;
	
	 //$netpaye=$payee-$relief-$nhifrelief;
	$netpaye=$payee-$relief;

	
	if(	$netpaye<0){
		$netpaye=0;
	}else{
		$netpaye=$netpaye;

	}

		$alldecuctions=$netpaye+$nhif+$nssf+$houselevy;

	$netsalary=$realamount-$alldecuctions-$mypays;
	
	
	$nssfconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"NSSF",'companyid', $companyid);
	$nssfid=$nssfconfig[0]['id'];
	
	$nnssfDATA=array(	'amount'=>$nssf,);
	$nhifconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"NHIF",'companyid', $companyid);
	$nhifid=$nhifconfig[0]['id'];
	$nhifDATA=array(	'amount'=>$nhif,);
	
	$payeconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"PAYE",'companyid', $companyid);
	$payeid=$payeconfig[0]['id'];
	
		$houselevyconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"HOUSE LEVY",'companyid', $companyid);
	$houselevyid=$houselevyconfig[0]['id'];
$houseleveyamount=($totalpayments*($hslevyrate/100));

	

	$payeDATA=array(	'amount'=>$netpaye,);
		$nhifreliefDATA=array(	'nhifrelief'=>$nhifrelief,
	);
	
		$HouselevyDATA=array(	'amount'=>$houseleveyamount,);

	$this->usermodel->updatedata($nnssfDATA,'employeecharges','id',$nssfid);
	$this->usermodel->updatedata($nhifDATA,'employeecharges','id',$nhifid);
	$this->usermodel->updatedata($payeDATA,'employeecharges','id',$payeid);
	$this->usermodel->updatedata($nhifreliefDATA,'people','id',$myid);
	$this->usermodel->updatedata($HouselevyDATA,'employeecharges','id',$houselevyid);

	
	
	
	

		    									$data['mydeduction'] = $mydeduction;
		    									$data['deduction'] = $alldecuctions;

	    									$data['nssf'] = $nssf;
	    									$data['nhif'] = $nhif;
												$data['nhifrelief'] = $nhifrelief;

												$data['houselevy'] = $houselevy;
	    									
											$data['houselevyrelief'] = $houselevyrelief;
											
	    									$data['realamount'] = $realamount;


    									$data['OriginalAmount'] = $OriginalAmount;
    									$data['relief'] = $relief;
										$data['payee'] = $netpaye;

								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										      $this->load->view("template/headerpagemin");
			
		//$this->load->view('userdata/paye', $data);
		 
		redirect('user/mypayrollsetup?randomitemidentifier='.$myid);

		$this->load->view("template/footerpage");																
							
						
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }




 public function startbulklabour()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
			  		 		 //$myid = $this->input->post("myid");

			  		 		 $salarydate = $this->input->post("salarydate");
						  		 		 $code = $this->input->post("code");

						  		 		 $slarymonth = $this->input->post("slarymonth");
						  		 		 $year = $this->input->post("year");

		
				
			  		  $this->form_validation->set_rules("salarydate", "salary date", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/slaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_bulklabour') == "bulk")
					   {
						   
						   
									$data['slarymonth'] = $slarymonth;
									$data['year'] = $year;
										$data['fromdate'] = $salarydate;
						   
						$data['readings'] = $this->usermodel->populatealldatanoarrayfiveLabour($code,'status', 1,'category', "user",'companyid', $companyid,'branchid',$branchid,'paid', "Yes");
  
   

					   
					   
				$this->load->view("template/headerpagemin");


	$this->load->view('userdata/bulklabour', $data);
		 

		$this->load->view("template/footerpage");																
							
						
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }








 
   public function bulkcalculatemypaye()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
			  		 		 //$myid = $this->input->post("myid");

			  		 		 $mynssf = $this->input->post("nssf");

			
		
				
			  		  $this->form_validation->set_rules("nssf", "NSSF TYPE", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/slaryhistory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_mypaye') == "bulk")
					   {
						   
						    function getAccountName($category, $constans) {
    $key = array_search($category, array_column($constans, 'category'));
    if ($key !== FALSE) {
        return $constans[$key]['amount'];
						}
					}   
 
						   
						   
						$mypeople = $this->usermodel->populatealldatanoarrayfive('people','status', 1,'category', "user",'companyid', $companyid,'branchid',$branchid,'paid','Yes');
  


	 if(is_array($mypeople)) 

 {
	foreach ($mypeople as $people){
		
		$mypays = 0;
					$mydeduction=0;
					$mysalary=0;  
	 $myid=$people->id;
	 	 $mysalary=$people->salary;

						   
					 

					 // $member = $this->usermodel->populateallarray('people','id',$myid);
//$mysalary=$member[0]["salary"];	 
 $allmypay = $this->usermodel->populatealldatarraythree('employeecharges','memberid', $myid,'category', "Pay",'status', "Active");

	 if(is_array($allmypay)) 

 {
	foreach ($allmypay as $rowallmypay){
		
	$mypays=$mypays+$rowallmypay->amount;
	
		
	}
  	
 }
 
 $alldeductions = $this->usermodel->populatealldatarraythree('employeecharges','memberid', $myid,'category', "Deduction",'status', "Active");

	 if(is_array($alldeductions)) 

 {
	foreach ($alldeductions as $rowalldeductions){
				$mydeduction=$mydeduction+$rowalldeductions->amount;

					
		
	}
  	
 }
$totalpayments=$mysalary+$mypays;




$amount = $totalpayments;
					   
 $scale = array();

	   			        		$mainsacle= $this->usermodel->populatealldatawhere('paye','id','asc','companyid', $companyid);
	 if(is_array($mainsacle)) 

 {
	foreach ($mainsacle as $rowscale){
		
					$scale[]=array(	
			'amt'=>$rowscale->amt,
			'id'=>$rowscale->id,
			'percentage'=>$rowscale->percentage,
			
			
								);	
		
	}
  	
 }
 						   $constans = array();

    			        		$mainconstants= $this->usermodel->populatealldatawhere('constants','id','asc','companyid', $companyid);
	 if(is_array($mainconstants)) 

 {
	foreach ($mainconstants as $rowmainconstants){
		$constans[]=array(	
			'name'=>$rowmainconstants->name,
						'id'=>$rowmainconstants->id,
						'amount'=>$rowmainconstants->amount,
				'category'=>$rowmainconstants->category,
);	}
  	
 }
 


 
 
 $realamount = $totalpayments;

  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$salesmethod=$myconfiguration[0]["salesmethod"];
$payee = 0;

$netpaye=0;
//
$relief = getAccountName("Relief", $constans);
$minimumpaye = getAccountName("MinimumPaye", $constans);
$Pension = getAccountName("Pension", $constans);
$nssf=0;
$nhifrelief=0;

$nhif=0;
$alldecuctions=0;
	$netsalary=0;
    
 
	$nhifrelief=0;
$houselevyrelief=0;
	$houselevy=0;

	$tireone=0;
$tireoneone=0;
	$Tire1=0;
	$Tire2=0;
	
	


 if($mynssf=="Old"){
	$nssf=getAccountName("NSSF", $constans);
	
}else{
	
	
		
				
		$GETNSSF = $this->usermodel->populatealldatanoarraythreeAsc('nssf','id >',0,'start <',$realamount,'companyid',$companyid);


//$nssf=0;
if(is_array($GETNSSF)){
	
foreach ($GETNSSF as $row){
	
	$total=0;
	
	$start=$row->start;
	$end=$row->end;
	$type=$row->type;
	$tire1tire2=$row->tire1tire2;

	$rate=$row->amount;
	$flatrate=$row->flatrate;
	

	
	$tireoneone=$tireoneone+$row->tire1;

	$t1=(($realamount)* ($rate/100));
	
	$tireone=$tireone+$t1;
	
	if($flatrate=="yes"){
			$total=$tire1tire2;


	}else{
		
		if($realamount  >=  $end ){
				
			
			if($type=="percentage"){
		$total=(($end-$start)* ($rate/100));
		}else{
			
			$total=$tire1tire2;
			
		}
			
			
		}else{
			
			$total=(($realamount-$start)*($rate/100));
			
			
		}
		
		
	}


  $nssf=$nssf+$total;

			}
			
								
		}
	
	
		
	if($tireone < $tireoneone){
		$Tire1=$tireone;
	}else{
	$Tire1=$tireoneone;

		}
		
		$Tire2=$total-$Tire1;
	
	//

	if($mynssf=="Tire1"){
			    $nssf=$Tire1;
				
				
	
	}else{
				$nssf=$nssf;

	}
	//echo $nssf;
	//exit;

}
$hslevyrate = getAccountName("Housing Levy", $constans);
$houselevy=(($realamount)* ($hslevyrate/100));

$hslevyreliefrate = getAccountName("Housing Levy Relief", $constans);
$houselevyrelief=(($hslevyreliefrate/100)* $houselevy);



$GETSHA = $this->usermodel->populatealldatanoarraythreeAsc('nhif','id >',0,'start <',$realamount,'companyid',$companyid);
$nhiftotal=0;
$nhifrelief=0;

if(is_array($GETSHA)){
	
foreach ($GETSHA as $rows){
	
	$nhiftotal=0;
	
	$start=$rows->start;
	$end=$rows->end;
	$flatratecategory=$rows->category;

	if($flatratecategory=="yes"){
		

	}else{
	
			$nhiftotal=(($realamount)*($rows->amount/100));
					
	
		}
		
		
	}
	}
	
	$nhif=$nhiftotal;
	$nhifrelief=(0.15* $nhif);











$OriginalAmount = $totalpayments;
//$OriginalAmount=$OriginalAmount-$nssf;
$OriginalAmount=$OriginalAmount-$nssf-$nhif-$houselevy;












 //$nhifconfig = $this->usermodel->populatedeductions("nhif",$companyid,$realamount);
//$nhif=$nhifconfig[0]["amount"];
 //$nhifrelief=$nhifconfig[0]["nhifrelief"];


$amount=$amount-$nssf-$nhif-$houselevy;


//$amount=$amount-$nssf;


	 foreach ($scale as $key => $array) {
        if ($key == 0) {
            $amount_bal = $scale[$key]['amt'];
        }else {
            $amount_bal = $amount - $scale[$key]['amt'];
        }
		
        $scale_amt = $scale[$key]['amt'];
        $percentage = $scale[$key]['percentage'];
        
        if ($amount > 0) {                  
            
            if($key == 0) {
				if($OriginalAmount<$minimumpaye){
					                $payee_charge = round(($OriginalAmount *($percentage/100)),2);

				}else{
					                $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);

				}
				            }elseif(($key == 1)) {

            //}elseif(($key == 1) || ($key == 2) || ($key == 3)) {
                if($amount < $scale[$key]['amt']) {
                   $payee_charge = round(($amount *($percentage/100)),2); 
                }else {
                    $payee_charge = round(($scale[$key]['amt'] *($percentage/100)),2);
                }
				           // }elseif($key == 4) {

            }elseif($key == 2) {
                $payee_charge = round((($OriginalAmount - $scale[$key]['amt']) *($percentage/100)),2);
            }
            $payee += $payee_charge;
            //echo $amount.'<br />';
        }else {
            
        }
        $amount = $amount - $scale[$key]['amt'];
    }
	
	$netpaye=$payee-$relief;

	
	 //$netpaye=$payee-$relief-$nhifrelief;
	//$netpaye=$payee-$relief-$houselevyrelief;

	
	if(	$netpaye<0){
		$netpaye=0;
	}else{
		$netpaye=$netpaye;

	}


	$alldecuctions=$netpaye+$nhif+$nssf+$houselevy;
	
	//$netsalary=$realamount-$netpaye-$mypays;
	
	
	
	

	$netsalary=$realamount-$alldecuctions-$mypays;
	
	
	$nssfconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"NSSF",'companyid', $companyid);
	$nssfid=$nssfconfig[0]['id'];
	
	$nnssfDATA=array(	'amount'=>$nssf,);
	$nhifconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"NHIF",'companyid', $companyid);
	$nhifid=$nhifconfig[0]['id'];
	$nhifDATA=array(	'amount'=>$nhif,);
	
	$payeconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"PAYE",'companyid', $companyid);
	$payeid=$payeconfig[0]['id'];
	
		$houselevyconfig = $this->usermodel->populatealldatanorraythree('employeecharges','memberid', $myid,'statutory',"HOUSE LEVY",'companyid', $companyid);
	$houselevyid=$houselevyconfig[0]['id'];
 $houseleveyamount=($totalpayments*($hslevyrate/100));

	

	$payeDATA=array(	'amount'=>$netpaye,);
		$nhifreliefDATA=array(	'nhifrelief'=>$nhifrelief,
	);
	
		$HouselevyDATA=array(	'amount'=>$houseleveyamount,);

	$this->usermodel->updatedata($nnssfDATA,'employeecharges','id',$nssfid);
	$this->usermodel->updatedata($nhifDATA,'employeecharges','id',$nhifid);
	$this->usermodel->updatedata($payeDATA,'employeecharges','id',$payeid);
	$this->usermodel->updatedata($nhifreliefDATA,'people','id',$myid);
	$this->usermodel->updatedata($HouselevyDATA,'employeecharges','id',$houselevyid);

	
	
	
	

		    									$data['mydeduction'] = $mydeduction;
		    									$data['deduction'] = $alldecuctions;

	    									$data['nssf'] = $nssf;
	    									$data['nhif'] = $nhif;
												$data['nhifrelief'] = $nhifrelief;

												$data['houselevy'] = $houselevy;
	    									
											$data['houselevyrelief'] = $houselevyrelief;
											
	    									$data['realamount'] = $realamount;


    									$data['OriginalAmount'] = $OriginalAmount;
    									$data['relief'] = $relief;
										$data['payee'] = $netpaye;

		}
		
		}
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
										      $this->load->view("template/headerpagemin");
			
		//$this->load->view('userdata/paye', $data);
		 
		redirect('user/salaryhistory');

		$this->load->view("template/footerpage");																
							
						
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   public function addcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
				
			
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'category');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Product..</div>');	
							redirect('user/viewcategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not added.. Try again</div>');
								
								 redirect('user/viewcategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  public function addproductsubcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    
		
							  		  $this->form_validation->set_rules("maincategory", "main category name", "trim|required");

			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsubcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addproductsubcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
						'maincategory'=>$maincategory,

				
			
								);
							$usr_result = $this->usermodel->add($data,'maincategory');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Sub-Product Category..</div>');	
							redirect('user/viewsubcategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product Sub-Category was not added.. Try again</div>');
								
								 redirect('user/viewsubcategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
  public function postdelivery()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 	
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 			
		 	 $code = trim($this->input->post("code"));
			 	// $serial = $this->input->post("serial");
				 

		   	  $status = $this->input->post("status");
			  		   	  $branch = $this->input->post("branch");
			  		   	  $orderno = $this->input->post("orderno");

			  		   	 // $commission = $this->input->post("commission");
			  		   	 // $shipping = $this->input->post("shipping");
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $staff = $this->input->post("staff");
			  			  $mode = $this->input->post("mode");

			  $description = "Dispatched Goods";
			  $qty = $this->input->post("qty");
			  $ordereddate = $this->input->post("ordereddate");

			  							  $serial="" ;

			     $view = $this->input->post("view");
			     $category = $this->input->post("category");

				 
					
		
							  		  $this->form_validation->set_rules("orderno", "Order Number", "trim|required");

			  		  $this->form_validation->set_rules("staff", "S", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/recorddelivery', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adddelivery') == "product")
					   {
						 

						           		          		$confirmorderno = $this->usermodel->populateallarray('delivery','orderno',$orderno);

						     if ($confirmorderno !=false)
						   {
							 
							 // $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 // <strong>Error!</strong> That Order Number ('.$orderno.')  already exist. Try again.</div>');
							//redirect($view);	

						   }
						   









						 $mainid="";
						   
						  $productname = $this->usermodel->geteproductlistbyid($code,$branch);

						  if ($productname ==false)
						   {
							 						 $myserialname = $this->usermodel->geteproductlistbyserial($code,$branch);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 

							//$qty=$myserialname[0]['qty'];						  
							
							if($branch=="Main"){
							$productname = $this->usermodel->geteproductbyid($myserialname[0]['code']);

							}else{
							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$branch);

							}

						   $mainid=$productname[0]['id'];
						   $original=trim($productname[0]['qty']); 
	 $balancebalance=$original-$qty;


						   }else{
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							redirect($view);	

								
							//redirect('user/viewsales');						   
						   return false;
						   }
						   }else{
							  $serial="" ;
							   
							   
						   }
						   
						
						   
						   
						   
	$productid=$productname[0]['id'];  
  $buyingprice=$productname[0]['buyingprice']; 
      $sellingprice=trim($productname[0]['sellingprice']); 
	        $name=trim($productname[0]['name']); 
  
						   
						 $category=$this->usermodel->populateallarray('productcategory','id', $category);
		   $finalcommission="";
						    						     $commission=trim($category[0]['commission']);

						     $commissiontype=trim($category[0]['type']);
							 if($commissiontype=="Amount"){
								 
									   $finalcommission=trim($category[0]['commission']);
							 }else{
								 
								$mycommission=(($commission/100)*$sellingprice);
										$finalcommission= $this->formatMoney($mycommission, true);	 
							 }
						   
							
	        $shipping=trim($category[0]['shipping']); 
						   
						   				

						   
						   
						   
						   
						   
			 
												
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
		  	'description'=>$description,

						'status'=>$status,
						'commissionrate'=>$commission,

			
			'createdate'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'staff'=>$staff,
								'orderno'=>$orderno,
				'branch'=>$branchid,

				'description'=>$description,
				
			'qty'=>$qty,
						'mode'=>$mode,

		
			'serial'=>$serial,
			'ordereddate'=>$ordereddate,
						
			'shipping'=>$shipping,
			'commission'=>$finalcommission,
									'type'=>$commissiontype,

								); 
												 
												

				
			
							$usr_result = $this->usermodel->add($data,'delivery');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								$newqtyDATA=array(		
						'qty'=>$balancebalance,

								);
											$serialdata=array(		
						'status'=>"used",

								);
								 $this->usermodel->updatedata($newqtyDATA,'productlist','id',$mainid);
								 $this->usermodel->updatedata($serialdata,'serials','id',$serialid);

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a delivery..</div>');	
							redirect('user/recorddelivery');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Delivery was not added.. Try again</div>');
								
								 redirect('user/recorddelivery');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
 
  
  public function updatepostdelivery()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 //$userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 	 $name = trim($this->input->post("name"));

		 	 $code = trim($this->input->post("code"));
			 	$serial = $this->input->post("serial");
				 			 	$myid = $this->input->post("mycategoryid");


		   	  $status = $this->input->post("status");
			  		   	  $branch = $this->input->post("branch");
			  		   	  $orderno = $this->input->post("orderno");

			  		   	  $commission = $this->input->post("commission");
			  		   	 $shipping = $this->input->post("shipping");
			$supplier = $this->input->post("supplier");
			  $buyingprice = $this->input->post("buyingprice");
			  $sellingprice = $this->input->post("sellingprice");
			  $staff = $this->input->post("staff");
			  $description = "Dispatched Goods";
			  $qty = $this->input->post("qty");
			  $ordereddate = $this->input->post("ordereddate");

			  							  $serial="" ;

			     $view = $this->input->post("view");
			     $category = $this->input->post("category");
			     $commissionrate = $this->input->post("commissionrate");
			     $myprofit = $this->input->post("profit");
			     $page = $this->input->post("page");

				 
					
		
							  		  $this->form_validation->set_rules("orderno", "Order Number", "trim|required");

			  		  $this->form_validation->set_rules("staff", "S", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/recorddelivery', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatedeliverydetails') == "delivery")
					   {
						   $mainid="";
						   
						 
						   
						   

						 $category=$this->usermodel->populateallarray('productcategory','id', $category);
		   
						   
						   
						     
						   
						   					$mycommission=(($commissionrate/100)*$sellingprice);
										$finalcommission= $this->formatMoney($mycommission, true);
if($status=="Delivered"){
		            
			  				$profit=($sellingprice-$buyingprice-$finalcommission-$shipping);

			
						   
			
			  }else{
			$profit=$myprofit;
  
			  }
				
						   
						   
						   
						   
						   
			 
												
												$data=array(		
			'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
		  	'description'=>$description,

						'status'=>$status,

			
			//'createdate'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
						'profit'=>$profit,

			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'staff'=>$staff,
								'orderno'=>$orderno,
				'branch'=>$branch,

				'description'=>$description,
				
			'qty'=>$qty,
			
		
			//'serial'=>$serial,
			//'ordereddate'=>$ordereddate,
						
			'shipping'=>$shipping,
						'commissionrate'=>$commissionrate,

			'commission'=>$finalcommission,
						
								); 
												 
												

						$usr_result= $this->usermodel->updatedata($data,'delivery','id',$myid);

			
							
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
							
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a delivery..</div>');	
											redirect("Systemusers/recorddelivery/".$page);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Delivery was not added.. Try again</div>');
								
											redirect("Systemusers/recorddelivery/".$page);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
  public function addcategorytask()
    {
		
			$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  		   	  $mode = $this->input->post("mode");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addtasktypecategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
					  	'mode'=>$mode,

		  	'description'=>$description,
			
						'companyid'=>$companyid,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'tasktype');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Task Category..</div>');	
							redirect('user/viewtaskcategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Task Category was not added.. Try again</div>');
								
								 redirect('user/viewtaskcategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
  public function addgrouping()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $memberid = $this->input->post("itemid");
				$categoryid = $this->input->post("categoryid");
		   	  $status = $this->input->post("status");
			  $mystatus="";
			  if( $status =="active"){
				  $mystatus="1"; 
			  }else{
				   $mystatus="0"; 
				  
			  }
		    
			
				
			  		  $this->form_validation->set_rules("itemid", "Member name", "trim|required");
					  
$confirm_result = $this->usermodel->confirmgrouping($memberid, $categoryid,$companyid);
			  
			  
			    if($confirm_result ==TRUE){
				 $this->session->set_flashdata('groupmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> This member had been assigned to that group.. Try a diffrent group or add more groups</div>');
								
								redirect('user/viewmygrouping?randomitemidentifier='.$memberid );	
			  }
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmygrouping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addgrouppingy') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'memberid'=>$memberid,
				'status'=>$mystatus,
		  	'categoryid'=>$categoryid,
			'createdate'=>$dateposted,
			
			'companyid'=>$companyid,
				
			
								);
							$usr_result = $this->usermodel->add($data,'grouping');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('groupmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a Member to a new agroup  ..</div>');	
							redirect('user/viewmygrouping?randomitemidentifier='.$memberid );																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('groupmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Member  was not added into anew group.. Try again</div>');
								
								redirect('user/viewmygrouping?randomitemidentifier='.$memberid );	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
  
  public function addcustomedgrouping()
    {
		
			$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $memberid = $this->input->post("itemid");
				$categoryid = $this->input->post("categoryid");
		   	  $status = $this->input->post("status");
			  $mystatus="";
			  if( $status =="active"){
				  $mystatus="1"; 
			  }else{
				   $mystatus="0"; 
				  
			  }
		    
			
				
			  		  $this->form_validation->set_rules("itemid", "Prosuct name", "trim|required");
					  
$confirm_result = $this->usermodel->confirmgcustomedrouping($memberid, $categoryid,$companyid);
			  
			  
			    if($confirm_result ==TRUE){
				 $this->session->set_flashdata('groupmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> This product had been assigned to that group.. Try a diffrent group or add more groups</div>');
								
								redirect('user/viewmygproductrouping?randomitemidentifier='.$memberid );	
			  }
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmygrouping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcustomedgrouppingy') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'memberid'=>$memberid,
				'status'=>$mystatus,
		  	'categoryid'=>$categoryid,
			'createdate'=>$dateposted,
			
			'companyid'=>$companyid,
				
			
								);
							$usr_result = $this->usermodel->add($data,'productsgrouping');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('groupmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a Product to a new agroup  ..</div>');	
							redirect('user/viewmygproductrouping?randomitemidentifier='.$memberid );																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('groupmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product  was not added into anew group.. Try again</div>');
								
								redirect('user/viewmygproductrouping?randomitemidentifier='.$memberid );	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   public function addsms2()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $contact = trim($this->input->post("contact"));

		   	  $mymessage = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			 
			 
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsms') == "sms")

					   {
						   
				
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546310</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=150){
				
					$COST=1;
				 }else if($countmessage<=310){
					 
					$COST=2;
				 }else if($countmessage<=470){
					$COST=3;
					
				 }
				 else if($countmessage<=630){
					$COST=4;
				
				 }
				 else if($countmessage<=790){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		try{
				$url = 'http://sms.robisearch.com/sendsms.jsp?';
			$xml_data ='<?xml version="1.0"?><smslist><sms><user>'.$username.'</user><password>'.$password.'</password><message>'.$message.'</message><mobiles>'.$allcontacts.'</mobiles><senderid>'.$from.'</senderid><cdmasenderid>00201009546310</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid></sms></smslist>'; 

 
			$ch = curl_init($url);			
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
			curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
		
				$xml = new SimpleXMLElement($output);

			
			$code="error-code";
			$mydescription="error-description";
			$finalcode=$xml->error->$code;
			$description=$xml->error->$mydescription;
			if($finalcode== 0) {
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=150){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=310){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=470){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=630){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=790){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} catch (Exception $e) {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or '.$e->getMessage(). '.Try again </div>');
						redirect('user/viewsms');		
				}
				
			
}
}
			
	if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewsms');
			
				
			}
			
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
  
  
  
   public function addsms()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				if (isset($_GET['contact'])){
				$contact=$_GET['contact'];
				$mymessage=$_GET['mymessage'];
				$target=$_GET['target'];

				}else{
				$contact = htmlspecialchars(trim($this->input->post("contact")));
				$target="No";

		   	  $mymessage = trim($this->input->post("message",TRUE));
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");
			  
					
				}
							
				
				
				
				
				
				
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			
			 
			 
						   
				
					 
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
//$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
 $username=$confirmsmsaccount_result[0]['username'];
 $from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
			
			
			
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=".urlencode($from)."&mobile=$allcontacts";

			//$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=". urlencode($password) . "&partnerID=".urlencode($username)."&message=".urlencode($message)."&shortcode=".urlencode($from)."&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";



			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	
	
	
	
	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
						redirect('user/viewsms');		
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else{
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  
  
  
  
  
  
  
  
  
  
 
  public function addsalessms()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 	
			  		   	  $contact = $this->input->post("contact");
		   	  $message = $this->input->post("message");
		   	   $myview = $this->input->post("view");

		  $this->pushedsmswithview($message,$contact,$myview);	

			
			
			
	}
  
  
  
  
  
  
  
   	function SendStStockMaster1($itemcode,$qty)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
						   }											
							
						  
						  
						  
	$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
							  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

	 
	 
	 
	 
	 
	 
	 
	 
		 		
		 		 $apiUrl = ''.$etimsurl.'/etims-api/saveStockMaster';

        // Data to send in the JSON format
		
		
		  $data = [
		  
            "itemCd" => $itemcode,
            "rsdQty" => $qty,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
			
        ];
		  
		
		
		
		
		
		
		


        // Convert the data to JSON format
        $jsonData = json_encode($data);
						
			$ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
//var_dump($response);
//exit;

					        // Check for cURL errors
            if (curl_errno($ch)) {


						
				
				
				
           } else {
				
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



						if ($resultCd == '000') {	
						
							$datasaved=1;
						}else {

							$datasaved=0;
						}							
					
		   
		
			}		   
										   
										   
						   
										   
						   
}					   
			
   	function SendStStockMaster($code,$qty)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);

	 
						  
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
			  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);
//$apiUrl = ''.$etimsurl.'/etims-api/saveStockMaster';





	 	$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);
								 
				$name=$productname[0]['name']; 
				$itemclassification=$productname[0]['itemclassification']; 
		  	$itemcode=$productname[0]['hscode'];
					  	$packagingunit =$productname[0]['packagingunit']; 
					  	$salesunit=$productname[0]['salesunit']; 
	   					  	$taxcode=$productname[0]['itemtax']; 			
								$buyingprice=$productname[0]['buyingprice'];
									$sellingprice=$productname[0]['sellingprice'];
	 									$inventorytype=$productname[0]['producttype'];

	 
	 
 if($inventorytype !="Service"){	 
	 
	 if($onlineoffline=="OSCU"){
			 $apiUrl = ''.$etimsurl.'/etims-api/saveStockMaster';


			 }else{
			
			$apiUrl = ''.$etimsurl.'/stockMaster/saveStockMaster';

			 }
	 
	 
		 		

        // Data to send in the JSON format
		
		
		  $data = [
		  	'tin' => $kra_pin,
            'bhfId' => $branch_id,
            "itemCd" => $itemcode,
            "rsdQty" => $qty,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
			
        ];
		  
		
		
		
		
		
		
		


        // Convert the data to JSON format
        $jsonData = json_encode($data);
						
			$ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
		//var_dump($response);
		//exit;
        // Check for cURL errors
            if (curl_errno($ch)) {


						
				
				
				
           } else {
				
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



					
		   
		
			}		   
										   
										   
 }				   
										   
						   
}					 				   					   
						   
					function SendStStockIO($code,$qty,$sarNo,$sarNo1,$companyname,$krapin,$sarTyCd){
	

			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 		$productname = $this->usermodel->populatealldataarray('products','code', $code,'companyid', $companyid);
	 
	 
	 	$inventorytype=$productname[0]['producttype'];

	 
	 
 if($inventorytype !="Service"){
	 
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
						   }											
							
						  
				$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
				  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);
$company_name=trim($configuration[0]["name"]);

	
	
	
	
	
	if($companyname ==""){
		$companyname=$company_name;
	}else{
		$companyname=$companyname;

	}
	
	if($krapin ==""){
			$krapin=$kra_pin;	

	}else{
	$krapin=$krapin;	
	}
	
		
        $currentDate = date('YmdHis');
        $currentDateSt = date('Ymd');

        // API endpoint URL
		
		if($onlineoffline=="OSCU"){
        $apiUrl = ''.$etimsurl.'/etims-api/insertStockIO';
			

			 }else{
			
			$apiUrl = $apiUrl = ''.$etimsurl.'/stock/saveStockItems';

			 }
			 
	 
			 // echo code;  
		//echo "iko";
		//exit;
		
		
		

	//$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'c', $branchid);
						 
	 
				$name=$productname[0]['name']; 
				$itemclassification=$productname[0]['itemclassification']; 
		  	$itemcode=$productname[0]['hscode'];
					  	$packagingunit =$productname[0]['packagingunit']; 
					  	$salesunit=$productname[0]['salesunit']; 
	   					  	$taxcode=$productname[0]['itemtax']; 			
								$buyingprice=$productname[0]['buyingprice'];
									$sellingprice=$productname[0]['sellingprice'];	
		$vatrate=$productname[0]['tax_included'];
		
		
		
		

        $taxableAmount = round(($sellingprice / (1 + ($vatrate / 100))), 2);
        $taxAmount = round(($sellingprice - $taxableAmount), 2);
		$TTtaxableAmount = round((($sellingprice / (1 + ($vatrate / 100))) * $qty), 2);
        $TTtaxAmount = round((($sellingprice - $taxableAmount)* $qty), 2);
		
		
$ttamount=$sellingprice * $qty;

        $itemtransfered = [
            [
                "itemSeq" => 1,
                "itemCd" => $itemcode,
                "itemClsCd" => $itemclassification,
                "itemNm" => $name,
                "bcd" => $code,
                "pkgUnitCd" => $packagingunit,
                "pkg" => (int)$qty,
                "qtyUnitCd" => $salesunit,
                "qty" => (int)$qty,
                "itemExprDt" => '',
                // "itemExprDt"=> $inventory->expiry_date->format('YmdHis'),
                "prc" => (int)$sellingprice,
                "splyAmt" => (int)$buyingprice,
                "totDcAmt" =>(int) $ttamount,
                "taxblAmt" => (int)$taxableAmount,
                "taxTyCd" => $taxcode,
                "taxAmt" =>(int) $taxAmount,
                "totAmt" => (int)$ttamount,
            ]
        ];
		
		
        $data = [
		  "tin" => $kra_pin,
           "bhfId" => $branch_id,
				
            "sarNo" =>(int) $sarNo,
            "orgSarNo" => $sarNo,
            "regTyCd" => "M",
            "custTin" => $krapin,
            "custNm" => $companyname,
            "custBhfId" => $branch_id,
            "sarTyCd" => $sarTyCd,
            "ocrnDt" => $currentDateSt,
			//"totItemCnt" => (int) $qty,

            "totItemCnt" => 1,
            "totTaxblAmt" => $TTtaxableAmount,
            "totTaxAmt" => $TTtaxAmount,
            "totAmt" => $ttamount,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin",
            "itemList" => $itemtransfered,

        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);

       // \Log::debug(' Stock transfer to send Etims.' . $jsonData);
        // return $jsonData;

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array(
                'tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
			
        if (curl_errno($ch)) {
           // echo 'cURL Error: ' . curl_error($ch);
            ///\Log::debug('eTIMS  Get Imported Items list Error.', curl_error($ch));
           // return $this->sendError('Error Getting Imported Item list.');
        } else {
            // Process the API response as needed
            //return $response;
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];

            //\Log::debug('ETIMS Response from STOCK I/O.', $responseArray);


            if ($resultCd == '000') {
                // Check if the decoding was successful
				
				
				}
				
				
				
				
				}






 }


	}		   
				
				
				
				
	
  
  
  
   	
  
  
   	function saveItemComposition($itemcode,$qty,$childcode)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
						   }											
							
				$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
				  
						  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

$apiUrl = ''.$etimsurl.'/etims-api/saveItemComposition';
 $data = [
            "itemCd" => $itemcode,
            "cpstItemCd" => $childcode,
            "cpstQty" =>(int) $qty,
            "regrId" => "Admin",
            "regrNm" => "Admin"
        ];
		// Convert the data to JSON format
        $jsonData = json_encode($data);
		$ch = curl_init();// Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);

					        // Check for cURL errors
            if (curl_errno($ch)) {


						
				
				
				
           } else {
				
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



						if ($resultCd == '000') {	
						
							$datasaved=1;
						}else {

							$datasaved=0;
						}							
					
		   
		
			}		   
										   
										   
						   
										   
						   
}					   
							   					   
						   
  
  
  
  
  
  
  
  
  
  
  
  
  	function addallpushedsms($mainmessage,$maincontact,$myview)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				
								$contact = htmlspecialchars(trim($maincontact));

		   	  $mymessage = trim($mainmessage);
			
				
				
				
				
				
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			
			 
			 
						   
				
					 
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
//$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 //redirect($myview);
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
			
			
			
						$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=".urlencode($from)."&mobile=$allcontacts";

			//$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=". urlencode($from)."&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
								// redirect($myview);
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
								// redirect($myview);
			}else{
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
								 //redirect($myview);

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  
  
  	 public function viewphoto() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];

	      $page = $_GET['page'];

     $itemid = $_GET['randomitemidentifier'];

   			        		$data['viewproducts'] = $this->usermodel->populateallarray('productlist','code', $itemid);

	$this->load->view("template/headerpagemin");

		
$data['page']=$page;
$data['itemid']=$itemid;
	$data['currencysymbol']=$currencysymbol;	
		 $this->load->view('userdata/viewphoto', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  	function pushedsmswithview($mainmessage,$maincontact,$myview)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				
								$contact = htmlspecialchars(trim($maincontact));

		   	  $mymessage = trim($mainmessage);
			
				
				
				
				
				
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			
			 
			 
						   
				
					 
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
//$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect($myview);
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
			
			
			
						$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=".urlencode($from)."&mobile=$allcontacts";

			//$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=" . urlencode($from) . "&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
								 redirect($myview);
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
								 redirect($myview);
			}else{
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
								 redirect($myview);

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  
  
  
  
   public function addsms__()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $contact = trim($this->input->post("contact"));

		   	  $mymessage = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			 
			 
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsms') == "sms")

					   {
						   
				
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		try{
				$url = 'http://sms.robisearch.com/sendsms.jsp?';
			$xml_data ='<?xml version="1.0"?><smslist><sms><user>'.$username.'</user><password>'.$password.'</password><message>'.$message.'</message><mobiles>'.$allcontacts.'</mobiles><senderid>'.$from.'</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid></sms></smslist>'; 

 
			$ch = curl_init($url);			
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
			curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
		
				$xml = new SimpleXMLElement($output);

			
			$code="error-code";
			$mydescription="error-description";
			$finalcode=$xml->error->$code;
			$description=$xml->error->$mydescription;
			if($finalcode== 0) {
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} catch (Exception $e) {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance or '.$e->getMessage(). '.Try again </div>');
						redirect('user/viewsms');		
				}
				
			
}
}
			
	if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewsms');
			
				
			}
			
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
public function addgroupsms()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		 			
		 		 $categoryid = $this->input->post("categoryid");

		   	  $message = $this->input->post("message")	;
			  		 $mymessage = htmlspecialchars($message);	

			 
			  		  $this->form_validation->set_rules("message", "message", "trim|required");
		$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			 	if ($this->input->post('btn_groupaddsms') == "oursms")

					   {
						  
			
			
			
		
			
			// $confirmgroups= $this->usermodel->confirmgroupsaccount($categoryid); 
			
			
			
			
	

		//$memberid=$row->memberid;
		//$viewmember = $this->usermodel->populatmyemember($memberid);
		
										//$viewmember = $this->usermodel->getgroupmembers($categoryid);










											$viewmember = $this->usermodel->getgroupmembers($categoryid);
											

					if(is_array($viewmember)) {

   foreach($viewmember as $c){
		
	   $mycontact=trim($c->phone) ; 
	   					   
						   
			 $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						  	   $countmessage =strlen($mymessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];

    // DONE!!! 
											$data=array(		
			'userid'=>$userid,
			
				'contact'=>$mycontact,
			
		  	'message'=>$mymessage,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);





		$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($mymessage) . "&shortcode=".urlencode($from)."&mobile=$mycontact";

			//$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=". urlencode($from)."&mobile=$allcontacts";










			
			
							//$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($mymessage) . "&shortcode=".urlencode($from)."&mobile=$mycontact";

				          //$finalURL = "https://sms.bulksmschapchap.com/api/Services/sendsms/?apikey=" . urlencode($mypassword) . "&partnerID=" . urlencode($myusername) . "&message=" . urlencode($mymessage) . "&shortcode=". urlencode($from)."&mobile=$mycontact";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";
				
				 if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 
				
				
				
				
				

			
			
				$usr_result = $this->usermodel->add($data,'sms');
				
				 $countmessage =strlen($mymessage);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
				
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			
				
				}else{
								//echo 'Error occurred during Sending Message: Please check on your internet connection or balance or ',  $e->getMessage(), "\n .Try again ";

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance..Try again</div>');
							redirect('user/viewsms');		
				}		
			
				

				}
	
	 
	 

}
	
			




								
		if($finalcode=="Success"){
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else  {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$mycontact .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}






								
								   }else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There is no any member who is active from the group you have selected.. Try again</div>');
								
								 redirect('user/viewsms');
										}
		
		
}else{
	redirect('login');	
	
	
}
}
	
	}
 
  
  
public function addgroupsms__()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		 			
		 		 $categoryid = $this->input->post("categoryid");
		 		 $smscategory = $this->input->post("smscategory");

		   	  $message = $this->input->post("message")	;
			  		 $mymessage = htmlspecialchars($message);	

			 
			  		  $this->form_validation->set_rules("message", "message", "trim|required");
		$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			 	if ($this->input->post('btn_groupaddsms') == "oursms")

					   {
						  
			
			
			
		
			
			// $confirmgroups= $this->usermodel->confirmgroupsaccount($categoryid); 
			
		
	

		//$memberid=$row->memberid;
		//$viewmember = $this->usermodel->populatmyemember($memberid);
		
										//$viewmember = $this->usermodel->getgroupmembers($categoryid);

										if($smscategory=="group"){
										$viewmember = $this->usermodel->getgroupmembers($categoryid);

										}else{
									$viewmember = $this->usermodel->getallmobileusers();

										
										}


					if(is_array($viewmember)) {

   foreach($viewmember as $c){
		
	   $mycontact= $c->phone ; 
	   					   
						   
			 $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						  	   $countmessage =strlen($mymessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$myusername=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$mypassword=$confirmsmsaccount_result[0]['password'];

    // DONE!!! 
											$data=array(		
			'userid'=>$userid,
			
				'contact'=>$mycontact,
			
		  	'message'=>$mymessage,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
$url = 'http://sms.robisearch.com/sendsms.jsp?';
$xml_data ='<?xml version="1.0"?><smslist><sms><user>'.$myusername.'</user><password>'.$mypassword.'</password><message>'.$mymessage.'</message><mobiles>'.$mycontact.'</mobiles><senderid>'.$from.'</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid></sms></smslist>'; 
//$xml = "<SendMessage><message id='292' sentdate='636742' message='$message' source='$allcontacts'/></SendMessage>";

 
 //$xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			$ch = curl_init($url);			
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
			curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
			try{
				
	
			$xml = new SimpleXMLElement($output);
			
			$code="error-code";
			$mydescription="error-description";
			$finalcode=$xml->error->$code;
			$description=$xml->error->$mydescription;
			if($finalcode== 0) {
				$usr_result = $this->usermodel->add($data,'sms');
				
				 $countmessage =strlen($mymessage);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }
				
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
				} catch (Exception $e) {
								//echo 'Error occurred during Sending Message: Please check on your internet connection or balance or ',  $e->getMessage(), "\n .Try again ";

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance..Try again</div>');
							redirect('user/viewsms');		
				}		
			
				

				}
	
	 
	 

}
	
			




								
if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewsms');
			
				
			}






								
								   }else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There is no any member who is active from the group you have selected.. Try again</div>');
								
								 redirect('user/viewsms');
										}
		
		
}else{
	redirect('login');	
	
	
}
}
	
	}
 
  
  
  
 
 

  
  public function addgroupsms1()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		 			
		 		 $categoryid = $this->input->post("categoryid");

		   	  $message = $this->input->post("message")	;
			  
			  $confirmgroups= $this->usermodel->confirmgroupsaccount($categoryid); 
			  		  $this->form_validation->set_rules("message", "message", "trim|required");
		$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			 	if ($this->input->post('btn_groupaddsms') == "oursms")

					   {
						  
			
			
			
					   	if($companyid==2){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>ALERT!</strong> You can not send group sms because you have note subcribe to unlimited/premium account. You are still using test account . You can contact us through :0780655987 or info@robisearch.com for full/unlimited (premium) account setup to enjoy more Services</div>');
							
								 redirect('user/viewsms');
								 return false;
								 
		}
			
			
			
			
			
			
			
			
			
				   	 	if ($confirmgroups != false)
								{
							
									
  
  	foreach ($confirmgroups as $row): 


$memberid=$row->memberid;
$viewmember = $this->usermodel->populatmyemember($memberid);
					
					if(is_array($viewmember)) {

   foreach($viewmember as $c){
			 
				 

              

	   $contact= $c->phone ; 
	   					   
						   
						   
						   	  $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						   	if($confirmaccount_result[0]['totalsms']<1){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$apikey=$confirmsmsaccount_result[0]['apikey'];
		    $gateway    = new AfricasTalkingGateway($username, $apikey);
		  try 
    { 
     
       $results = $gateway->sendMessage($contact, $message, $from);
                
      foreach($results as $result) {
       
				   
						   
												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$contact,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'sms');
				if ($usr_result ==TRUE) //active user record is present
							{
							$finaltotalsms=$totalsms-1;
								$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
	

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	
							//redirect('user/viewsms');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS  was not Sent.. Try again</div>');
								
								 //redirect('user/viewsms');
		}
      }
	  		 
  
    }
    catch ( AfricasTalkingGatewayException $e )
    {
    // SMS  not Sent to  ".  $recipients .".Error was Encountered  while sending SMS.: ".$e->getMessage().";
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS was not sent!   </strong>   Error was Encountered  while sending SMS.'.$e->getMessage().'.Check your balance or internet availability then try again</div>');
								
								 redirect('user/viewsms');
    }
    // DONE!!! 

}
	
	 
	 

}



} else {
    echo 'There is no member assigned to this group.';
}
					
	

endforeach;
								
if(isset($usr_result)){

 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Sent SMS..</div>');	

								
								 redirect('user/viewsms');
		

}else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS  was not Sent.. Try a different group</div>');
								
								 redirect('user/viewsms');
		
	
	
	
}






								
								   }else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> There is no any member who is active from the group you have selected.. Try again</div>');
								
								 redirect('user/viewsms');
										}
		
		
}else{
	redirect('login');	
	
	
}
}
	
	}
 
 
  
  public function allocaterequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $allocation = $this->input->post("allocation");
		 		 $allocationid = $this->input->post("allocationid");
		 		 $allocationinvoice = $this->input->post("allocationinvoice");
		 		 $amount = $this->input->post("amount");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");

		    		   	  $bankid = $this->input->post("bankname");

				    		   	  $paiddate = $this->input->post("paiddate");
				    		   	  $mode = $this->input->post("mode");
								    		   	  $transactioncode = $this->input->post("transactioncode");

								    		   	  $idno = $this->input->post("idno");

			  		  $this->form_validation->set_rules("allocation", "allocation", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewrequest', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateallocation') == "allocation")
					   {
						   $glaccounts = $this->usermodel->populateallarray('glaccounts','number', $bankid);
						 $availablebalance=$glaccounts[0]['amount'];
						 
						 $productlist = $this->usermodel->populateallarray('expenses','invoice', $allocationinvoice);
					$datespent=$productlist[0]['datespent'];

	$branchid=$productlist[0]['branchid'];
				$ourcompanyid=$productlist[0]['companyid'];
							$ttpaid=$productlist[0]['paid'];
							$expectedamount=$productlist[0]['amount'];
							$currentbalance=$expectedamount-$ttpaid;

						 /*	if($availablebalance < $amount){
								
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have less balance('.$availablebalance.'). Please bank more money first in this account and then try again.</div>');

								//	redirect($view);	
								//return false;

							}
							*/
							
								if($amount >  $currentbalance){
								
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The amount('.$amount.') you want to allocate is more than pending balance ('.$currentbalance.').. Please try allocate correct amount.</div>');

								redirect($view);	
							return false;

							}
								 $paidamount=$ttpaid+$amount;
							$finalbalance=$expectedamount-$paidamount;

									$nodata=array(		
			'updatedby'=>$userid,
			
				'allocation'=>$allocation,
				'balance'=>$finalbalance,

						'allocationtext'=>$description,
						'paid'=>$paidamount,

			
			'updatedat'=>$paiddate,

			
								);
							
							
												$data=array(		
			'updatedby'=>$userid,
			
				'allocation'=>$allocation,
				'balance'=>$finalbalance,

						'allocationtext'=>$description,
						'idno'=>$idno,
						'paid'=>$paidamount,

			
			'updatedat'=>$paiddate,

			
								);
										


										if($idno!=""){
							$usr_result = $this->usermodel->updatedata($data,'expenses','id',$allocationid);

									}else{
							$usr_result = $this->usermodel->updatedata($nodata,'expenses','id',$allocationid);
	
									}
														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								  
			  	 
				
	
		

					  	 
							
						 
	 $finalbalance=$availablebalance-$amount;
		
			$bankdata=array('amount'=>$finalbalance,);
												
			  
			 $creditdata=array( 'userid'=>$userid,'mode'=>$mode,'account'=>$bankid,'credit'=>$amount,'description'=>$description,'code'=>$allocationinvoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $ourcompanyid,'type'=> "expense",'transactioncode'=>$transactioncode);

			$main_result = $this->usermodel->add($creditdata,'debitcredit');
								
				
							if ($main_result ==TRUE)
							{			
								$this->usermodel->updatedata($bankdata,'glaccounts','number',$bankid);

							$myrequestedproducts =$this->usermodel->populateall('statement','invoice',$allocationinvoice);
			
if(is_array($myrequestedproducts)) {

   foreach($myrequestedproducts as $row)
   {

   $bankname=trim($row->account);
    $mybranch=trim($row->branchid);
	 $myamount=trim($row->amount);
	  $mycompanyid=trim($row->companyid);
	  
	  			  $nextglaccounts = $this->usermodel->populateallarray('glaccounts','number', $bankname);
					 $nextavailablebalance=$nextglaccounts[0]['amount'];
	 $nextfinalbalance=$nextavailablebalance+$myamount;
	 
	 
	  
	  	$debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$myamount,'description'=>"Expense",'code'=>$allocationinvoice,'crateddate'=>$datespent,'branch' => $mybranch,'companyid'=> $mycompanyid,'balance'=> $nextfinalbalance);



							$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
	  
	  
	  
	  
   }
}
							}							
								
								
								
								
								
								
								
								
								
								
								
								// $this->usermodel->add($addapprovalsdata,'approvals');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }


 
   public function approverequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $aprrovalid = $this->input->post("aprrovalid");
		 		 $aprrovalinvoice = $this->input->post("aprrovalinvoice");
		   	  $approval = $this->input->post("approval");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");

		    
		
				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewrequest', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateapproval') == "approval")
					   {
												$data=array(		
			'updatedby'=>$userid,
			
				'status'=>$status,
			
			
			
			'updatedat'=>$dateposted,

			
								);
											$addapprovalsdata=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
			'description'=>$description,

				'invoice'=>$aprrovalinvoice,
			'applicationid'=>$aprrovalid,

								);
							$usr_result = $this->usermodel->updatedata($data,'expenses','id',$aprrovalid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 $this->usermodel->add($addapprovalsdata,'approvals');

   if($approval!="No"){
	   	$Expense=$this->usermodel->populateallarray('expenses','id', $aprrovalid);
		$finalamount=$Expense[0]['amount'];
		$applicantid=$Expense[0]['userid'];
		$mydate=$Expense[0]['dateposted'];
   $correctime = date("d/m/Y H:i", strtotime($mydate));
	 $correctamount= $this->MyformatMoney($finalamount, true);
		
	   			$applicant=$this->usermodel->populateallarray('people','id', $applicantid);
		$applicantname=$applicant[0]['firstname'];
		
			$appriver=$this->usermodel->populateallarray('people','id', $userid);
		$apprivername=$appriver[0]['firstname'];
		
		
							$mycustomer=$this->usermodel->populateallarray('people','id', $approval);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];


	   
	   	$message="Dear ".$firstname.", ".$applicantname." applied for ". $correctamount." on ". $correctime ." and has been ". $status ." by ".$apprivername." Check your erp for action.";

  
														
													
									$myview=$view;				  
		  $this->addallpushedsms($message,$contact,$myview);	
							
	   
	   
   }












						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }

   public function approvedispatch()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $aprrovalid = $this->input->post("aprrovalid");
		 		 $aprrovalinvoice = $this->input->post("aprrovalinvoice");
		   	  $approval = $this->input->post("approval");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");

		    
		
				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbulkdispatch', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateapproval') == "dispatch")
					   {
						   
						     if($approval!="No"){
																	$data=array(		
			'approvedby'=>$userid,
			
				'remarks'=>$status,
							'name'=>$approval,

			
			
			'dateapproved'=>$dateposted,

			
								); 
								 
								 
							 }else{
								 
								 
																$data=array(		
			'approvedby'=>$userid,
			
				'remarks'=>$status,
			
			
			
			'dateapproved'=>$dateposted,

			
								);	 
								 
							 }
			
											$addapprovalsdata=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
			'description'=>$description,

				'invoice'=>$aprrovalinvoice,
			'applicationid'=>$aprrovalid,

								);
							$usr_result = $this->usermodel->updatedata($data,'bulkdispatch','id',$aprrovalid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 $this->usermodel->add($addapprovalsdata,'approvals');

   if($approval!="No"){
	   	$Expense=$this->usermodel->populateallarray('bulkdispatch','id', $aprrovalid);
		//$finalamount=$Expense[0]['amount'];
		$applicantid=$Expense[0]['userid'];
		$mydate=$Expense[0]['createdate'];
   $correctime = date("d/m/Y H:i", strtotime($mydate));
	// $correctamount= $this->MyformatMoney($finalamount, true);
		
	   			$applicant=$this->usermodel->populateallarray('people','id', $applicantid);
		$applicantname=$applicant[0]['firstname'];
		
			$appriver=$this->usermodel->populateallarray('people','id', $userid);
		$apprivername=$appriver[0]['firstname'];
		
		
							$mycustomer=$this->usermodel->populateallarray('people','id', $approval);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];


	   
	   	$message="Dear ".$firstname.", ".$applicantname." applied for items  on ". $correctime ." and has been ". $status ." by ".$apprivername." Check your erp for action.";

  
														
													
									$myview=$view;				  
		  $this->addallpushedsms($message,$contact,$myview);	
							
	   
	   
   }












						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }
  public function approveporequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $aprrovalid = $this->input->post("aprrovalid");
		 		 $aprrovalinvoice = $this->input->post("aprrovalinvoice");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");
		 		  $approvedby = $this->input->post("approvedby");

		
				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/allpurchaseorder', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatepoapproval') == "approval")
					   {
												$data=array(		
			'updatedid'=>$approvedby,
						'controller'=>$approvedby,

				'approvalstatus'=>$status,
			
						'description'=>$description,

			
			'updateddate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'purchaseorder','id',$aprrovalid);
							//$usr_result = $this->usermodel->updatedata($data,'purchaseorder','id',$approvedby);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								// $this->usermodel->add($addapprovalsdata,'approvals');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }

public function approvetillcollection()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $aprrovalid = $this->input->post("aprrovalid");
		 		 $aprrovalinvoice = $this->input->post("aprrovalinvoice");

		   	  $remarks = $this->input->post("remarks");
			  		   	  $view = $this->input->post("view");
		 		  $approvedby = $this->input->post("approvedby");

		
				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtill', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetillapproval') == "approval")
					   {
												$data=array(		
			'approvedby'=>$approvedby,

				'status'=>$status,
			
						'remarks'=>$remarks,

			
			'collecteddate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'tillcollection','id',$aprrovalid);
							//$usr_result = $this->usermodel->updatedata($data,'purchaseorder','id',$approvedby);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								// $this->usermodel->add($addapprovalsdata,'approvals');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the till status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Till status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }


 
  public function approvemyrequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 $sendsms = $this->input->post("sendsms");

		 		 $status = $this->input->post("status");
		 		 $aprrovalid = $this->input->post("aprrovalid");
		 		 $aprrovalinvoice = $this->input->post("aprrovalinvoice");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");
		 		  $approvedby = $this->input->post("approvedby");
 $applicantid = $this->input->post("applicantid");

				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/allpurchaseorder', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatepoapproval') == "approval")
					   {
						   
						
					$oldcomments= $this->usermodel->populateallarray('quotation','id',$aprrovalid);




				$oldtext=$oldcomments[0]["description"];   
						   
    if($oldtext !=""){
		
		$description=$oldtext." </br>".$description;
						   
	}		   
						   
												$data=array(		
			'updatedid'=>$approvedby,
						'approvedby'=>$approvedby,

				'status'=>$status,
			
						'description'=>$description,

			
			'updateddate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'quotation','id',$aprrovalid);
							//$usr_result = $this->usermodel->updatedata($data,'purchaseorder','id',$approvedby);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								if($sendsms=="yes"){	
							$correctime = date("d/m/Y H:i", strtotime($dateposted));
				
								
  //$quotationdata = $this->usermodel->populateallarray('quotation','id',$itemid);
//$applicantid=$quotationdata[0]["userid"];
								
	
$finalcomment="";
  $mycustomer=$this->usermodel->populateallarray('people','id', $applicantid);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];

			$leavestatus=$status;
						   			$message="Dear ".$firstname.", a request has been ". $leavestatus.".on: ". $correctime ." Comments are:  ". $description.".Check the system for details.";
  						   			//$message="Dear ".$firstname.", Your request has been ". $leavestatus." on ". $correctime .".Check the system for details.";
		  $this->addallpushedsms($message,$contact,$view);
								
								}
								

								// $this->usermodel->add($addapprovalsdata,'approvals');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }
 
  
  public function updateaccountabilityrequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $accountid = $this->input->post("accountid");
		 		 $accountinvoice = $this->input->post("accountinvoice");

		   	  $description = $this->input->post("description");
			  		   	  $view = $this->input->post("view");
		   	  $idno = $this->input->post("idno");

		    
		
				
			  		  $this->form_validation->set_rules("status", "Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewrequest', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateaccountability') == "accountability")
					   {
						   
						   					$nodata=array(		
			'updatedby'=>$userid,
			
				'invoicestatus'=>$status,

			
			
			'updatedat'=>$dateposted,

			
								);
												$data=array(		
			'updatedby'=>$userid,
			
				'invoicestatus'=>$status,
							'idno'=>$idno,

			
			
			'updatedat'=>$dateposted,

			
								);
											$addapprovalsdata=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
			'description'=>$description,

				'invoice'=>$accountinvoice,
			'applicationid'=>$accountid,

								);
									if($idno!=""){
																	$usr_result = $this->usermodel->updatedata($data,'expenses','id',$accountid);

									}else{
																$usr_result = $this->usermodel->updatedata($nodata,'expenses','id',$accountid);
	
									}

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 $this->usermodel->add($addapprovalsdata,'approvals');

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the accountability status to '.$status.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The accountability status was not updated to '.$status.'. Try again.</div>');	
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect($view);																
					   }
	    }
    }


 
 
  public function updateproductcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 			$data['branchid'] = $session_data['branchid'];
	  $branchid = $data['branchid'];
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");
			  		   	  $type = $this->input->post("type");

		    
		   	  $commission = $this->input->post("commission");
			  		   	  $shipping = $this->input->post("shipping");
			  		   	  $status = $this->input->post("status");
			  		   	  $imgid = $this->input->post("imgid");

		

			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatecategory') == "category")
					   {					  
	 $file= trim($_FILES["photo"]['name']);
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'status'=>$status,
				'type'=>$type,

			'createdate'=>$dateposted,
				'maincategory'=>$maincategory,
			'commission'=>$commission,
				'shipping'=>$shipping,

								);
																	$dataimg=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'status'=>$status,
				'type'=>$type,

			'createdate'=>$dateposted,
				'maincategory'=>$maincategory,
			'commission'=>$commission,
				'shipping'=>$shipping,
								'imgid'=>$imgid,

								);
	if($file!=""){
							$usr_result = $this->usermodel->updatedata($dataimg,'productcategory','id',$mycategoryid);

					}else{
												$usr_result = $this->usermodel->updatedata($data,'productcategory','id',$mycategoryid);
	
						
					}

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										
			
					if($file!=""){
																$this->uploadimages($imgid,$companyid,$branchid,$userid);

					}
								
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the product category..</div>');	
							redirect('user/viewproductcategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> product Category  was not Updated.. Try again</div>');
								
								 redirect('user/viewproductcategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


 
  public function updateuom()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $code = $this->input->post("code");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateuom') == "uom")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				'code'=>$code,
			
								);
							$usr_result = $this->usermodel->updatedata($data,'uom','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the UOM.</div>');	
							redirect('user/viewuom');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> UOM   was not Updated.. Try again</div>');
								
								 redirect('user/viewuom');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  public function updateitemreturn()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $description= $this->input->post("description");

		   	  $invoice = $this->input->post("invoice");
			  		   	  $view = $this->input->post("view");
			  		   	  $myid = $this->input->post("myid");

		    
		
				
			  		  $this->form_validation->set_rules("invoice", "Invoice no", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatereturn') == "return")
					   {
												$data=array(		
			'updatedby'=>$userid,
			
			
		  	'description'=>$description,
			
			'updatedat'=>$dateposted,
			
								);
							$usr_result = $this->usermodel->updatedata($data,'sales_order','id',$myid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted a return comment.</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The return comments was could not be posted.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
 
  public function updatetabletransfer()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $mytable= $this->input->post("mytable");
		 		 $newtable = $this->input->post("newtable");

		   	  $invoice = $this->input->post("invoice");
			  		   	  $view = $this->input->post("view");

		    
		
				
			  		  $this->form_validation->set_rules("invoice", "Invoice no", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($view, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetransfer') == "transfer")
					   {
												$data=array(		
			'updatedby'=>$userid,
			
			
		  	'mytable'=>$newtable,
			
			'updatedat'=>$dateposted,
			
								);
							$usr_result = $this->usermodel->updatedata($data,'sales','invoice',$invoice);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully transfered  the bill to table number no:'.$newtable.'</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The table was could not be transfred.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
		
	public function posttransferdeals()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $dealowner= $this->input->post("dealowner");
		 		 $newowner = $this->input->post("newowner");
		   	  //$newid = $this->input->post("newid");

		   	  $fromdate = $this->input->post("fromdate");
			  $todate = $this->input->post("todate");

		    	 $frotime="00:00:00";
	  $totime="23:59:59";
	  	  	   $fromdate=$fromdate." ".$frotime;
			  	  	   $todate=$todate." ".$totime;

				
			  		  $this->form_validation->set_rules("dealowner", "Deal owner ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view("userdata/transferdeals", $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetransfer') == "transfers")
					   {
												$data=array(		
		
			
			
								);
		$usr_result = $this->usermodel->updatedealtransfer($dealowner,$newowner,$fromdate,$todate,$companyid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
						$this->usermodel->updatefollowuptransfer($dealowner,$newowner,$fromdate,$todate,$companyid);
	
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully transfered  the deals :'.$tablename.'</div>');	
							redirect("user/transferdeals");																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The deals  could not be updated. Check on the column name or there was no records to be updated.. Try again</div>');
								
							redirect("user/transferdeals");																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
	
	
	
	
	
	
	
	
	
	public function updateaccount()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $tablename= $this->input->post("tablename");
		 		 $oldid = $this->input->post("oldid");
		   	  //$newid = $this->input->post("newid");

		   	  $newid = $this->input->post("newid");
			  		   	  $column = $this->input->post("column");

		    
		
				
			  		  $this->form_validation->set_rules("tablename", "table name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view("userdata/bulkupdate", $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetables') == "tables")
					   {
												$data=array(		
			$column=>$newid,
			
			
								);
		$usr_result = $this->usermodel->updatedatabytwo($data,$tablename, $column,$oldid,'companyid',$companyid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated  the table :'.$tablename.'</div>');	
							redirect("user/bulkupdate");																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The table was could not be updated. Check on the column name or there was no records to be updated.. Try again</div>');
								
							redirect("user/bulkupdate");																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  public function updatepayments()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
		$data['branchid'] = $session_data['branchid'];
	  $branchid = $data['branchid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$exactime =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 $mytable = $this->input->post("mytable");

		 		 $invoice = $this->input->post("invoice");
		 		  $mpesa = $this->input->post("mpesa");		  
	  	        $cheque = $this->input->post("cheque");		  
	            $card = $this->input->post("card");	
		    	$voucher = $this->input->post("voucher");	
		    	$cash = $this->input->post("cash");	
				
					$move = $this->input->post("move");	
									$type = $this->input->post("type");	
									$paymentstatus = $this->input->post("paymentstatus");	

										$creditnote = $this->input->post("creditnote");	

		      $credit = $this->input->post("credit"); 
			  		      $points = $this->input->post("points"); 
			  			  		      $total = $this->input->post("total"); 
			  			  		      $myid = $this->input->post("myid"); 
		    		    	$cashier = $this->input->post("cashier");	
	$description = $this->input->post("description");	
		    		    	$balance = $this->input->post("change");	
		    		    	$view = $this->input->post("btn_updatepaymetmode");	
							$dateposted = $this->input->post("dateposted");	
		    		    	$customer = $this->input->post("customer");	
		    		    	$maindiscount = $this->input->post("maindiscount");	
$othercurrencyamount = $this->input->post("othercurrencyamount");	
		    		    	$othercurrency = $this->input->post("othercurrency");	

		  $receiveoverpayment=$this->usermodel->populatuserpermissionsdataarray('income','receiveoverpayment',$userid);


			  		  $this->form_validation->set_rules("myid", "Receipt Id amount", "trim|required");

			  	$entermpesacode=$this->usermodel->populatuserpermissionsdataarray('sales','entermpesacode',$userid);
				

			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/changepayment', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatepaymetmode'))
					   {
						   
						   
						  		  
			$finalbalance=0;

			$mytotal=$cash+$mpesa+$voucher+$cheque+$points+$card+$credit+$creditnote+$maindiscount;
			 
			 $finalbalance= (($mytotal-$total)); 
						   
						   	
							
							
								if(($type=="Invoice") && ($customer =="")){
								
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sorry. You can not update this sale. You can not clear credit sales without selecting customer first.Try again</div>');
								
								 redirect('user/changepayment?invoice='.$invoice);
								
								return false;
							}
							
//

			
if($receiveoverpayment == true){
	
	
}else{
	



							if($finalbalance!=0){
								
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Total money paid ('.$mytotal.') can not be less or more than the expected amount ('.$total.') Try again</div>');
								
								 redirect('user/changepayment?invoice='.$invoice);
								
								return false;
							}
}		
		
								$mpesastatus="";
								$mpesaid="";
				if(($cashier !="") && ($type=="Mpesa") ){
	
//
						   		$mpesaresult = $this->usermodel->populateallarray('sms_in','code', $cashier);
		
		if ($entermpesacode !=true){
		
			if($mpesaresult==false){
								
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That code does not exist.Try again</div>');
								
								redirect('user/changepayment?invoice='.$invoice);
								
							return false;
							}
							
				}
					
	
		
		
		
		
		
		
		
		
		
		if($mpesaresult!=FALSE){
			
			
			
			
			
			
				
		if ($entermpesacode !=true){
			$mpesaamount=$mpesaresult[0]['amount'];
			if($mpesaamount !=$mpesa){
								
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The mpesa  code is not equalt to the amount captured.Try again</div>');
								
								redirect('user/changepayment?invoice='.$invoice);
								
							return false;
							}
							
				}
					
			
			
			
			
			
					$mpesaid=$mpesaresult[0]['id'];
					
			$paymentstatus="Cleared";
			$mpesastatus="1";
					
		}else{
			$paymentstatus=	$paymentstatus;
			$mpesastatus="0";
		}
	//$mpesa=$mpesaresult[0]['amount'];
  
	//oruani
	
}		
$finalmpesa=0;
$finalcash=0;		   
						   
					if($move=="yes"){
$finalmpesa=$cash;
$finalcash=0;
					}else{
						$finalmpesa=$mpesa;
					$finalcash=$cash;
						
					}		






				$ordersales="";	
			if($paymentstatus=="Cleared"){
			
			$ordersales="printed";
		}else{
			$ordersales="new";
		}			


if($cash > $total){
$finalcash=$total;
}	



//





						   
												$data=array(		

				'othercurrency'=>$othercurrency,
			 'othercurrencyamount' => $othercurrencyamount,  
				
			
			 	'companyid'=>$companyid,
			 'paymentstatus' => $paymentstatus,   

		  'mpesa' => $finalmpesa,    
		     'cheque' => $cheque,  
		     'card' => $card, 
			   'voucher' => $voucher, 
			   'credit' => $credit, 
					   'points' => $points,
								   'cash' => $finalcash,
								   'balance' => $balance,
							 'cashier' => $cashier,
							  'description' => $description,
		    		     'dateposted' => $dateposted,
						 				'ordersales'=>$ordersales,

						 		    		     'maindiscount' => $maindiscount,
						      'mytable' => $mytable,

						      'total' => $total,
		    		     'customer' => $customer,
		    		     'type' => $type,
 'creditnote' => $creditnote,

	'updatedby'=>$userid,
			'updatedat'=>$exactime,
						   
								);
							$usr_result = $this->usermodel->updatedata($data,'sales','id',$myid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
								    		    	$houseno = $this->input->post("houseno");
																				
												if($houseno !=""){
													
													
																	$roomsdata=array(		
			'updatedby'=>$userid,
			
			'updatedat'=>$dateposted,
				'status'=>$paymentstatus,
			
								);
		$this->usermodel->updatedata($roomsdata,'roomsales','invoice',$invoice);

										}	
								
								
								
								
								
								
								
								
								if($creditnote>0){
									if($customer>0){
										$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
									
				

			
								$finalcustomerbalance=$supplierbalance-$creditnote;
	
			
				
				
				
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
							'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
									}
									
									
								}
										if($mpesaresult!=FALSE){
														$paymentdata=array(		
					'id'=>$mpesaid,
			
					'used'=>$mpesastatus,
		
						   
					  	);
							$this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

								
								
											$mpesadata=array(		
			'userid'=>$userid,
			
				'code'=>$cashier,
			
		  	'branch'=>$branchid,
				 'companyid'=>$companyid,
				'type'=>"Sales paid",
				 	'amount'=>$finalmpesa,
			'dateposted'=>$dateposted,
				'paymentstatus'=>$paymentstatus,
			
								);
							 $this->usermodel->add($mpesadata,'mpesasales');
								
								
								
								
								
											}
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the sales..</div>');	
								 redirect($view);
								 
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The sales   was not updated.May be you have not changed any value. Try again</div>');
								
								 redirect('user/changepayment?invoice='.$invoice);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updateproject()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $invoice = $this->input->post("invoice");

		    			  		   	  $category = $this->input->post("category");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproject') == "project")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
							'category'=>$category,

		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'invoice'=>$invoice,

			'createdate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'projects','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the branch category..</div>');	
							redirect('user/viewprojets');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Branch   was not Updated.. Try again</div>');
								
								 redirect('user/viewprojets');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 

  public function createprojecttask()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 $taskid = $this->input->post("taskid");

		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $invoice = $this->input->post("invoice");
			  		   	  $year = $this->input->post("year");
			  		   	  $todate = $this->input->post("todate");
			  		   	  $fromdate = $this->input->post("fromdate");

		    			  		   	  $category = $this->input->post("category");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_createtaskproject') == "project")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
				'category'=>$category,

		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'invoice'=>$invoice,
						 	'taskid'=>$taskid,

			'createdate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->add($data,'projectstask');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully created task for this project..</div>');	
							redirect('user/viewprojets');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The task for this project  was not saved.. Try again</div>');
								
								 redirect('user/viewprojets');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 

  public function copyproject()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $invoice = $this->input->post("invoice");
			  		   	  $year = $this->input->post("year");
			  		   	  $todate = $this->input->post("todate");
			  		   	  $fromdate = $this->input->post("fromdate");

		    			  		   	  $category = $this->input->post("category");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateproject') == "project")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
				'category'=>$category,

		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'invoice'=>$invoice,

			'createdate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->add($data,'projects');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
						        		$LATEST = $this->usermodel->last_recordproject($companyid);
									$latestid=$LATEST[0]["id"];		
								$finallastid=$latestid+1;

   $query=$this->usermodel->populateall('projectsbudget','projectid', $mycategoryid);
									

		   
						   
if(is_array($query)) {

$insertdata = array();
   foreach($query as $row){
	     
		
	  
	  	$insertdata[]=array(		
						
				 	'userid'=>$userid,
			
				'code'=>$row->code,
				'expamount'=>$row->month,
				'createdate'=>$fromdate,
				'year'=>$year,
				'month'=>$row->month,
				'companyid'=>$companyid,

				'todate'=>$todate,
				 'projectid'=>$finallastid,
				'expamount'=>$row->expamount,




//

				'branch'=>$row->branch,
				'updatedby'=>$row->updatedby,
				'description'=>$row->description,
				//'qty'=>$row->qty,
				'uom'=>$row->uom,
				'usedqty'=>$row->usedqty,
				'balanceqty'=>$row->balanceqty,


				


											);
											
	  
	  
	  
	  
	  
	  
	  
	  
   
   }
   
   
   $this->db->insert_batch('projectsbudget', $insertdata); 

   
   
   
        if($this->db->affected_rows() > 0)
								{
		
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully copied the budget    ..</div>');	
							redirect("user/viewmybudget?randomitemidentifier=".$finallastid."&type=receiving");																
							}else {
							   

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Budgets were not uploaded into the system.. Try again</div>');

							redirect("user/viewmybudget?randomitemidentifier=".$finallastid."&type=receiving");																
							}
   
   
}


								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the branch category..</div>');	
							redirect('user/viewprojets');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Branch   was not Updated.. Try again</div>');
								
								 redirect('user/viewprojets');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updatechargesforplots()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("categoryid");

		   	  $description = $this->input->post("description");
			  		   	  $priority = $this->input->post("priority");


		
				
			  		  $this->form_validation->set_rules("name", "Charge name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('pmsdata/allapaymentcharges', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatecharges') == "charges")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'priority'=>$priority,
		

		
			
								);
								
							$usr_result = $this->usermodel->updatedata($data,'charges','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							


								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the charges..</div>');	
							redirect('admin/viewallpaymentcharge');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges   was not Updated.. Try again</div>');
								
								 redirect('admin/viewallpaymentcharge');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 

  public function updatebranch()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $invoice = $this->input->post("invoice");
			  		   	  $status = $this->input->post("status");

		    			  		   	  $currency = $this->input->post("currency");

		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatebranch') == "branch")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'invoice'=>$invoice,
			'currency'=>$currency,
			'status'=>$status,

			'updatedate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'branch','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							


 $file= $_FILES["logo"]['name'];


if($file!=""){
		
		$config['upload_path'] = is_dir($file).'uploads/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('logo')) {               
             $this->data['error'] = $this->upload->display_errors();
            
        } else {
			
        $this->db->set('logo',$new_name );
         $this->db->where('id', $mycategoryid);
         $this->db->update('branch');
        
        }  


}
	











							
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the branch category..</div>');	
							redirect('user/viewbranch');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Branch   was not Updated.. Try again</div>');
								
								 redirect('user/viewbranch');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  public function updatetable()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewtables', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatetable') == "updatetable")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'tables','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the table Number category..</div>');	
							redirect('user/viewtables');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Table Number   was not Updated.. Try again</div>');
								
								 redirect('user/viewtables');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updatemessage()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $maincategory = $this->input->post("maincategory");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatemessage') == "updatemessage")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'message','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the message category..</div>');	
							redirect('user/viewmessage');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Message   was not Updated.. Try again</div>');
								
								 redirect('user/viewmessage');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 	public function closesquotationtatus()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice = $_GET['randomitemidentifier'];
	 		

	  $status = $_GET['status'];
	  $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	$data['id'] = $session_data['id'];
			
		 $userid = $data['id'];		
		 
		
							
 
 
 
 $customerbalance=array(		
			
				'deliverydate'=>"Completed",
							'branchid'=>$userid,
'updateddate'=>$dateposted,
								);
		$usr_result= $this->usermodel->updatedata($customerbalance,'quotation','invoice',$invoice);
				
		

	
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> Your Data was successfully Saved..</div>');


								
							redirect("user/viewnewquotation?randomitemidentifier=".$invoice);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your Data was not successfully Saved. Try again</div>');
								
							redirect("user/allquatation");																
							}		
			
	}
	
	}
	

 
 
 	public function updatereceivedeals()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	 		

	  $status = $_GET['status'];
	  $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	$data['id'] = $session_data['id'];
			
		 $userid = $data['id'];		
		 
		 
		 $finalcustomerbalance=0;
				$peopleid="";
				
     $purchaseorder = $this->usermodel->populateallarray('purchaseorder','invoice',$invoice_number);
	 
	 
									$vatrate=$purchaseorder[0]["vatrate"];
									$oldtotal=$purchaseorder[0]["amount"];
									$oldpoaid=$purchaseorder[0]["paid"];
									$supplier=$purchaseorder[0]["supplier"];
									$transactionstatus=$purchaseorder[0]["transactionstatus"];

									$projectname=$purchaseorder[0]["status"];
									$deliverydate=$purchaseorder[0]["deliverydate"];

									
									
									$people = $this->usermodel->populateallarray('people','id',$supplier);
									$supplierbalance=$people[0]["supplierbalance"];
									$peopleid=$people[0]["id"];
			
				
								
																	$fromdate=$purchaseorder[0]["deliverydate"];

								
		 $userid = $data['id'];

		if($status=="suspended"){

		$finaltotalamount=0;
	        		$myreceivedproducts = $this->usermodel->populateall('newstock','invoice_number', $invoice_number);

	  	if(is_array($myreceivedproducts)){
	 
	 foreach ($myreceivedproducts as $c){
		  $transactionid=$c->id;
		 	 $itemid=$c->item_id;
			  $totalqty=$c->total;
		 $myproducts=$this->usermodel->getallproductbyid($itemid);
		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
		
   $finalqty=($availableqty+$totalqty);
	
		 	 $this->usermodel->deletedata($transactionid,"id","newstock");

		 //$usr_result = $this->usermodel->deletedata($invoice_number,"invoice_number","newstock");
		 $productdata=array(		
												'qty'=>$finalqty,
													);
								
								$usr_result = 	 $this->usermodel->updateproduct($productdata,$mycode); 
		 
	 }
		}
if($usr_result){
	
	
	
				$myoldbalance=$oldtotal-$oldpoaid;
				

			
								$finalcustomerbalance=$supplierbalance-$myoldbalance;
	
			
				
				
				
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
							'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
			
	
	
	
	
	
	
				//$this->usermodel->deletedata($invoice_number,"code","debitcredit");
				$this->usermodel->deletedatatwo("debitcredit","code",$invoice_number,"type <>","payment");
			//$this->usermodel->deletedatafour("debitcredit","code",$invoice_number,"type <>","Supplier Credit Note","type <>","supplier payment");

	
	
	
	$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully suspended the invoice.</div>');	
		redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);

}else{
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The invoice  was not suspended.. Try again</div>');
	redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);
	
}

		
}else{
	

	  $vat=0;
		  $taxable=0;
		  	 	
$currentfinalamount=0;
	  $ttvat=0;
		  $tttaxable=0;
		
		if($status=="closed"){




		$myclosedproducts = $this->usermodel->accountinginventory($invoice_number);
		//echo count($myclosedproducts);
		//exit;
	  	$accountfinaltotalamount=0;
		if(is_array($myclosedproducts)){
				//$this->usermodel->deletedata($invoice_number,"code","debitcredit");
				
								$this->usermodel->deletedatafour("debitcredit","code",$invoice_number,"type <>","Supplier Credit Note","type <>","supplier payment");

	$finaltotalamount=0;
		$ttdiscount=0;

		$ttqtys=0;
	 $insertdata = array();
$assetaccount="";
	 foreach ($myclosedproducts as $row){
		 		  $vattype=$row->tax;
		 		   $myid=$row->id;
				  $ttdiscount= (float)$ttdiscount + (float)$row->discount;
  
				$countserial = $this->usermodel->countserial($myid);
				
				
				
				
				if(($countserial > 0) && ($countserial != $row->total)){
					
					
					
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not complete this purchase. The number of serials captured ('.$countserial.')  are not the same as original quantities ('.$row->total.') recorded... Try again</div>');
	redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);
	return false;
				}
			
				  
$ttqtys=$ttqtys+$row->total;
		 
		  $myyqty=$row->total;
		 	 $myytotal=$row->buyingprice;
			  $currenttotal=($myyqty*$myytotal);
		$finaltotalamount=$finaltotalamount+ $currenttotal;
		
		
		 $transactionid=$row->id; 
		 
		 $accountcode = $this->usermodel->populateallarray('products','code', $row->item_id);
					$myassetaccount=$accountcode[0]['assetaccount'];
					 					   
if($finaltotalamount < 0){
			$currentfinalamount=(-1*$finaltotalamount);
		}else{
		$currentfinalamount=$finaltotalamount;	
		}
		$currentfinalamount=$currentfinalamount-$ttdiscount;
		//
		 		
	 //$assetaccount=$row->assetaccount;
 if($myassetaccount!=""){ $assetaccount=$myassetaccount;}else{ $assetaccount=1110; }

		
		
			

			
					$mytotals=0;
			
			if($currenttotal < 0){
			$mytotals=(-1*$currenttotal);
		}else{
								$mytotals=$currenttotal;

		}
		$mytotals=$mytotals-(float)$row->discount;
							
							if($projectname=="creditnote"){
															$insertdata[]=array( 'userid'=>$userid,'account'=>$assetaccount,'credit'=>$mytotals,'description'=>"Inventory Returned",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Purchases",'refno'=> $row->item_id,'supplier'=> $supplier);

							}else{
														$insertdata[]=array( 'userid'=>$userid,'account'=>$assetaccount,'debit'=>$mytotals,'description'=>"Inventory Purchased",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Purchases",'refno'=> $row->item_id,'supplier'=> $supplier);
	
							}


//$creditdata=array( 'userid'=>$userid,'account'=>$mybank,'credit'=>$myytotal,'description'=>$mydescription,'code'=>$invoice_number,'crateddate'=>$datespent,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'refno'=> $transactionid);

							//$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							//$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
		
		
		
		if($vattype=="VATABLE"){
								  $mytax=1+($row->vatrate/100); 
								  
								  
								  
								  
								 $myytotal=((float)$myytotal-((float)$row->discount/(float)$myyqty));
								 
								 $vatable=((float)$myytotal/(float)$mytax);
								 $myfinaltax=(($myytotal-$vatable));
								
								 $finaltax= $this->formatMoney(($myfinaltax*$myyqty), true);
								$vatable= $this->formatMoney(($vatable*$myyqty), true);


							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
							  $vat=$finaltax;
						      $taxable=$vatable;
							  
							  	  $ttvat=$ttvat+$finaltax;
							 $tttaxable=$tttaxable+$vatable;
							  
										$updatevatdata=array(		
			
				'vat'=>$finaltax,
				'taxable'=>$vatable,
			
								);
		 $this->usermodel->updatedata($updatevatdata,'newstock','id',$myid);

							  
							  
							  //
	
	 
	 
	 
	 
	 //
	 
	 
	 
	 
	 
		}
		
		  $finaltotalamount=(round($finaltotalamount)) ;
		
		

			
				
				
				
				
		$myreturnedproducts = $this->usermodel->returnedinventory($invoice_number);
	 	$returnedfinaltotalamount=0;
		if(is_array($myreturnedproducts)){

	 foreach ($myreturnedproducts as $row){
		 
		 $correctqty=$row->total;
		 	 $mybuyingprice=$row->buyingprice;
			  $ttcurrentamount=$correctqty*$mybuyingprice;
		$returnedfinaltotalamount=$returnedfinaltotalamount+ $ttcurrentamount;
		
		
		}
		
		
		}
		$finaltotalamount=$finaltotalamount-$returnedfinaltotalamount;
				
				
				
				
				
				
				
				
				
				
				$currentbalance=$finaltotalamount-(double)$oldpoaid;
				
				
				
				$myoldbalance=(double)$oldtotal-(double)$oldpoaid;
				if($transactionstatus=="closed"){
					$finalcustomerbalance=$supplierbalance+($currentbalance-$myoldbalance);

				}else{
								$finalcustomerbalance=$supplierbalance+$currentbalance;
	
				}
				
					if($oldtotal!= $finaltotalamount){
					if($finalcustomerbalance > 0){
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
										'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			}
			}
				
				
				
				
				
				
				
				

		$usr_result =$this->db->insert_batch('debitcredit', $insertdata); 
		
		
		
		
			if($projectname=="creditnote"){
							$creditdata=array( 'userid'=>$userid,'account'=>2130,'debit'=>$currentfinalamount,'description'=>"Account Receivable for inventory",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Purchases",'supplier'=> $supplier);
	
							}else{
							$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$currentfinalamount,'description'=>"Account payable for inventory",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Purchases",'supplier'=> $supplier);
	
							}

							$susr_result = $this->usermodel->add($creditdata,'debitcredit');

			
		
		
		
		}
	
	
	
	
	

	
	
	
	


	
	//$vat=$finaltax;
						      ///$taxable=$vatable;
	
		 // $ttvat=$ttvat+$vat;
							//$tttaxable=$tttaxable+$taxable;
							  
	
										$updatedata=array(		
			'updatedid'=>$userid,
			
				'transactionstatus'=>$status,
						 	'amount'=>$currentfinalamount,
						 	'qty'=>$ttqtys,

			 	'companyid'=>$companyid,
				'fromdate'=>$fromdate,
			'updateddate'=>$dateposted,
				'vat'=>$ttvat,
				'taxable'=>$tttaxable,
			
								);
			$usr_result = $this->usermodel->updatedata($updatedata,'purchaseorder','invoice',$invoice_number);

			
if($usr_result){
	
	
	

	
	
	
	
	
	
	
	
	
	
	$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully '.$status.' the invoice/purchasee..</div>');	
		//redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);
		redirect('user/viewpurchases');

}else{
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The operation was not Updated.. Try again</div>');
	redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);
	
}
}else{
	
	$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully '.$status.' the invoice/purchasee..</div>');	
		//redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);
		redirect('user/viewpurchases');	
	
	
}
	
	}
 
 
	}	}
 
 

 

 
  
  public function updatedailystockperitem()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $code = $this->input->post("code");
			  		 		   	  $open = $this->input->post("open");

						  		   	  $closedate = $this->input->post("closedate");

						  		

		   	  $balance = $this->input->post("balance");
		   	  $price = $this->input->post("price");

			  	

		    			  	
$totalsold=($open-$balance);


		$finaltotal=$totalsold*$price;
		
		$finalstock=$added+$open;
		
		$mybalance=($open+$added+$returned)-($unsold+$sold);
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewopeningstock', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatestock') == "stock")
					   {
						   
						   
						   
						   
					
						 $productlist = $this->usermodel->populatealldataarray('stock','id', $mycategoryid,'companyid', $companyid);

				
				

		$branch=$productlist[0]['branchid'];	   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'updatedby'=>$userid,
			
'code'=>$code,
'sold'=>$totalsold,
//'open'=>$open,
'balance'=>$balance,
//'added'=>$added,
'totalamount'=>$finaltotal,
'price'=>$price,
'total'=>$balance,

			
			 	'companyid'=>$companyid,
			
			'closedate'=>$closedate,
				
				
			 	'unsold'=>0,
			
			'returned'=>0,
				
								);
								
								
								

														$usr_result = $this->usermodel->updatedata($data,'stock','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
						
								$productdata=array(		
												'qty'=>$balance,
													);
								
								
								
								
								if($branch=="Main"){
						$this->usermodel->updatedata($productdata,"products",'code',$code);

								}else{
							 $this->usermodel->updateproductlist($productdata,$code,$branch) ; 
	
								}
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the stock..</div>');	
								 redirect('user/viewopeningstock');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not Updated.. Try again</div>');
								
								 redirect('user/viewopeningstock');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 


 
  
  public function updatedailystock()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $code = $this->input->post("code");
			  		   	  $sold = $this->input->post("sold");
						  		   	  $closedate = $this->input->post("closedate");

						  		   	  $open = $this->input->post("open");

									  		   	  $added = $this->input->post("added");
		   	  $balance = $this->input->post("balance");
		   	  $price = $this->input->post("price");

			  		   	  $totalamount = $this->input->post("totalamount");

		    			  		   	  $total = $this->input->post("total");
		    			  		   	  $unsold = $this->input->post("unsold");
		    			  		   	  $returned = $this->input->post("returned");
$totalsold=($unsold+$sold);
		$finaltotal=$totalsold*$price;
		
		$finalstock=$added+$open;
		
		$mybalance=($open+$added+$returned)-($unsold+$sold);
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewopeningstock', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatestock') == "stock")
					   {
												$data=array(		
			'updatedby'=>$userid,
			
'code'=>$code,
'sold'=>$totalsold,
'open'=>$open,
'balance'=>$mybalance,
'added'=>$added,
'totalamount'=>$finaltotal,
'price'=>$price,
'total'=>$finalstock,

			
			 	'companyid'=>$companyid,
			
			'closedate'=>$closedate,
				
				
			 	'unsold'=>$unsold,
			
			'returned'=>$returned,
				
								);
								
								
								

														$usr_result = $this->usermodel->updatedata($data,'stock','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the stock..</div>');	
								 redirect('user/viewopeningstock');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not Updated.. Try again</div>');
								
								 redirect('user/viewopeningstock');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
  
  public function updateclosingstock()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 			  $myid = $this->input->post("myid");
		 			  $method = $this->input->post("method");

		  $balance = $this->input->post("balance");

	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
		  $department = $this->input->post("department");
		  $mybranch = $this->input->post("mybranch");
		  $code = $this->input->post("code");

			  		  $this->form_validation->set_rules("balance", "Closing balance", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewopeningstock', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
					   //validation succeeds
					 	if ($this->input->post('btn_editclosingstock') == "mystock")
					   {
						  
												$data=array(		
			//'updatedby'=>$userid,
			


'balance'=>$balance,

			
			//'closedate'=>$dateposted,
				
			
								);
														$usr_result = $this->usermodel->updatedata($data,'stock','id',$myid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									$productdata=array(		
													'qty'=>$balance,
													);
							$this->usermodel->updatedatabytwo($productdata,'productlist','code',$code,'branch',$mybranch);

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the stock..</div>');	
							
							redirect('user/enterallclosingstock?startdate='.$startdate.'&department='.$department.'&branchid='.$branchid.'&method='.$method);	

		//$this->enterallclosingstock($startdate,$branchid,$department);
return true;
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not Updated.. Try again</div>');
								
							redirect('user/enterallclosingstock?startdate='.$startdate.'&department='.$department.'&branchid='.$branchid.'&method='.$method);	


							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 	
 function createRandomPasswordForLogin() {
	  	$session_data = $this->session->userdata('logged_in');

			$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	$chars =  $userid.time()."003232303232023232023456789453242131231425325212312353253256325213213546121425453553245352444343422323";
					  //$chars = '2342355ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+';

	srand((int)microtime()*100000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 5) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}


 
  
  
  

	public function searchallsms()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallsms';
		$config['total_rows'] = $this->usermodel->search_sms_count($searchterm,$userid);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewsms'] = $this->usermodel->searchallasms($searchterm,$limit,$userid);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$mytotal_amount = $this->usermodel->countamount($userid);

	$total_amount=$mytotal_amount[0]['totalsms'];	
	 $data["total_amount"] =$total_amount;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewsms',$data);
				
		$this->load->view("template/footerpage");
		
	}
	




  
  
  
    public function sendotpetims()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
	
		  
		  		     $data['branchid'] = $session_data['branchid'];
		   $branchid = $data['branchid'];
		   
		   
		    $name = $this->input->post("name");
		 		 $phone = $this->input->post("phone");
		 		  $mycategoryid = $this->input->post("mycategoryid");

			  
		    
		
				
			  		  $this->form_validation->set_rules("phone", "phone no", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewetiminitialize', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_sendotp') == "otp")
					   {
						   
						   
						   		  $correctime=date("Y-m-d H:i:s");

		$smscode =  $userid.$this->createRandomPasswordForLogin();

	
		$myview="";
		 	$taskmessage = "Hello! Your one time ETIMS Activation code is: .". $smscode ." at  ". $correctime .". Use it within 15 minutes.";


//$myview="user/receivesmscode?randomitemidentifier=".$employeeno."&contact=".$contact."&branch=".$branch;
									//

			$updatesmsdata=array(	
							'updatedby'=>$name,			
							'phone'=>$phone,
							'code'=>trim($smscode),
							'requestdate'=>$correctime,

							);
						
	
							   	$this->usermodel->updatedata($updatesmsdata,'etiminitialization','id',$mycategoryid);
																	  $this->pushroomsms($taskmessage,$phone,$myview);

								     redirect("user/receivesmscodeetims?randomitemidentifier=".$mycategoryid."&contact=".$phone."&branch=".$branchid."&code=".$smscode);

	
return false; 
						   
						   
						   
						   
$usr_result =true;


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong>OTP has been sent to you..</div>');	
							redirect('user/viewetiminitialize');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> SMS Error.. check sms or internet.. Try again</div>');
								
								 redirect('user/viewetiminitialize');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  
  
  
  
  
	 public function loginalletims()
    {
          		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];

		 $userid = $data['id'];
		  //
           $myuserid = $this->input->post("myuserid");
           $branch = $this->input->post("branch");
           $smscode = trim($this->input->post("smscode"));
           $contact = $this->input->post("contact");
$smscodemain = $this->input->post("smscodemain");

          //set validations

         $this->form_validation->set_rules("smscode", "SMS Code", "trim|required|xss_clean");
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
                 $this->load->view("template/headerpagemin");

		$this->load->view('userdata/smsotpetims',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_login') == "loginall")
					   {
						   
						   
						   	   if($smscode ==""){
							   
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your have not entered any verification code sent to your sms. Please enter the code then try again. .</div>');

							 redirect("user/receivesmscodeetims?randomitemidentifier=".$myuserid."&contact=".$contact."&branch=".$branch."&code=".$code);

							   return false;
							   
							   
							   
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						$confirmusers = $this->usermodel->populatealldataarray('etiminitialization', 'id',$myuserid,'code',trim($smscode));
		  // loginall
		  
		
						   if($confirmusers !=true){
							   
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your have entered wrong verification code.. Kindy enter the code sent to your phone and try again. .</div>');

							 redirect("user/receivesmscodeetims?randomitemidentifier=".$myuserid."&contact=".$contact."&branch=".$branch."&code=".$smscodemain);

							   return false;
							   
							   
							   
						   }
						   
	$correctime=date("Y-m-d H:i:s");					   
$to_time = strtotime($correctime);
   $fromdatetime=$confirmusers[0]['requestdate'];
$from_time = strtotime($fromdatetime);
 $timedifference= round(abs($to_time - $from_time) / 60,2);
						   
						   

						   
	   if($timedifference > 15){
							   
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The verification code has expired. Try resend the code  using the orenge button and use the new code  within 15 minutes. try again. .</div>');

							 redirect("user/receivesmscodeetims?randomitemidentifier=".$myuserid."&contact=".$contact."&branch=".$branch."&code=".$smscodemain);

							   return false;
							   
							   
							   
						   }					   
						   
						   
						   
						$currentdate=date('Y-m-d');
						   
				
									if($confirmusers==true){	

									
								     $tin=($confirmusers[0]['tin']);
								   


								   $sdcId=($confirmusers[0]['sdcId']);
									$bhfid=($confirmusers[0]['bhfid']);
								    $cmcKey=($confirmusers[0]['cmcKey']);
									$businesskey=($confirmusers[0]['businesskey']);
									$code=($confirmusers[0]['code']);
									$phone=($confirmusers[0]['phone']);
									$updatedby=($confirmusers[0]['updatedby']);
									$requestdate=($confirmusers[0]['requestdate']);
									$branchid=($confirmusers[0]['branchid']);
					$mrcNo=($confirmusers[0]['mrcNo']);
									$invoice=($confirmusers[0]['bhfSttsCd']);
	$onlineoffline=($confirmusers[0]['onlineoffline']);
									$url=($confirmusers[0]['url']);

									$combined=TRIM($tin.$bhfid);
									 $verification = ($this->encryption->encrypt($combined)); 

				
				
							$this->load->view("template/headerpagemin");

	 		



$data['tin'] = $tin;
$data['sdcId'] = $sdcId;
$data['bhfid'] = $bhfid;
$data['cmcKey'] = $cmcKey;

$data['businesskey'] = $businesskey;
$data['code'] = $code;
$data['phone'] = $phone;
$data['updatedby'] = $updatedby;
$data['requestdate'] = $requestdate;	
$data['verification'] = $verification;
$data['branchid'] = $branchid;	
$data['mrcNo'] = $mrcNo;	
$data['invoice'] = $invoice;	
$data['url'] = $url;	
$data['onlineoffline'] = $onlineoffline;	
								






				$this->load->view('userdata/extendetims',$data);
		$this->load->view("template/footerpage");
						
													}
  
  
  
  
		}
		
	
	} 
  
  } 
  
  
  
	function pushroomsms($mainmessage,$maincontact,$myview)
	{
 
		
			//SS$session_data = $this->session->userdata('logged_in');

   
 	//$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 //$userid = $data['id'];
		 	// $data['companyid'] = $session_data['companyid'];
	 $companyid = 1;
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				
				
				
					$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);




				$userid=$configuration[0]["paymenttypes"];



	
				
					$sigature=$configuration[0]["sigature"];

	if($sigature!=""){
		
		$mainmessage=$mainmessage. " ".$sigature;
	}else{
				$mainmessage=$mainmessage;
	}
				
			
				
				
				
				
				
				
				
				
				
				
				
								$contact = htmlspecialchars(trim($maincontact));

		   	  $mymessage = trim($mainmessage);
			
				
				
				
				
				
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			
			 
			 
						   
				
					 
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
//$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 //redirect($myview);
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
			
			
			
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=".urlencode($from)."&mobile=$allcontacts";

			//$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=$from&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
								// redirect($myview);
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Verification sms   is sent successfully to your phone.</div>');
					
			
								// redirect($myview);
			}else{
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not sent to your phone. <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
												//	  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');


							//redirect($myview);

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  



  
  
  
    public function updateetimsurl()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $onlineoffline = $this->input->post("onlineoffline");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $url = $this->input->post("url");
			  
		    
		
				
			  		  $this->form_validation->set_rules("url", "URL", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewetiminitialize', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateurl') == "updateurl")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'url'=>$url,
			
		  	'onlineoffline'=>$onlineoffline,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
														$usr_result = $this->usermodel->updatedata($data,'etiminitialization','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the Url..</div>');	
							redirect('user/viewetiminitialize');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Url  was not Updated.. Try again</div>');
								
								 redirect('user/viewetiminitialize');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  
  
  
  
  
  
  
  
  
  
  public function updatecategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatecategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
														$usr_result = $this->usermodel->updatedata($data,'category','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the category..</div>');	
							redirect('user/viewcategory');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Category  was not Updated.. Try again</div>');
								
								 redirect('user/viewcategory');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  public function addcomputerkey()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $computerno = $this->input->post("computerno");
		 		 $itemid = $this->input->post("itemid");

		   	  $description = $this->input->post("description");
			  
		    			   	  $view = $this->input->post("view");

		 		 $extensiontype = $this->input->post("extensiontype");
		 		 $status = $this->input->post("status");
				$todate = $this->input->post("todate");

				$fromdate = $this->input->post("fromdate");
			  
			  
			 
			  
		
			  
		
				
			  		  $this->form_validation->set_rules("computerno", "Computerno Key", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewrenewalrequests', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcomputer') == "computer")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'computerno'=>$computerno,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
					  
			   	'extensiontype'=>$extensiontype,
			 	'status'=>$status,
			   	'todate'=>$todate,
			 	'fromdate'=>$fromdate,
			  			 	'invoice'=>$itemid,

			  
			  
			  
			
								);
							$usr_result = $this->usermodel->add($data,'computers');


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully created the computer key..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Computer key  was not Updated.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  public function updaterenewalrequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $computerno = $this->input->post("computerno");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  
		    	
		 		 $extensiontype = $this->input->post("extensiontype");
		 		 $status = $this->input->post("status");
				$todate = $this->input->post("todate");

				$fromdate = $this->input->post("fromdate");
			  
			  
			 
			  
		
			  
		
				
			  		  $this->form_validation->set_rules("computerno", "Computerno Key", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewrenewalrequests', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updaterequestrenewals') == "request")
					   {
												$data=array(		
			//'userid'=>$userid,
			
				'computerno'=>$computerno,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			//'createdate'=>$dateposted,
					  
			   	'extensiontype'=>$extensiontype,
			 	'status'=>$status,
			   	'todate'=>$todate,
			 	'fromdate'=>$fromdate,
			  	 	'updatedid'=>$userid,
'updatedate'=>$dateposted,
			  
			  
			  
			  
			
								);
														$usr_result = $this->usermodel->updatedata($data,'renewals','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the date extension data..</div>');	
							redirect('user/viewrenewalrequests');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Extension  was not Updated.. Try again</div>');
								
								 redirect('user/viewrenewalrequests');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updatecomputerkeys()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $computerno = $this->input->post("computerno");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  
		    	
		 		 $extensiontype = $this->input->post("extensiontype");
		 		 $status = $this->input->post("status");
				$name = $this->input->post("name");

				$fromdate = $this->input->post("fromdate");
			  
			  
			 
			  
		
			  
		
				
			  		  $this->form_validation->set_rules("computerno", "Computerno Key", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbusinessrequests', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateupdatecomputerkeys') == "keys")
					   {
												$data=array(		
			//'userid'=>$userid,
			
				'computerno'=>$computerno,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			
					  
			   	'extensiontype'=>$extensiontype,
			 	'status'=>$status,
			   	'name'=>$name,
			 	'fromdate'=>$fromdate,
			  			 	'updatedid'=>$userid,
'updatedate'=>$dateposted,
			  
			  
			  
			
								);
						$usr_result = $this->usermodel->updatedata($data,'computers','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the date extension data..</div>');	
							redirect('user/viewnewbusinessrequests');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Extension  was not Updated.. Try again</div>');
								
								 redirect('user/viewnewbusinessrequests');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updatecomputerkeysetims()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $computerno = $this->input->post("computerno");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  
		    	
		 		 $extensiontype = $this->input->post("extensiontype");
		 		 $status = $this->input->post("status");
				$name = $this->input->post("name");

				$fromdate = $this->input->post("fromdate");
			  
			  
			 
			  
		
			  
		
				
			  		  $this->form_validation->set_rules("computerno", "Computerno Key", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbusinessrequests', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateupdatecomputerkeys') == "keys")
					   {
												$data=array(		
			//'userid'=>$userid,
			
				'computerno'=>$computerno,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			
					  
			   	'extensiontype'=>$extensiontype,
			 	'status'=>$status,
			   	'name'=>$name,
			 	'fromdate'=>$fromdate,
			  			 	'updatedid'=>$userid,
'updatedate'=>$dateposted,
			  
			  
			  
			
								);
						$usr_result = $this->usermodel->updatedata($data,'etimsactivations','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the ETIMS data..</div>');	
							redirect('user/viewnewbusinessrequestsetims');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> ETIMS DATA  was not Updated.. Try again</div>');
								
								 redirect('user/viewnewbusinessrequestsetims');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
  public function updatedeliverystatus()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 $serial = $this->input->post("serial");

		 		 $status = $this->input->post("status");
		 		 $mycategoryid = $this->input->post("mycategoryid");
				$profit=0;
		   	  $description = $this->input->post("description");
			  		   	  $page = $this->input->post("page");

			  
			  $finaldescription="";
			  			  $currentdescription="";

			  $confirmdata= $this->usermodel->populateallarray('delivery','id',$mycategoryid);
  
							
						  if ($confirmdata !=false)
						   {
						  $currentstatus=$confirmdata[0]['status'];
$currentdescription=$confirmdata[0]['itemid'];

			  if($currentstatus==$status){
				  
				  

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The  delivery status update failed because you did not change any status or selected different stataus.Try again</div>');
																			
											
											redirect("Systemusers/recorddelivery/".$page);
				  return false;
				  
			  }
			  
			  
						   }
			  
			  
			  
		
					
			  
			  if($status=="Delivered"){
		            
			
			
								  		$mypreviousdata= $this->usermodel->populateallarray('delivery','id',$mycategoryid);
					if ($mypreviousdata !=false)
						   {
						  $serial=$mypreviousdata[0]['serial']; 
						  $code=$mypreviousdata[0]['code']; 
					$buyingprice=$mypreviousdata[0]['buyingprice'];
					$sellingprice=trim($mypreviousdata[0]['sellingprice']); 
						$mode=trim($mypreviousdata[0]['mode']);
										$shipping=$mypreviousdata[0]['shipping']; 
										$commission=$mypreviousdata[0]['commission']; 

										$mycommission=(($commission/$sellingprice)*100);
										$finalcommission= $this->formatMoney($mycommission, true);

if($mode=="Comm"){
	  				$profit=($commission-$shipping);

}else{
	
	  				$profit=($sellingprice-$buyingprice-$commission-$shipping);

	
}


						   }else{
							   $profit=0;
							   
						   }
						   
			
			  }
				
			  
			  $this->form_validation->set_rules("status", "Product Status", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/recorddelivery', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatestatusdelivery') == "delivery")
					   {
						 	  $mycustomer=$this->usermodel->populateallarray('people','id', $userid);

			$myname=$mycustomer[0]['firstname'];
						   			$actiondone=$myname ." Changed the delivery status from ". $currentstatus."  to ". $status."  on  ". $dateposted.".";
  
						   //
if($currentdescription	==""){
						$finaldescription=$actiondone;

					}else{
						$finaldescription=$currentdescription.".; ".$actiondone;

					}	
										$data=array(		
			
			
					'status'=>$status,
						'itemid'=>$finaldescription,
			 	'updatedate'=>$dateposted,
				'myid'=>$userid,
		  	'description'=>$description,
			 	'companyid'=>$companyid,

				
			
								);
								
													$profitdata=array(		
			//'userid'=>$userid,
			
			'status'=>$status,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'profit'=>$profit,

				
				'itemid'=>$finaldescription,
			 	'updatedate'=>$dateposted,
				'myid'=>$userid,
								);
								
								$noprofitdata=array(		
			
			
			'status'=>$status,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						 	'profit'=>"",
						 	'commission'=>"",
						 	'shipping'=>"",

					'itemid'=>$finaldescription,
			 	'updatedate'=>$dateposted,
				'myid'=>$userid,
			
								);
								
								if($status=="Delivered"){
																$usr_result = $this->usermodel->updatedata($profitdata,'delivery','id',$mycategoryid);

								}else if($status=="Claim Damaged"){
									
									
																				$serialdamageddata=array(		
						'status'=>"damaged",

								);
								
							
								 $this->usermodel->updatedata($serialdamageddata,'serials','serial',$serial);

									$usr_result = $this->usermodel->updatedata($data,'delivery','id',$mycategoryid);

								}else if(($status=="Returned and Received")||($status=="Claim OK")){
									
									
									$mainid="";
									
									
$myserialname= $this->usermodel->populateallarray('serials','serial',$serial);
  
							   $balancebalance=0;
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
						   $mybranch=$myserialname[0]['branch']; 

							//$qty=$myserialname[0]['qty'];						  
							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$mybranch);
						   $mainid=$productname[0]['id'];
						   $original=trim($productname[0]['qty']); 
	 $balancebalance=$original+1;


						   }
														$usr_result = $this->usermodel->updatedata($noprofitdata,'delivery','id',$mycategoryid);
																
																$newqtyDATA=array(		
						'qty'=>$balancebalance,

								);
											$serialdata=array(		
						'status'=>"new",

								);
								
							
								 $this->usermodel->updatedata($newqtyDATA,'productlist','id',$mainid);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$serial);


								}else{
									
																$usr_result = $this->usermodel->updatedata($data,'delivery','id',$mycategoryid);

								}


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the delivery status..</div>');	
											redirect("Systemusers/recorddelivery/".$page);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The delivery status  was not Updated.. Try again</div>');
								
											redirect("Systemusers/recorddelivery/".$page);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
  public function updaterequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 	$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $paymentmethodes = $this->input->post("paymentmethodes");
	  $refno = $this->input->post("refno");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
				  		  $view = $this->input->post("view");   

		   
				  		 // $invoice = $this->input->post("invoice");   

  				  		  $bankname = $this->input->post("bankname");   
  				  		  $itemid = $this->input->post("itemid");   

				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editexpenserequest', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_editrequest') == "request")
					   {
													$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
						'supplier'=>$supplier,

			'crateddate'=>$dateposted,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   

					    'branch' => $branchid,  
			    'companyid' => $companyid,  
				
			   			     

				
			
			
			
								);					$usr_result = $this->usermodel->updatedata($data,'statement','id',$itemid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the data..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not Updated.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 	
public function addnewvoucher()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$business = $this->input->post("business");
	  $customer = $this->input->post("customer");
	  $cardnumber = $this->input->post("cardnumber");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $myid = $this->input->post("myid");   

				  		  $invoice = $this->input->post("invoice");   

				  		  $fromdate = $this->input->post("fromdate");   

				  		  $todate = $this->input->post("todate");   

				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbanks', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addvoucher') == "voucher")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'cardnumber'=>$cardnumber,
		  	'customer'=>$customer,
			
			
			'fromdate'=>$fromdate,
			'todate' => $todate,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   		  'dateposted' => $dateposted,   

			
			    'companyid' => $companyid,  
				
			   			    'business' => $business,  

							   			    'invoice' => $invoice,  

			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'voucher');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'voucher','id',$myid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function addloyality()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:a');
		 $userid = $data['id'];
	
				 $userid = $data['id'];
		  $data['companyid'] = $session_data['companyid'];
		   $companyid = $data['companyid'];
		     $data['branchid'] = $session_data['branchid'];
		   $branchid = $data['branchid'];
		 		
		 		 $value = $this->input->post("value");
				$cardnumber = $this->input->post("cardnumber");
		   	   $type = $this->input->post("type");
			   $description = $this->input->post("description");
		     $correctamount = $this->input->post("value");
					   $amount = $this->input->post("value");
					   $transactiontype = $this->input->post("transactiontype");

				
			  		  $this->form_validation->set_rules("cardnumber", "Card number ", "trim|required");
			  		  $this->form_validation->set_rules("value", "Amount ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addloyality') == "loyatity")
					   {
						   						$totalpoints=0;
$totalcoins=0;
						
						
						      					   	$confirmcard = $this->usermodel->Getcardnumber($cardnumber,$companyid);
	if($confirmcard!=FALSE){
			
					$cardnumber=$confirmcard[0]['address_1'];
						   
						
						   
				  
						   
						   
						   
						   
						   	
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$pointsdisplay=$smsconfig[0]['display'];
		
			$oldpoints=$confirmcard[0]['savedpoints'];
					$oldcoins=$confirmcard[0]['savedcoins'];
$customerid=$confirmcard[0]['id'];
		
		
			  if($transactiontype=="Redeem"){	
			  
			  	 if($type=="Points"){
					 if($correctamount>$oldpoints){
						  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have less points('.$oldpoints.' )... Try again</div>');
								
								 redirect('user/viewloyality');
					 }
					 
				 }else{
					 
					 	 if($correctamount>$oldcoins){
							 	  
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have less coins/saving('.$oldcoins.' )... Try again</div>');
								
								 redirect('user/viewloyality');
								 return false;
						 
					 }
				 }
			  
		
			  
			  }
		
		
		
		
		
		
		
		
		
		
		

						   		$savedpoints=0;
		$TTAMOUNTS=0;
		
		

					
							  if($transactiontype=="Post"){	

			 if($type=="Points"){
							$savedpoints=  $value/$pointsdisplay;
					$TTAMOUNTS=0;
												$totalpoints=$oldpoints+$savedpoints;

			$totalcoins=$oldcoins;
						}else{
								
							$TTAMOUNTS=$amount;
												$totalpoints=$oldpoints;
								$savedpoints= 0;
								$totalcoins=$oldcoins+$TTAMOUNTS;
						}
							  }else{
								  $amount="-".$amount;
								  
								 if($type=="Points"){
							$savedpoints=  $amount;
					$TTAMOUNTS=0;
												$totalpoints=$oldpoints+$savedpoints;

			$totalcoins=$oldcoins;
						}else{
								
							$TTAMOUNTS=$amount;
												$totalpoints=$oldpoints;
								$savedpoints= 0;
								$totalcoins=$oldcoins+$TTAMOUNTS;
						}  
								  
								  
								  
								  
							  }


						$redeemdata=array(		
			'userid'=>$userid,
			'value'=>$savedpoints,
				'cardnumber'=>$cardnumber,
			
		  	'description'=>$description,
			'type'=>$type,
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
								  'amount'=>$TTAMOUNTS,
								'originalamount'=>0,
								  'invoice'=>"Redeemed",
								);
						 
												$data=array(		
			'userid'=>$userid,
			'value'=>$savedpoints,
				'cardnumber'=>$cardnumber,
			
		  	'description'=>$description,
			'type'=>$type,
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
								  'amount'=>$TTAMOUNTS,
								'originalamount'=>$amount,
								  'invoice'=>"Direct",
								);
								
								  if($transactiontype=="Post"){
									  
							$usr_result = $this->usermodel->add($data,'loyalitycards');
												}else{
										$usr_result = $this->usermodel->add($redeemdata,'loyalitycards');
	
													
												}
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										$updatecoinsdata=array(		
											
												'savedcoins'=>$totalcoins,
												'savedpoints'=>$totalpoints,
												
													);
								
								
										$this->usermodel->updatedata($updatecoinsdata,'people','id',$customerid);
							
								
							
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Created a new Loyality Point..</div>');	
							redirect('user/viewloyality');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Loyality point  was not added.. Try again</div>');
								
								 redirect('user/viewloyality');
							}
					   
					   
					   
						   
			
					   
					   
					 }
					   else
					   {
						
							
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Loyality point  was not added because the card number does not exist.. The Try again</div>');
								
								 redirect('user/viewloyality');
					   }   
					   
					   
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
  public function addmysale()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
	
				 $userid = $data['id'];
		  $data['companyid'] = $session_data['companyid'];
		   $companyid = $data['companyid'];
		 				 		 $paymentdate = $this->input->post("paymentdate");

		 		 $datesold = $this->input->post("datesold");
				$name = $this->input->post("name");
		   	  $sellingprice = $this->input->post("sellingprice");
			   $profit = $this->input->post("profit");
		     
  $mode = $this->input->post("mode");
				$code = $this->input->post("code");
			   $description = $this->input->post("description");
		    $rate = $this->input->post("rate");
		$customer = $this->input->post("customer");
				$customerphone = $this->input->post("customerphone");
				$customeremail = $this->input->post("customeremail");
				$customerlocation = $this->input->post("customerlocation");
											$action = $this->input->post("action");
											$mycategoryid = $this->input->post("mycategoryid");

$expcommission=(($sellingprice *$rate)/100) ; 
		
				
			  		  $this->form_validation->set_rules("name", "Card number ", "trim|required");
			  		  $this->form_validation->set_rules("datesold", "Amount ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postsales') == "payment")
					   {
												$data=array(		
			'userid'=>$userid,
			'datesold'=>$datesold,
				'name'=>$name,
						'paymentdate'=>$paymentdate,

		  	'profit'=>$profit,
			'sellingprice'=>$sellingprice,
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
								 'expcommission'=>$expcommission,

 

			'mode'=>$mode,
				'code'=>$code,

			'rate'=>$rate,
		  	'description'=>$description,
		'customer'=>$customer,
			
			'dateposted'=>$dateposted,
			'customerphone' =>$customerphone,
				'customeremail' =>$customeremail,
				'customerlocation'=>$customerlocation,
				
				
 
								);
								
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'commission');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'commission','id',$mycategoryid);

								}
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted a new sale Point..</div>');	
							redirect('user/payments');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sale  was not posted.. Try again</div>');
								
								 redirect('user/payments');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
  public function addallsale()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
	
				 $userid = $data['id'];
		  $data['companyid'] = $session_data['companyid'];
		   $companyid = $data['companyid'];
		 				 		 $paymentdate = $this->input->post("paymentdate");

		 		 $datesold = $this->input->post("datesold");
				$name = $this->input->post("name");
		   	  $sellingprice = $this->input->post("sellingprice");
			   $profit = $this->input->post("profit");
		     			   $paid = $this->input->post("paid");

  $mode = $this->input->post("mode");
				$code = $this->input->post("code");
			   $description = $this->input->post("description");
		    $rate = $this->input->post("rate");
		$customer = $this->input->post("customer");
				$customerphone = $this->input->post("customerphone");
				$customeremail = $this->input->post("customeremail");
				$customerlocation = $this->input->post("customerlocation");
											$action = $this->input->post("action");
											$mycategoryid = $this->input->post("mycategoryid");

$expcommission=(($sellingprice *$rate)/100) ; 
		
				
			  		  $this->form_validation->set_rules("name", "Card number ", "trim|required");
			  		  $this->form_validation->set_rules("datesold", "Amount ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postsales') == "payment")
					   {
												$data=array(		
							'paid'=>$paid,

				'name'=>$name,
			'paymentdate'=>$paymentdate,

		  	'profit'=>$profit,
			'sellingprice'=>$sellingprice,
			
			'dateposted'=>$dateposted,
								 'expcommission'=>$expcommission,

 

			'mode'=>$mode,
				'code'=>$code,

			'rate'=>$rate,
		  	'description'=>$description,
		'customer'=>$customer,
			
			'dateposted'=>$dateposted,
			'customerphone' =>$customerphone,
				'customeremail' =>$customeremail,
				'customerlocation'=>$customerlocation,
				
				
 
								);
								
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'commission');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'commission','id',$mycategoryid);

								}
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted a new sale Point..</div>');	
							redirect('user/viewallpostedsales');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sale  was not posted.. Try again</div>');
								
								 redirect('user/viewallpostedsales');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
		
	
		public function uploadrequestdocument() {
		$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   //	$type = $this->input->post("type");
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
    if($this->input->post('btn_uploadrequestdocument')) {
    $file= $_FILES["document"]['name'];
	  $category = "Expense";
	  			   $img_id = $this->input->post("img_id");

			   $receipt = $this->input->post("receipt");
		     $entrydate = $this->input->post("entrydate");

		   		     $view = $this->input->post("view");
		   		     $documentname = $this->input->post("documentname");

 //exit;
  $documentname = $this->input->post("documentname");					  
		//$studentid1 = $this->input->post("studentid");
if($file!=""){
		$document = $this->input->post("document");
	$config['upload_path'] = is_dir($document).'docs/';
		//$config['upload_path'] = '10.1.1.148/home/portal/test/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
   
		        $config["allowed_types"] = 'jpg|jpeg|png|gif|pdf';

        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);

	  
	  	$data=array(		
			'img_id'=>$img_id,
			'documentname'=>$documentname,
			'name'=>$new_name,
		  	'description'=>$receipt,
			'category'=>$category,
			'entrydate'=>$dateposted,
					'userid'=>$userid,
						'companyid'=>$companyid,

			
								);
								

        if(!$this->upload->do_upload('document')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Your document could not be uploaded.. Please select and upload ONLY PDF documents one by one or try again.
						  </div>');
        	 redirect('user/viewmorerequestdocuments?randomitemidentifier='.$img_id);

         
       
        } else {

		
														$usr_result =  $this->usermodel->add($data,'documents');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
										
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Uploaded your document make sure all the admission documents are uploaded using the same procedure..!</div>');
								
								 redirect('user/viewmorerequestdocuments?randomitemidentifier='.$img_id);
							}
							

        }  


}


}else{

$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Make sure you upload the correct image first

						  </div>');
						  								 redirect('user/viewmorerequestdocuments?randomitemidentifier='.$img_id);


		}
		
		}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	  public function uploadrequestdocument2()
    {
		
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   //	$type = $this->input->post("type");
						$view = "user/viewdocuments";
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		 $img_id = $this->input->post("img_id");

				
		   	  $category = "Expense";
			   $receipt = $this->input->post("receipt");
		     $entrydate = $this->input->post("entrydate");
		   		     $userfile = $this->input->post("userfile");

		   		     $view = $this->input->post("view");
		   		     $documentname = $this->input->post("documentname");

				
			  		  $this->form_validation->set_rules("img_id", "document name ", "trim|required");
  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmorerequestdocuments', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_uploadrequestdocument') == "request")
					   {
						   
						 
						       $file= (isset($_FILES["document"]['name']));
							   
							   echo ($file);
							   exit;

		$photo = $this->input->post("document");

		$config['upload_path'] = is_dir($photo).'docs/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
												$data=array(		
			'img_id'=>$img_id,
			'documentname'=>$documentname,
			'name'=>$new_name,
		  	'description'=>$receipt,
			'category'=>$category,
			'entrydate'=>$dateposted,
					'userid'=>$userid,
						'companyid'=>$companyid,

			
								);
								
								
								
								
							
						    if(!$this->upload->do_upload('photo')) {  
							   echo  $this->data['error'] = $this->upload->display_errors();
							  echo "Not saved";
							 $this->usermodel->add($data,'documents');

							 
      

						
				
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added a new document.</div>');	
							
								 redirect('user/viewmorerequestdocuments?randomitemidentifier='.$img_id);
								 
																						
							}
							else if ($usr_result ==FALSE) 
							{     
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The document  was not created.. Try again</div>');
																 redirect('user/viewmorerequestdocuments?randomitemidentifier='.$img_id);

							
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
	
	
	
	
	
	
  public function adddocuments()
    {
		
			$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   //	$type = $this->input->post("type");
						//$view = "user/viewdocuments";
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 				 		 $img_id = $this->input->post("img_id");

		 		 $documentname = $this->input->post("documentname");
				$idno = $this->input->post("idno");
		   	  $category = $this->input->post("category");
			   $description = $this->input->post("description");
		     $entrydate = $this->input->post("entrydate");
 $view = $this->input->post("view");
		   		     $mydocuments = $this->input->post("mydocuments");

			
			  		  $this->form_validation->set_rules("category", "Category Name ", "trim|required");
			  		  $this->form_validation->set_rules("documentname", "documentname ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdocuments', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adddocuments') == "documents")
					   {
												$data=array(		
			'img_id'=>$img_id,
			'documentname'=>$documentname,
				'idno'=>$idno,
			
		  	'description'=>$description,
			'category'=>$category,
			'entrydate'=>$entrydate,
			'dateposted'=>$dateposted,
					'userid'=>$userid,
									'companyid'=>$companyid,
					'mydocuments'=>$mydocuments,

			
								);
							$usr_result = $this->usermodel->add($data,'documents');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						$this->uploadimage($view, $img_id,$userid);
						
					}
						
						
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added a new document.</div>');	
							
					redirect($view);
								 
																						
							}
							else if ($usr_result ==FALSE) 
							{     
							
							
							$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The document  was not created.. Try again</div>');
								
							
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


	public function addbill()
    {
		
			$session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
	 $userid = $data['id'];
   
 	$data['id'] = $session_data['isd'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		//  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		 
		 							// $receiptno = $this->input->post("receiptno");

					
		 		 $amount = $this->input->post("amount");
				//$supplier = $this->input->post("supplier");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$datespent = $this->input->post("datespent");
				$controller = $this->input->post("controller");
				$duedate = $this->input->post("duedate");
							$invoice = $this->input->post("invoice");
						$idno = $this->input->post("idno");

						$action = $this->input->post("action");
												$type = $this->input->post("type");

						$view = $this->input->post("view");
						$terms = $this->input->post("terms");
$suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));

			  		  $this->form_validation->set_rules("supplier", "Supplier/customer name ", "trim|required");
			  		  $this->form_validation->set_rules("datespent", "Bill Date ", "trim|required");

			  
			  
			  
			  
			  
			  
			  
			  
			  
			  

			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    

			 redirect($view,$data);
		
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addbill') == "bill")
					   {
												$data=array(		
		
			'amount'=>$amount,
				'supplier'=>$supplier,
							
																'type'=>$type,

		  	'invoice'=>$invoice,

			'user'=>$user,
		  	'description'=>$description,
		'datespent'=>$datespent,
			
			'dateposted'=>$dateposted,
			'controller' =>$controller,
				'duedate' =>$duedate,
					'terms' =>$terms,
					'idno' =>$idno,

				'userid'=>$userid,
						'companyid'=>$companyid,		

			
								);
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'expenses');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'expenses','invoice',$invoice);

								}
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{

			
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new Bill  ..</div>');	
						 //redirect($view);
						  redirect('user/editbill?randomitemidentifier='.$invoice);

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bill  was not created.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							 redirect($view);
					   }
	    }
    }
   
   
   
   
 
 	public function updateandcloseexpenses()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	 		

	  $status = $_GET['status'];
	  $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	$data['id'] = $session_data['id'];
			
		 $userid = $data['id'];		
        		          		$expenses = $this->usermodel->populateallarray('expenses','invoice',$invoice_number);
									$expenseid=$expenses[0]["id"];
									
									$datespent=$expenses[0]['datespent'];
									$mydescription=$expenses[0]['description'];
$mybranchid=$expenses[0]['branchid'];
				
		

		$mybank=$expenses[0]['bankname'];
								
 $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$vatrate=$myconfiguration[0]["tax1rate"]; 
								



	
	
	  $vat=0;
		  $taxable=0;
		  	 		$finaltotalamount=0;

	  $ttvat=0;
		  $tttaxable=0;
		  
		if($status=="closed"){
			$myclosedproducts= $this->usermodel->populateall('statement','invoice',$invoice_number);
	$mycode=0;
	  	$finaltotalamount=0;
		if(is_array($myclosedproducts)){
			
		$this->usermodel->deletedata($invoice_number,"code","debitcredit");

	 $debitdata = array();
	// $creditdata = array();

	 foreach ($myclosedproducts as $row){
		 		  $vattype=$row->tax;
		 		  $bankname=$row->account;
				  		 		  $description=$row->description;


  $mycode=$row->code;
				    $myid=$row->id;
$myytotal=$row->amount;
		$finaltotalamount=$finaltotalamount+ $row->amount;
		
		
		 $transactionid=$row->id; 

			
					
			
		
							
									$debitdata[]=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$myytotal,'description'=>$description,'code'=>$invoice_number,'crateddate'=>$datespent,'branch' => $mybranchid,'companyid'=> $companyid,'balance'=> 0,'refno'=> $transactionid);


							//$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
		
		
		if($vattype=="VATABLE"){
			
				if($mycode >0){
							  $mytax=1+($mycode/100); 
							
						}else{
						  $mytax=1+($vatrate/100); 	
							
							
						}
							
			
			
			
								  $mytax=1+($vatrate/100); 
								  
								  
								 $vatable=($myytotal/$mytax);
								 $myfinaltax=(($myytotal-$vatable));
								
								$finaltax= $this->formatMoney(($myfinaltax), true);
								$vatable= $this->formatMoney(($vatable), true);

							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
						
							  
							  
										$updatevatdata=array(		
			
				'vat'=>$finaltax,
				'vatable'=>$vatable,
			
								);
			 $this->usermodel->updatedata($updatevatdata,'statement','id',$myid);

							  
							  
							  //
	
	 }
	 
	 
	 
		if($finaltotalamount>0){

		$usr_result =$this->db->insert_batch('debitcredit', $debitdata); 
		
		

$creditdata=array( 'userid'=>$userid,'account'=>$mybank,'credit'=>$finaltotalamount,'description'=>$mydescription,'code'=>$invoice_number,'crateddate'=>$datespent,'branch' => $mybranchid,'companyid'=> $companyid,'balance'=> 0,'refno'=> $transactionid);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
			}
		
	 
	 
	 
	 
	 
		}
		
			
		
		
		
		}
	
							  
	
						   	$mydata=array(		
			
							
								'status'=>"Closed",
								'amount'=>$finaltotalamount,
							

								);
						   								$usr_result = $this->usermodel->updatedata($mydata,'expenses','invoice',$invoice_number);

			
if($usr_result){
	
	
	
	$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully '.$status.' the expense..</div>');	
		//redirect('user/editexpense?randomitemidentifier='.$invoice_number);
		redirect('user/viewexpenses');

}else{
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The operation was not Updated.. Try again</div>');
	redirect('user/editexpense?randomitemidentifier='.$invoice_number);
	
}

	}
	}
 
 
 
 
 

   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
	 public function addexpense()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	 $userid = $data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		$mytime= date('H:i:s');

				$data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		 $userid = $data['id'];
		 
		 							// $receiptno = $this->input->post("receiptno");

							 		 $branchid = $this->input->post("branchid");
								
						$action = $this->input->post("action");

		 		 $amount = $this->input->post("amount");
				$supplier = $this->input->post("supplier");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$MYdatespent = $this->input->post("datespent");
		
		$timeall=$MYdatespent." ".$mytime;
		
		
				 if($action=="insert"){
						
														   	   $datespent = date("Y-m-d H:i:s", strtotime($timeall));

							}else 	if($action=="update"){
														   	   $datespent = $MYdatespent;

								}
	
				$department = $this->input->post("department");

				$controller = $this->input->post("controller");
				$idno = $this->input->post("idno");
				$contact = $this->input->post("contact");
							$bankname = $this->input->post("bankname");
							$invoice = $this->input->post("invoice");

				$imgid = $this->input->post("imgid");
												$type = $this->input->post("type");

						$view = $this->input->post("view");
						$myview = $this->input->post("myview");
						$filename = $this->input->post("filename");
						$img_id = $this->input->post("img_id");
				

						$paymentmethodes = $this->input->post("paymentmethodes");

			  		  $this->form_validation->set_rules("type", "Type", "trim|required");
			  		  $this->form_validation->set_rules("invoice", "Ref No ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/'.$filename, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
	
			if($branchid==""){
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Kindly select the branch first for you  to continue. You have not selected any branch/counter. Try again</div>');
								
								 redirect($view.$invoice);
								 return false;
				
			}
			
			 
			
			
			
			
			
		
			
			  $finalamount=0;
					  		$viewreceivings= $this->usermodel->populateall('statement','invoice',$invoice);
 
					   	if(is_array($viewreceivings)) {
				   	 
							
					$finalcode="";			
				  
					foreach ($viewreceivings as $row){ 
					
					$mytotal= $row->amount;
					$finalamount=$finalamount+$mytotal;
					}
					}  
						
			
					   //validation succeeds
					   
					    	if ($this->input->post('btn_invoicestatus') == "invoicestatus")
					   {
						   
							  $mycustomer=$this->usermodel->populateallarray('people','id', $controller);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];

	 $correctamount= $this->MyformatMoney($finalamount, true);
						   
			   
						   						$invoicestatus = $this->input->post("invoicestatus");

						   	$mydata=array(		
			
							
								'status'=>"Submitted",
								'amount'=>$finalamount,

							

								);
						   								$usr_result = $this->usermodel->updatedata($mydata,'expenses','invoice',$invoice);
														
														
														
			if ($usr_result ==TRUE) //active user record is present
							{
	
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully submitted your request..</div>');	
			$correctime = date("d/m/Y H:i", strtotime($dateposted));

  			$message="Dear ".$firstname.", ".$user." has applied for  ". $correctamount." on ". $correctime ." regarding ". $description .". Check your erp for approval.";

  
														
													
									$myview=$view.$invoice;				  
		  $this->addallpushedsms($message,$contact,$myview);	
						 redirect($view.$invoice);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your request   was not submitted.. Try again</div>');
								
								 redirect($view.$invoice);
							}
														
													

														
														

						   
					   }
					   
					   
					   
					   
					   
					   
					   
					   
					   
					   
					 	if ($this->input->post('btn_addexpense') == "expense")
					   {
												$data=array(		
			'img_id'=>$img_id,
				'imgid'=>$imgid,
			'amount'=>$amount,
				'supplier'=>$supplier,
								'bankname'=>$bankname,
				'type'=>$type,
								'department'=>$department,

			'amount'=>$finalamount,

		  	'invoice'=>$invoice,

			'user'=>$user,
		  	'description'=>$description,
		'datespent'=>$datespent,
			
			'dateposted'=>$dateposted,
			'controller' =>$controller,
				'idno' =>$idno,
				'contact'=>$contact,
				//'receiptno'=>$receiptno,
				'userid'=>$userid,
						'companyid'=>$companyid,		
						'paymentmethodes'=>$paymentmethodes,		

									'branchid'=>$branchid,		

								);
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'expenses');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'expenses','invoice',$invoice);

								}
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						$this->uploadimage($view, $img_id,$userid);
						
					}
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new expense  ..</div>');	
						 redirect($view.$invoice);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Expense  was not created.. Try again</div>');
								
								 redirect($view.$invoice);
							}
					   }
					   else
					   {
								 redirect($view.$invoice);
					   }
	    }
    }
	
   
	 public function addloanrequest()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	 $userid = $data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		$mytime= date('H:i:s');

				$data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		 $userid = $data['id'];
		 
		 							// $receiptno = $this->input->post("receiptno");

							 		 $branchid = $this->input->post("branchid");
						$action = $this->input->post("action");

		 		 $amount = $this->input->post("amount");
				$supplier = $this->input->post("supplier");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$MYdatespent = $this->input->post("datespent");
		
		$timeall=$MYdatespent." ".$mytime;
		
		
				 if($action=="insert"){
						
														   	   $datespent = date("Y-m-d H:i:s", strtotime($timeall));

							}else 	if($action=="update"){
														   	   $datespent = $MYdatespent;

								}
	

				$controller = $this->input->post("controller");
				$idno = $this->input->post("idno");
				$contact = $this->input->post("contact");
							$bankname = $this->input->post("bankname");
							$invoice = $this->input->post("invoice");

				$imgid = $this->input->post("imgid");
												$type = $this->input->post("type");

						$view = $this->input->post("view");
						$myview = $this->input->post("myview");
						$filename = $this->input->post("filename");
						$img_id = $this->input->post("img_id");
				

						$paymentmethodes = $this->input->post("paymentmethodes");

			  		  $this->form_validation->set_rules("type", "Type", "trim|required");
			  		  $this->form_validation->set_rules("invoice", "Ref No ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/'.$filename, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
	
			if($branchid==""){
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Kindly select the branch first for you  to continue. You have not selected any branch/counter. Try again</div>');
								
								 redirect($view);
								 return false;
				
			}
			
			 
			
			
			
			
			
		
		
			
					   //validation succeeds
					   
					  
														
													

														
														

						   
					   $config = $this->usermodel->populateallarray('people','id',$user);


 $names = $config[0]['firstname']." ".$config[0]['surname'];
					   
					   
					   
					   
					   
					   
					   
					   
					   
					   
					 	if ($this->input->post('btn_addexpense') == "expense")
					   {
												$data=array(		
			'img_id'=>$img_id,
				'imgid'=>$imgid,
			'amount'=>$amount,
				'supplier'=>$supplier,
								'bankname'=>$bankname,
				'type'=>$type,

		  	'invoice'=>$invoice,

			'user'=>$names,
		  	'description'=>$description,
		'datespent'=>$datespent,
			
			'dateposted'=>$dateposted,
			'controller' =>$controller,
				'idno' =>$idno,
				'contact'=>$contact,
				'supplier'=>$user,
				'userid'=>$userid,
						'companyid'=>$companyid,		
						'paymentmethodes'=>$paymentmethodes,		
'status'=>"Submitted",
									'branchid'=>$branchid,		

								);
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'expenses');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'expenses','invoice',$invoice);

								}
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								  $mycustomer=$this->usermodel->populateallarray('people','id', $controller);

			 $contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];

								
								
														   $correctime = date("d/m/Y H:i", strtotime($dateposted));

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully submitted your request..</div>');	
							
  						   			$message="Dear ".$firstname.", ".$user." has applied for  ". $correctamount." on ". $correctime ." regarding ". $description .". Check your erp for approval.";

  
														
													
										  
		  $this->addallpushedsms($message,$contact,$view);
								
								
								
								
								
								
								
								
										 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						$this->uploadimage($view, $img_id,$userid);
						
					}
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new expense  ..</div>');	
						 redirect($view);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Expense  was not created.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
								 redirect($view);
					   }
	    }
    }
	
		
public function uploadtaskimages($view, $img_id,$userid,$documentname) {
    
    $file= $_FILES["photo"]['name'];

if($file!=""){
		
	  
	  
	  

		$config['upload_path'] = is_dir($file).'docs/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 

	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif|pdf|doc|docx|xlsx|xls|csv|xlsm|xltx|xltm';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('imagemsg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please select correct image type  .e.g jpg,jpeg,png,gif.
						  </div>');
             redirect($view);
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$img_id,
				'userid'=>$userid,
							'documentname'=>$documentname,

								);
		$usr_result1 = $this->usermodel->add($data1,'alldocuments');
         if($usr_result1 ==TRUE){
		 		$this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have Added adocument!</div>');
 redirect($view);
		 }else{
		 
		    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please try again..
						  </div>');
		  redirect($view);
		 }
        



        }  


}



		
		}

public function uploadimage($view, $img_id,$userid) {
    
    $file= $_FILES["photo"]['name'];

if($file!=""){
		
	  
	  
	  

		$config['upload_path'] = is_dir($file).'docs/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
		 

	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif|pdf|doc|docx|xlsx|xls|csv|xlsm|xltx|xltm';
        $config["max_size"] = 20024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('imagemsg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please select correct image type  .e.g jpg,jpeg,png,gif.
						  </div>');
             redirect($view);
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$img_id,
				'userid'=>$userid,
			
								);
		$usr_result1 = $this->usermodel->add($data1,'alldocuments');
         if($usr_result1 ==TRUE){
		 		$this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have Added adocument!</div>');
 redirect($view);
		 }else{
		 
		    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please try again..
						  </div>');
		  redirect($view);
		 }
        



        }  


}



		
		}

	
	
	public function adddocuments22() {
    
    $file= (isset($_FILES["photo"]['name']));
   
$img_id = $this->input->post("img_id");
if($file!=""){
		
	  
	  
	  
	  $photo = $this->input->post("photo");

		$config['upload_path'] = is_dir($photo).'uploads/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  


        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
          echo "Not saved";

         
       
        } else {
				
		 		
 
echo "You have successfully made a upload";


        }  


}



		
		}


	

	
		public function uploadimage111($view, $img_id,$userid) {
    
    $file= $_FILES["photo"]['name'];

if($file!=""){
		
	  
	  
	  

		$config['upload_path'] = is_dir($file).'docs/';
  		$new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
     	 $new_name = $new_date.time().".".$ext;
	
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif|pdf|doc|docx';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('imagemsg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please select correct image type  .e.g jpg,jpeg,png,gif.
						  </div>');
             redirect($view);
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$img_id,
				'userid'=>$userid,
			
								);
		$usr_result1 = $this->usermodel->add($data1,'alldocuments');
         if($usr_result1 ==TRUE){
		 		$this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have Added adocument!</div>');
 redirect($view);
		 }else{
		 
		    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please try again..
						  </div>');
		  redirect($view);
		 }
        



        }  


}



		
		}

	

   
    
	public function deletelogsbyid()
    {
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d H:i:s');
		
		 $userid = $data['id'];
		 
	$mycustomer=$this->usermodel->populateallarray('people','id', $userid);


			$myname=$mycustomer[0]['firstname'];

   $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	

	  	  	  $table= $this->input->post("table");
			
							  $usr_result = $this->usermodel->deletebyid($itemid, $table);
  	if ($usr_result ==TRUE) //active user record is present
							{
								
									
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view);

							} else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
											redirect($view);
							}
	  
			  
	}
   
   
	public function deletebyid()
    {
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d H:i:s');
		
		 $userid = $data['id'];
		 
	$mycustomer=$this->usermodel->populateallarray('people','id', $userid);


			$myname=$mycustomer[0]['firstname'];

   $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	

	  	  	  $table= $this->input->post("table");
			  $productcode="";
			  
			  		if($table=="newstock"){
$newstock = $this->usermodel->populateallarray('newstock','id', $itemid);


					}
		  if($table=="productlist"){
				  $products=$this->usermodel->populateallarray('productlist','id', $itemid);
									
									$productname=$products[0]['name'];
									$productcode=$products[0]['code'];
									$buyingprice=$products[0]['buyingprice'];
									$sellingprice=$products[0]['sellingprice'];
									$qty=$products[0]['qty'];

									$branch=$products[0]['branch'];

			$actiondone=$myname ." Deleted ". $productname."  with code  of ". $productcode."  and available quantity of ". $qty." .The Buying price = ". $buyingprice." and selling price = ". $sellingprice." from branch ". $branch." at ".$postedtime;




				  
			  }else if($table=="sales"){
				   $salesdata=$this->usermodel->populateallarray('sales','id', $itemid);
									
									$total=$salesdata[0]['total'];
									$cash=$salesdata[0]['cash'];
									$dateposted=$salesdata[0]['dateposted'];
									$type=$salesdata[0]['type'];
									$invoice=$salesdata[0]['invoice'];
									$myuserid=$salesdata[0]['userid'];

$user=$this->usermodel->populateallarray('people','id', $myuserid);


			$myusername=$user[0]['firstname'];

			$actiondone=$myname ." Deleted ". $type." sales with receipt Number= ". $itemid." and Refrence No= ". $invoice."  worth  a total of =". $total." with   cash  of ". $cash." .The deleted   sales was made on ". $dateposted."  by ". $myusername." and the deletion took place  at ".$postedtime;



			  }else if($table=="products"){
				   $products=$this->usermodel->populateallarray('products','id', $itemid);
									
									$productname=$products[0]['name'];
									$productcode=$products[0]['code'];
									$buyingprice=$products[0]['buyingprice'];
									$sellingprice=$products[0]['sellingprice'];
									$qty=$products[0]['qty'];


			$actiondone=$myname ." Deleted ". $productname."  with code  of ". $productcode."  and available quantity of ". $qty." .The Buying price = ". $buyingprice." and selling price = ". $sellingprice." from   Main store and all branches at ".$postedtime;



			  }else if($table=="purchaseorder"){
				   $purchases=$this->usermodel->populateallarray('purchaseorder','id', $itemid);
									
									$purchaseinvoice=$purchases[0]['invoice'];
							  			  $actiondone=$myname ." Deleted item with id ". $itemid." from  ".  $table." table at ".$postedtime;


			  }else{
				  
				  			  $actiondone=$myname ." Deleted item with id ". $itemid." from  ".  $table." table at ".$postedtime;

			  }
			  	if($table=="newstock"){
					
					
			  	$usr_result=TRUE;
							
			
			
			
							}else{
			    $mydata = array(
									
									  'userid' => $userid,
									    'companyid' => $companyid,
									  		'ip' => $this->input->ip_address(),		
									
									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
			  			  								 										$usr_result = $this->usermodel->add($mydata,'activityloggs');

			  
							}
			  
	
			  
			  
			  
			  
			  if(($view=="user/viewprndingmoneyreceived") && ($table=="mpesasales")){
										  	  	  $code= $this->input->post("code");

										 $productdata=array(		
												'used'=>2,
													);
													 $mpesasales = $this->usermodel->populateallarray('mpesasales','code',$code);
											$myitemid=trim($mpesasales[0]['id']); 
											$this->usermodel->deletedata($myitemid,"id","mpesasales");
											$usr_result=	 $this->usermodel->updatedata($productdata,'sms_in','code',$code); 
											
								 										$usr_result = $this->usermodel->add($mydata,'activityloggs');

											

										
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully reversed the payment</div>');
											redirect($view);
	 
										return false;



								}

	if($table=="products"){
	
			  $usr_result = $this->usermodel->deletebyname("code",$productcode,"productlist");
  $usr_result = $this->usermodel->deletebyname("code",$productcode,"serials");
  
	  }					
			

	 	if($table=="permissions"){
									
							
 $this->usermodel->cleardata('permissions');
$usr_result = $this->usermodel->cleardata('permissionsactions');

								}else{
			  $usr_result = $this->usermodel->deletebyid($itemid, $table);
			  
			   $mydata = array(
									
									  'userid' => $userid,
									    'companyid' => $companyid,
									  		'ip' => $this->input->ip_address(),		
									
									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
								 if($table!="newstock"){
			$usr_result = $this->usermodel->add($mydata,'activityloggs');
								 }

  
	  }
															
								//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
									if($table=="salary"){
										  	  	  $salaryid= $this->input->post("salaryid");
												  
												  
											
											  

										$this->usermodel->deletedata($salaryid,"salaryid","employeepayments");

								} 
								
								
								
								if($table=="purchaseorder"){
												  


										$this->usermodel->deletedata($purchaseinvoice,"invoice_number","newstock");
										$this->usermodel->deletedata($purchaseinvoice,"invoice","serials");

								} 
							if($table=="newstock"){

	 // $code = $this->input->post("code");   
	     $stockfrom = $newstock[0]['type'];  
	  $qty = $newstock[0]['total'];  
$stockto = $newstock[0]['stockto'];  
$code=$newstock[0]['item_id']; 
 //$ourcode=$newstock[0]['item_id']; 


				 
					 
			if($stockfrom=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);

			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $stockfrom);

			}
		
		
$oldproductsname=$productname[0]['name']; 

  $oldbuyingprice=$productname[0]['buyingprice']; 
      $oldsellingprice=trim($productname[0]['sellingprice']);
	  
	  
   $productid=$productname[0]['id']; 

  
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$qty);
												$myproductdata=array(		
												'qty'=>$finalqty,
													);
   
	 
	 
$myactiondone=$actiondone.". Item Name: ".$oldproductsname."(".$code.")"." with S.P of : ".$oldsellingprice.", Qty: ". $qty ;
	 
	  $mydata = array(
									
									  'userid' => $userid,
									    'companyid' => $companyid,
									  		'ip' => $this->input->ip_address(),		
									
									  'actiondone' =>  $myactiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
 $this->usermodel->add($mydata,'activityloggs');

	 
	 
	 
	 
	 
	 
	 
	 
												
										
			
				if($stockfrom=="Main"){
					
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'products','id',$productid);

			}else{
				

				
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'productlist','id',$productid);

			}							
							
							
							
							
							
							
							
							if($stockto=="Main"){
								        		$myproductname = $this->usermodel->populateallarray('products','code', $code);

			}else{
				

				
				   								$myproductname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $stockto);

			}
		
					 
	 
   $myproductid=$myproductname[0]['id']; 

  
   $myavailableqty=$myproductname[0]['qty']; 
   $myfinalqty=($myavailableqty-$qty);
												$ourproductdata=array(		
												'qty'=>$myfinalqty,
													);
   
	 
												
										
			
				if($stockto=="Main"){
					
										 $usr_result =  $this->usermodel->updatedata($ourproductdata,'products','id',$myproductid);

			}else{
				

				
										 $usr_result =  $this->usermodel->updatedata($ourproductdata,'productlist','id',$myproductid);

			}							
							

							
							
							
							
							
							
							
							
							
							
							
							
							
							

								
							}		
			
								
								
								
								
								if($table=="mpesasales"){
										  	  	  $code= $this->input->post("code");

										 $productdata=array(		
												'used'=>2,
													);
								
											$this->usermodel->deletedata($itemid,"id","mpesasales");
																			 										$usr_result = $this->usermodel->add($mydata,'activityloggs');


									$usr_result=	 $this->usermodel->updatedata($productdata,'sms_in','code',$code); 


								}
								
												
								
								if($table=="mergedmpesa"){
										  	  	  $code= $this->input->post("code");

										 $productdata=array(		
												'used'=>2,
													);
								
											$this->usermodel->deletedata($itemid,"id","mergedmpesa");
									$usr_result = $this->usermodel->add($mydata,'activityloggs');


									$usr_result=	 $this->usermodel->updatedata($productdata,'sms_in','code',$code); 


								}
							
							
							
								
								if($table=="sales"){
									
										 
										$usr_result=	$this->usermodel->deletedata($itemid,"invoice","sales_order");
								 										$usr_result = $this->usermodel->add($mydata,'activityloggs');

								}
							
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view);

									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
											redirect($view);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  
  
  
  
  
  
  
    
 public function returnleaseditems()
    {
			

  

	  
	$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d H:i:s');
		
		 $userid = $data['id'];
		 
		  $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	  	  $qty= $this->input->post("qty");
	  	  $serial= $this->input->post("serial");
	  	  	  $status= $this->input->post("status");

	  	  	  $table= $this->input->post("table");
		 		$items=$this->usermodel->populateallarray('lease','id', $itemid);
 $dateleased = $this->input->post("dateleased");	
 $invoice = $this->input->post("invoice");		  
 
		  $qty = $this->input->post("qty");    
		    
		  $details = $this->input->post("details");   
		     		   		  $amount = $this->input->post("amount");   
		     		   		  $duedate = $this->input->post("duedate");   
		   		  $mode = $this->input->post("mode");   


			$code=$items[0]['product'];
					 $branch=$items[0]['branchfrom'];

					 
					 
					 
			if($branch=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);

			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

			}
		
					 
	 
   $productid=$productname[0]['id']; 


  
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$qty);
												$myproductdata=array(		
												'qty'=>$finalqty,
													);
   
	 
								if($status=="Returned and Received"){					
										
			
				if($branch=="Main"){
					
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'products','id',$productid);

			}else{
				

				
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'productlist','id',$productid);

			}							
													
								}				
													
													
													
													
													
													
			
				
					 
					 
					 
					 
					 
					 
			  
			  
			  	 $leasedata=array(		
				 
			  	'duedate'=>$duedate,
					  	'amount'=>$amount,

			
			'entrydate'=>$entrydate,
			'dateleased' => $dateleased,	
				
		  'qty' => $qty,    
			  'mode' => $mode,   
		  'invoice' => $invoice,   

		  'details' => $details,   
												
												'status'=>$status,
												
													);
					  $usr_result=	 $this->usermodel->updatedata($leasedata,'lease','id',$itemid);
								
								
								
		 
								
								
	  //$usr_result = $this->usermodel->deletebyid($itemid, $table);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
								
								
								
								
								
								
					if(($serial!="")||($serial!="n/a")){
								 $serialdata=array(		
												
												'status'=>"new",
												
													);
						 $this->usermodel->updatedata($serialdata,'serials','serial',$serial);
								}
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully updated the lease !</div>');
											redirect($view);
											
									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not returned ..please try again</div>');
								
											redirect($view);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
   
  
  
  
  
  
  
  
 public function returndamageditems()
    {
			

  

	  
	$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d H:i:s');
		
		 $userid = $data['id'];
		 
		  $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	  	  $qty= $this->input->post("qty");
	  	  $serial= $this->input->post("serial");

	  	  	  $table= $this->input->post("table");
		 		$items=$this->usermodel->populateallarray('damages','id', $itemid);


			$code=$items[0]['product'];
					 $branch=$items[0]['expendituretype'];

					 
					 
					 
			if($branch=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);

			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

			}
		
					 
					 
   $productid=$productname[0]['id']; 

  
  
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$qty);
												$myproductdata=array(		
												'qty'=>$finalqty,
													);
   
	 
													
													
			
				if($branch=="Main"){
					
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'products','id',$transactionid);

			}else{
				

				
										 $usr_result =  $this->usermodel->updatedata($myproductdata,'productlist','id',$productid);

			}							
													
													
													
													
													
													
													
													
			
				
					 
					 
					 
					 
					 
					 
			  
			  
			  
		 
								
								
	  $usr_result = $this->usermodel->deletebyid($itemid, $table);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					if(($serial!="")||($serial!="n/a")){
								 $serialdata=array(		
												
												'status'=>"new",
												
													);
						 $this->usermodel->updatedata($serialdata,'serials','serial',$serial);
								}
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully returned the product!</div>');
											redirect($view);
											
									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not returned ..please try again</div>');
								
											redirect($view);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
   
  
  
  
  
  
  
  
 public function deletegroupbyid()
    {
			

   $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	  	  $needed= $this->input->post("needed");
	  	  $randomitemidentifier= $this->input->post("randomitemidentifier");

	  	  	  $table= $this->input->post("table");

	  
	$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d H:i:s');
		
		 $userid = $data['id'];
		 		$mycustomer=$this->usermodel->populateallarray('people','id', $userid);


			$myname=$mycustomer[0]['firstname'];

		 $actiondone=$myname ." Deleted item with id ". $itemid." from  ".  $table." table at ".$postedtime;
			  
			  
			    $mydata = array(
									
									  'userid' => $userid,
									  		'ip' => $this->input->ip_address(),		
									'companyid' => $companyid,
									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
			  
			  
			  
		 
								
								
	  $usr_result = $this->usermodel->deletebyid($itemid, $table);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							$usr_result = $this->usermodel->add($mydata,'activityloggs');

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view.$randomitemidentifier."&needed=".$needed);

									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
											redirect($view.$randomitemidentifier."&needed=".$needed);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
   
   
   
   
   
	
	
   
  public function addReport()
    {
		
			$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 				 		 $title = $this->input->post("title");

		 		 $controller = $this->input->post("controller");
				$type = $this->input->post("type");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$reportdate = $this->input->post("reportdate");
						$recommendation = $this->input->post("recommendation");

			  		  $this->form_validation->set_rules("reportdate", "Date of Report ", "trim|required");
			  		  $this->form_validation->set_rules("controller", "controller ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewreport', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addReport') == "Report")
					   {
												$data=array(		
			'userid'=>$userid,
			'controller'=>$controller,
				'type'=>$type,
			'user'=>$user,
		  	'description'=>$description,
		'reportdate'=>$reportdate,
						'title'=>$title,
'dateposted'=>$dateposted,
			'recommendation'=>$recommendation,
							'companyid'=>$companyid,

			
								);
							$usr_result = $this->usermodel->add($data,'salesreport');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new Report ..</div>');	
							redirect('user/viewreport');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Report  was not created.. Try again</div>');
								
								 redirect('user/viewreport');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   
   
   
   
  public function addsupplier()
    {
		
			$session_data = $this->session->userdata('logged_in');
 
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
 $firstname = $this->input->post("firstname");
$lastname = $this->input->post("lastname");
	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");   
				  $account = $this->input->post("account"); 
 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
 $balance = $this->input->post("balance");  
				
			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsuppliers', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsupplier') == "supplier")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'firstname'=>$firstname,
			'lastname'=>$lastname,
		  	'email'=>$email,
			
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  'account' => $account, 
				 'website' => $website, 
				 'idno' => $idno, 
				 'balance' => $balance,  
							 'companyid' => $companyid,  

			
			
								);
							$usr_result = $this->usermodel->add($data,'people');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Supplier..</div>');	
							redirect('user/viewsuppliers');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Supplier  was not added.. Try again</div>');
								
								 redirect('user/viewsuppliers');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 
 
 
 
 
 
 
 
	public function uploadlostfoundimage($imgid) {
    
    $file= $_FILES["photo"]['name'];
$imgid = $this->input->post("imgid");
if($file!=""){
		$photo = $this->input->post("photo");
		$config['upload_path'] = is_dir($photo).'alllostfound/';
  		$new_date=date('Ymd');
     	 $new_name = $new_date.time().$_FILES["photo"]['name'];
		$config['file_name'] = $new_name;
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 1024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);



        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Image could not be uploaded.. Please select correct image type  .e.g jpg,jpeg,png,gif.
						  </div>');
             redirect('user/viewproducts');
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'imgid'=>$imgid,
			
			
								);
		$usr_result1 = $this->systemusermodel->uploadimage($data1,$imgid);
         if($usr_result1 ==TRUE){
		 		$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully made a post!</div>');
 redirect('user/viewproducts');
		 }else{
		 
		    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Image could not be uploaded.. Please try again  ..........
						  </div>');
		 
		 }
        



        }  


}



		
		}
 
 
 
 
 
 
 
	public function uploadimages($imgid,$companyid,$branchid,$userid) {
     		  $dateposted = date('Y-m-d H:i:s');

    $file= $_FILES["photo"]['name'];
$imgid = $this->input->post("imgid");
if($file!=""){
		$photo = $this->input->post("photo");
		$config['upload_path'] = is_dir($photo).'photoimghod/';
  		$new_date=date('Ymd');
     $ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
			 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
		
		
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 2024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);



        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
         
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$imgid,
				'companyid'=>$companyid,
		'userid'=>$userid,
			'branchid'=>$branchid,
				'date'=>$dateposted,
				);
		
      							$usr_result = $this->usermodel->add($data1,'alldocuments');

		 
		 }
        



        }  


}



		
		
 
 
  public function addmygrouping()
    {
			$session_data = $this->session->userdata('logged_in');


 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = trim($data['companyid']);
		$phone = trim($this->input->post("phone"));	
		$firstname = trim($this->input->post("firstname"));
$view = trim($this->input->post("view"));
		
		 $mygroup = $this->usermodel->getmyemployee($phone,$companyid,$firstname);
		 
	
		if($mygroup==false){
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> This member does not exist in the database. Please add the person first then assign him/her to agroup!</div>');
			 redirect('user/viewmember');
		}else{
$memberid=trim($mygroup[0]->id);
	$categoryid = $this->input->post("categoryid");	
		$confirm_result = $this->usermodel->confirmgrouping($memberid, $categoryid,$companyid);
			  
			  
			    if($confirm_result ==TRUE){
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Dublicate Error!</strong> This member has been saved but could not be assigned to that group.. Try a diffrent group or add more groups</div>');
								
								 redirect('user/viewmember');
			  }else{
				  
				  							$data=array(		
			'userid'=>$userid,
			
				'memberid'=>$memberid,
				'status'=>"1",
		  	'categoryid'=>$categoryid,
			'createdate'=>$dateposted,
			
			'companyid'=>$companyid,
				
			
								);
							$usr_result = $this->usermodel->add($data,'grouping');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a Member to a new agroup  ..</div>');	
									 redirect($view);	
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Member  was not added into anew group.. Try again</div>');
								
									 redirect($view);	
							}
				  
				  
			  }
		
		
		}
	}
 
 
 
   public function addmember()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 		
 $firstname = $this->input->post("firstname");

	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");
				 $myidnumber = $this->input->post("idnumber");
			 $idnumber="";
			  $correctbranchid = $this->input->post("branchid");
			  $mybranch="";
			 
			 
			 
			 
			    if (isset($_POST['branchid'])){
				  	 $mybranch= $correctbranchid ;
			   }else{
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 				  	 $mybranch= $branchid ;

			   }
			
			 
			 
			 
			 
			 
			 
			   if (isset($_POST['idnumber'])){
				  	 $idnumber= $myidnumber ;
			   }else{
				 $idnumber= "" ;

			   }
			

			 $categoryid="";
				 			  $group = $this->input->post("categoryid");
 
 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
  $entrydate = $this->input->post("entrydate"); 

$transactionid = time(). $userid;
		  $view = $this->input->post("view"); 
		
			  		  $this->form_validation->set_rules("phone", "Phone", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addmember') == "member")
					   {
						   
						   
						
						
						
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   				   								$confirmuser = $this->usermodel->populatealldataarray('people','phone', $phone,'companyid', $companyid);
						   			$details="Details are :Name: ".$confirmuser[0]['firstname'].", Company: ".$confirmuser[0]['company'].",Phone: ".$confirmuser[0]['phone']." .";
	   if($confirmuser !=false){
							   
						   
						   			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That personel already exist on the system.'.	$details.' Try again. Try different personel.</div>');

						  
								redirect($view);	
	   return false;
					   }
					   
					   
						   
												$data=array(		
			'userid'=>$userid,
			
				'firstname'=>$firstname,
			
		  	'email'=>$email,

						'transactionid'=>$transactionid,

			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  
				 'website' => $website, 
				 'idno' => $idno, 
				  'companyid' => $companyid, 
							  'entrydate' => $entrydate, 
							  'idnumber' => $idnumber, 
					'group' => $group, 

							  							  'branchid' => $mybranch, 


			
			
								);
							$usr_result = $this->usermodel->add($data,'people');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{












   
						   	if ($this->input->post('categoryid')>0)
							{
								 $mycategoryid = $this->input->post("categoryid");

									
																		$this->addmygrouping();

								}
						   


						
						
						  
						   		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
														   
						
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$mybranch);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewmember');
						   

						   
						   return false;
						   }											
							
						  
										  
						  $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
				  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);
if($onlineoffline=="OSCU"){
		 $apiUrl = ''.$etimsurl.'/etims-api/saveBhfCustomer';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/branches/saveBrancheCustomers';

			 }
			//Display etims CUSTOMERS
//http://192.168.1.70:8088/customers/selectCustomer			

//{"tin":"A123456789Z","bhfId":"00", "custmTin":"A987654321Z"}


        // Data to send in the JSON format
        $data = [
		    "tin" => $kra_pin,
             "bhfId" => $branch_id,
            "custNo" => $idno,
            "custTin" => $idnumber,
            "custNm" => $firstname,
            "adrs" => $comments,
            "telNo" => $phone,
            "email" => $email,
            "faxNo" => null,
            "useYn" => "Y",
            "remark" => null,
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
        // Check for cURL errors
     
						
						
						
							    // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS customer :'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewmember');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			 $resultMsg = $responseArray['resultMsg'];




            if ($resultCd == '000') {
						   
						   
						$updatedataetims=array(
											
			'recoverpassword'=>"1",		

								);							
						$usr_result =$this->usermodel->updatedata($updatedataetims,'people','transactionid',$transactionid);
						
									   
						   
						   
			}else{
			    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during saving  ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewmember');
						   	
				
			}
		
		
		}		   
			
						   
	  }				    

							
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Member..</div>');	
							
								redirect($view);	
								
																							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Member  was not added.. Try again</div>');
								
																redirect($view);	

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
    public function addplotexpense()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
				$datespent = $this->input->post("datespent");

		 		$datespent =  ($datespent)." ".$currenttime ;

		 $userid = $data['id'];
		 $currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 		
					 $view = $this->input->post("view");
		 		 $amount = $this->input->post("amount");
				$type = $this->input->post("type");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
				$controller = $this->input->post("controller");
				$idno = $this->input->post("idno");
				$contact = $this->input->post("contact");
				$receiptno = $this->input->post("receiptno");
				$img_id = $this->input->post("img_id");
				$houseno = $this->input->post("houseno");
				$plotno = $this->input->post("plotno");
				//$comment = $this->input->post("comment");

			  		  $this->form_validation->set_rules("datespent", "Date of Expenditure ", "trim|required");
			  		  $this->form_validation->set_rules("amount", "Amount ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewexpenses', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addexpense') == "expense")
					   {
												$data=array(		
			'img_id'=>$img_id,
			'amount'=>$amount,
				'type'=>$type,
			'user'=>$user,
		  	'description'=>$description,
		'datespent'=>$datespent,
			
			'dateposted'=>$dateposted,
			'controller' =>$controller,
				'idno' =>$idno,
				'contact'=>$contact,
				'receiptno'=>$receiptno,
				'userid'=>$userid,
								'imgid'=>$plotno,
				'allocationtext'=>$houseno,
'companyid' => $companyid,
			
								);
							$usr_result = $this->usermodel->add($data,'expenses');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						$this->uploadimage($view, $img_id,$userid);
						
					}
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new expense  ..</div>');	
								 redirect($view);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Expense  was not created.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   
   
   
	
	
	
	public function viewexpenditure()
	{ 
		      $this->load->view("template/headerpagemin");
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$config['base_url'] = base_url('Systemusers/viewexpenditure');
		$config['total_rows'] = $this->usermodel->count_allwhere('expenses','type','plot');
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
        $data["viewexpenses"] = $this->usermodel->displayall($config["per_page"], $page,'expenses','type','plot');
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allexpenditure',$data);
				
		$this->load->view("template/footerpage");
	
	}
  
	
	
	
	
	
	
	
	 public function updatemembershipno()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];

		  $myid = $this->input->post("myid");		
 

  $address_1 = $this->input->post("address_1"); 
  $account = $this->input->post("account"); 

	
	
	
 
				  $entrydate = $this->input->post("entrydate"); 

			  		  $this->form_validation->set_rules("myid", "User Id", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addmembership') == "membership")
					   {
						   
					 
					 
					 
					 								        		$confirmnumber = $this->usermodel->populateallarray('people','address_1', $address_1);

						   	 if ($confirmnumber!=FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.That mebership number already exist.. Try again</div>');
								
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
							








								$data=array(		
			
			
			  
		  'address_1' => $address_1,    
		 		  'updatedat' => $dateposted,    

				 		 
				 		

		
								);
							$usr_result = $this->usermodel->updatemember($data,$myid) ;
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
							
							
					   }else if ($this->input->post('btn_addmembership') == "membershipserial")
					   {
						   
					 
					 
					 				        		$confirmnumber = $this->usermodel->populateallarray('people','account', $account);

						   	 if ($confirmnumber!=FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.That mebership Serial Number already exist.. Try again</div>');
								
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
							



					 
					 

						   			$data=array(		

		 		  'updatedat' => $dateposted,    

				 		 
				 			 'account' => $account, 

		
								);
							$usr_result = $this->usermodel->updatemember($data,$myid) ;
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/viewmymembershipno?randomitemidentifier='.$myid);
							}
					   }else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	  public function updatemember()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 				  				 $computerno = $this->input->post("computerno");

		  $myid = $this->input->post("myid");		
 $firstname = $this->input->post("firstname");
 $lastname = $this->input->post("lastname");
	  $branchid = $this->input->post("branchid");

	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");   
				  				 $password = $this->input->post("password");

	  $computernouserdata = $this->input->post("computernouserdata");   


	  $sucomputernouserdatapplierbalance = $this->input->post("supplierbalance");   
			   $savedcoins = $this->input->post("savedcoins");   
			    $savedpoints = $this->input->post("savedpoints");   
				 $balance = $this->input->post("balance");   
				  				 $rate = $this->input->post("rate");


		 $limitamount = $this->input->post("limitamount");		
	$customerlimit = $this->input->post("customerlimit"); 
			
	$number = $this->input->post("number"); 


		 $salesperson = $this->input->post("salesperson");		
	$renewaldetails = $this->input->post("renewaldetails"); 
								 
 $dob = $this->input->post("dob"); 

								 
 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
  $idnumber = $this->input->post("idnumber"); 
  $categoryid = $this->input->post("categoryid"); 
  $account = $this->input->post("account"); 

 
				  $entrydate = $this->input->post("entrydate"); 

			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addmember') == "member")
					   {
						   
					 
						   			$data=array(		
			//'computerno'=>$computerno,
				'userid'=>$userid,
				'firstname'=>$firstname,
				
				'lastname'=>$lastname,
							'rate'=>$rate,
							
							
							'renewaldetails'=>$renewaldetails,
							'salesperson'=>$salesperson,
							'password'=>$password,
							'branchid'=>$branchid,
														'number'=>$number,


		  	'email'=>$email,
			'entrydate'=>$entrydate,
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  				'idnumber' => $idnumber,   

				 'website' => $website, 
				 'idno' => $idno, 
				 			 'dob' => $dob, 
   	'customerlimit'=>$customerlimit,
								'limitamount'=>$limitamount,
			 'companyid' => $companyid, 
			
				  	 'supplierbalance' => $supplierbalance, 
								 'computernouserdata' => $computernouserdata, 

				 'savedcoins' => $savedcoins, 
				 			 'savedpoints' => $savedpoints, 
				 			 'group' => $categoryid, 
				 			 'account' => $account, 

			 'balance' => $balance, 
								);
							$usr_result = $this->usermodel->updatemember($data,$myid) ;
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect('user/viewmember');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/editmember?randomitemidentifier='.$myid);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	  public function updatemembercomputer()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 				  				 $computerno = $this->input->post("computerno");

		  $myid = $this->input->post("myid");		
 $firstname = $this->input->post("firstname");
 $lastname = $this->input->post("lastname");
	  $branchid = $this->input->post("branchid");

	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");   
				  				 $password = $this->input->post("password");



	  $supplierbalance = $this->input->post("supplierbalance");   
			   $savedcoins = $this->input->post("savedcoins");   
			    $savedpoints = $this->input->post("savedpoints");   
				 $balance = $this->input->post("balance");   
				  				 $rate = $this->input->post("rate");


		 $limitamount = $this->input->post("limitamount");		
	$customerlimit = $this->input->post("customerlimit"); 
			
	$number = $this->input->post("number"); 


		 $salesperson = $this->input->post("salesperson");		
	$renewaldetails = $this->input->post("renewaldetails"); 
								 
 $dob = $this->input->post("dob"); 

								 
 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
  $idnumber = $this->input->post("idnumber"); 
  $categoryid = $this->input->post("categoryid"); 
 $computernouserdata = $this->input->post("computernouserdata"); 

 
				  $entrydate = $this->input->post("entrydate"); 

			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcomputer') == "member")
					   {
						   
					 
						   			$data=array(		
			'computerno'=>$computerno,
				'userid'=>$userid,
				'firstname'=>$firstname,
				
				'lastname'=>$lastname,
							'rate'=>$rate,
							
							
							'renewaldetails'=>$renewaldetails,
							'salesperson'=>$salesperson,
							'password'=>$password,
							'branchid'=>$branchid,
														'number'=>$number,


		  	'email'=>$email,
			'entrydate'=>$entrydate,
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  				'idnumber' => $idnumber,   

				 'website' => $website, 
				 'idno' => $idno, 
				 			 'dob' => $dob, 
   	'customerlimit'=>$customerlimit,
								'limitamount'=>$limitamount,
			 'companyid' => $companyid, 
			
				  	 'supplierbalance' => $supplierbalance, 
				
				 'savedcoins' => $savedcoins, 
				 			 'savedpoints' => $savedpoints, 
							 				 			 'computernouserdata' => $computernouserdata, 

				 			 'group' => $categoryid, 

			 'balance' => $balance, 
								);
							$usr_result = $this->usermodel->updatedata($data,'peopleregistration','id',$myid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect('user/viewcomputerno');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/editcomputer?randomitemidentifier='.$myid);
							}
					   }else if ($this->input->post('btn_addcomputer') == "confirm"){
						  $data=array(		
			'computerno'=>$computerno,
				'userid'=>$userid,
				'firstname'=>$firstname,
				
				'lastname'=>$lastname,
							'rate'=>$rate,
							
							
							'renewaldetails'=>$renewaldetails,
							'salesperson'=>$salesperson,
							'password'=>$password,
							'branchid'=>$branchid,
														'number'=>$number,


		  	'email'=>$email,
			'entrydate'=>$entrydate,
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			   'computernouserdata' => $computernouserdata, 

			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  				'idnumber' => $idnumber,   

				 'website' => $website, 
				 'idno' => $idno, 
				 			 'dob' => $dob, 
   	'customerlimit'=>$customerlimit,
								'limitamount'=>$limitamount,
			 'companyid' => $companyid, 
			
				  	 'supplierbalance' => $supplierbalance, 
				
				 'savedcoins' => $savedcoins, 
				 			 'savedpoints' => $savedpoints, 
				 			 'group' => $categoryid, 

			 'balance' => $balance, 
								);
							//$usr_result = $this->usermodel->updatedata($data,'peopleregistration','id',$myid);
					$usr_result = $this->usermodel->add($data,'people');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$this->usermodel->deletedata($myid,"id","peopleregistration");
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect('user/viewcomputerno');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/editcomputer?randomitemidentifier='.$myid);
							}
					   
						}else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
  public function updatereseller()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		  $myid = $this->input->post("myid");		
 $firstname = $this->input->post("firstname");
 $lastname = $this->input->post("lastname");

	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");   
				   $rate = $this->input->post("rate"); 

 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
 
				  $entrydate = $this->input->post("entrydate"); 

			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editreseller', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatereseller') == "member")
					   {
						   
						   
						   			$data=array(		
			'userid'=>$userid,
			
				'firstname'=>$firstname,
							'lastname'=>$lastname,

		  	'email'=>$email,
			'entrydate'=>$entrydate,
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  
				 'website' => $website, 
				 'idno' => $idno, 
				 
			 'companyid' => $companyid, 
			
						 'rate' => $rate, 

								);
							$usr_result = $this->usermodel->updatemember($data,$myid) ;
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect('user/reseller');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/updatedata');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	 public function addmypayrollsetup()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 
			 		 $idno = $this->input->post("idno");		
			 		 $nhifrelief = $this->input->post("nhifrelief");		

		 		 $kra = $this->input->post("kra");		

		 $nssf = $this->input->post("nssf");		
	$nhif = $this->input->post("nhif"); 
		 
		 $department = $this->input->post("department");		
	$manager = $this->input->post("manager");
	$marital = $this->input->post("marital");
	$dob = $this->input->post("dob");
	
		$branchcode = $this->input->post("branchcode");
	$bankcode = $this->input->post("bankcode");
	
		  $myid = $this->input->post("myid");		
 $firstname = $this->input->post("firstname");
 $lastname = $this->input->post("lastname");

	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $entrydate = $this->input->post("entrydate");    
		 $probationdate = $this->input->post("probationdate");   
		  $salary = $this->input->post("salary");   
		   $jobstatus = $this->input->post("jobstatus");   
		    $paymentmode = $this->input->post("paymentmode");   
			 $salarystartdate = $this->input->post("salarystartdate");   
			   $salaryreviewdate = $this->input->post("salaryreviewdate");   
			    $status = $this->input->post("status");   
				 $bankname = $this->input->post("bankname");   
				   $number = $this->input->post("number"); 

 $bankaccount = $this->input->post("bankaccount"); 
 $method = $this->input->post("method"); 
 $leavegroup = $this->input->post("leavegroup"); 
  $idnumber = $this->input->post("idnumber"); 

 $paid = $this->input->post("paid"); 
	  $branchid = $this->input->post("branchid");
						

			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/editmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatepayroll') == "payroll")
					   {
						 
						 
						   
						   			$data=array(	
'kra'=>$kra,
			'nssf' => $nssf,		  
		  'manager' => $manager,  
				'nhif'=>$nhif,
			'marital' => $marital,		  
		  'manager' => $manager,    
		 'department' => $department, 									
			'userid'=>$userid,
						'leavegroup' => $leavegroup,		  

			
				'firstname'=>$firstname,
							'surname'=>$lastname,
							'paid'=>$paid,
	'branchid'=>$branchid,
		  	'email'=>$email,
			'idnumber'=>$idnumber,
						'idno'=>$idno,

			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'entrydate' => $entrydate,    
		 'probationdate' => $probationdate,   
		  'salary' => $salary,   
		   'jobstatus' => $jobstatus,   
		    'paymentmode' => $paymentmode,   
			 'salarystartdate' => $salarystartdate,   
			  
			   'salaryreviewdate' => $salaryreviewdate,   
			    'status' => $status,  
				'bankname' => $bankname,   
				  				 'number' => $number, 
				 'dob' => $dob, 

				 'bankaccount' => $bankaccount, 
				 'method' => $method, 
				 	 'branchcode' => $branchcode, 
				 'bankcode' => $bankcode, 
							 'nhifrelief' => $nhifrelief, 


			
								);
				$usr_result = $this->usermodel->updatedata($data,'people','id',$myid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
								 redirect('user/mypayrollsetup?randomitemidentifier='.$myid);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
								 redirect('user/mypayrollsetup?randomitemidentifier='.$myid);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
		public function updatemyuserswap()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$createddate=date('Y-m-d');
		        	 $status = trim($this->input->post("status"));
		        	 $view = trim($this->input->post("view"));
		        	 $role = trim($this->input->post("role"));

        	 $surname = trim($this->input->post("surname"));
		   	  $firstname = trim($this->input->post("firstname"));
		  	 $email = trim($this->input->post("email"));
         	 $usertype = trim($this->input->post("usertype"));
			  $myid = $this->input->post("myid");
			  $phone = trim($this->input->post("phone"));
			  
$idno = $this->input->post("idno"); 
$gender = $this->input->post("gender"); 
$data['itemid']=$myid;

         		  $roles = trim($this->input->post("roles"));
				  
				  


		 $limitamount = $this->input->post("limitamount");		
	$customerlimit = $this->input->post("customerlimit"); 
	









		$mypermissionsdata = $this->input->post("permissions")!=false ? $this->input->post("permissions"):array();
		
		//var_dump($mypermissionsdata);
		//exit;
		 //$permissionsid = $this->input->post("permissionsid");

		$mypermissionactiondata = $this->input->post("permissionctions")!=false ? $this->input->post("permissionctions"):array();

							
							$this->form_validation->set_rules('surname', 'Surname', 'trim|required|min_length[2]|max_length[25]|xss_clean');
							$this->form_validation->set_rules('firstname', 'Other name', 'trim|required|min_length[2]|max_length[35]|xss_clean');

        		$data['member'] = $this->usermodel->populateallarray('people','id',$myid);

			$data['errors'] = validation_errors();
			
			
			
			
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
	
		$this->load->view("template/headerpagemin");
		
		$this->load->view('userdata/viewemployee',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_swaproles') == "userroles")
					   {
						   
						  
			
						   

								
								$data=array(

								'firstname'=>$firstname,
								
								'idno'=>$idno,
							
								'surname'=>$surname,
								'surname'=>$surname,
							
					
								);
								$usr_result = $this->usermodel->updatemyuser($data,$myid) ;





							if ($usr_result ==TRUE) //active user record is present
							{
								
								$success=$this->db->delete('permissions', array('userid' => $myid));

												
								if($success)
								{
													$success=$this->db->delete('permissionsactions', array('userid' => $myid));

							  $myuserid = $this->input->post("myid");
				

											$mypermissionsdata = $this->usermodel->populateallrole('rolepermissions','userid',$role);
									 	if(is_array($mypermissionsdata)){

									foreach($mypermissionsdata as $allmodule)
									{
											$moduleid= $allmodule->moduleid;
										
										$success = $this->db->insert('permissions',
										array(
										'moduleid'=>$moduleid,
										'userid'=>$myuserid));

										
									
									}
								}
								
								
											$mypermissionactiondata = $this->usermodel->populateallrole('rolepermissionsactions','userid',$role);

									
								
									 	if(is_array($mypermissionactiondata)){
				
					foreach($mypermissionactiondata as $permission_action)
					{
						$actionid= $permission_action->actionid;
						$moduleid= $permission_action->moduleid;
						$success = $this->db->insert('permissionsactions',
						array(
						'moduleid'=>$moduleid,
						'actionid'=>$actionid,
						'userid'=>$myuserid));
					}
				}
								
								
		
							
								
								}
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
							}
							
							
					   }
	
		}
	
	
	}
	
	
	
	
	
	
	
	
	
		public function updatemyuser()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$createddate=date('Y-m-d');
		        	 $status = trim($this->input->post("status"));

        	 $surname = trim($this->input->post("surname"));
		   	  $firstname = trim($this->input->post("firstname"));
		  	 $email = trim($this->input->post("email"));
         	 $usertype = trim($this->input->post("usertype"));
			  $myid = $this->input->post("myid");
			  $phone = trim($this->input->post("phone"));
			  	  $code = trim($this->input->post("code"));
         		  $password = trim($this->input->post("password"));
$idno = $this->input->post("idno"); 
$gender = $this->input->post("gender"); 
$data['itemid']=$myid;
         		  $idnumber = trim($this->input->post("idnumber"));
         		  $rate = trim($this->input->post("rate"));

         		  $category = trim($this->input->post("category"));
				  
				           		  $categoryid = trim($this->input->post("categoryid"));

				  				  		 		 $dropdown = $this->input->post("dropdown");		

				  		 		 $view = $this->input->post("view");		

				
		 		 $leavegroup = $this->input->post("leavegroup");		

		 $department = $this->input->post("department");		
	$manager = $this->input->post("manager"); 
	
	




		 $limitamount = $this->input->post("limitamount");		
	$customerlimit = $this->input->post("customerlimit"); 
	









		$mypermissionsdata = $this->input->post("permissions")!=false ? $this->input->post("permissions"):array();
		
		//var_dump($mypermissionsdata);
		//exit;
		 //$permissionsid = $this->input->post("permissionsid");

		$mypermissionactiondata = $this->input->post("permissionctions")!=false ? $this->input->post("permissionctions"):array();

							$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[100]|xss_clean');
							//$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|min_length[8]|max_length[100]|xss_clean');
							//$this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[6]|max_length[100]|xss_clean');

							$this->form_validation->set_rules('surname', 'Surname', 'trim|required|min_length[2]|max_length[25]|xss_clean');
							$this->form_validation->set_rules('firstname', 'Other name', 'trim|required|min_length[2]|max_length[35]|xss_clean');
			//$this->form_validation->set_rules('email', 'Email Account', 'trim|required|valid_email|min_length[5]');

        		$data['member'] = $this->usermodel->populateallarray('people','id',$myid);

			$data['errors'] = validation_errors();
			
			
			
			
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
	
		$this->load->view("template/headerpagemin");
		
		$this->load->view('userdata/editemployee',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_updatemyuser') == "user")
					   {
						   
						  
						   
			
						   

								
								$data=array(
								'code'=>$code,

								'firstname'=>$firstname,
								'gender'=>$gender,
								'idnumber'=>$idnumber,
								'rate'=>$rate,
								'idno'=>$idno,
								'status'=>$status,
								'email'=>trim($email),
								'surname'=>$surname,
								'surname'=>$surname,
								'password'=>$password,
									
										///'createdate'=>$createddate,
										'updatedat'=>$createddate,
									
																					'dropdown'=>$dropdown,

								'phone'=>$phone,
								'category'=>$category,
							  
				  	 'department' => $department, 
	 'group' => $categoryid, 
				 'manager' => $manager, 
				 'leavegroup' => $leavegroup, 
		 

								'usertype'=>$usertype,
							'companyid'=>trim($companyid),

								
								);
								$usr_result = $this->usermodel->updatemyuser($data,$myid) ;

							if ($usr_result ==TRUE) //active user record is present
							{
								
								$success=$this->db->delete('permissions', array('userid' => $myid));

												
								if($success)
								{
														$insertpermissions = array();

									foreach($mypermissionsdata as $allmodule)
									{
										

										
											 $insertpermissions[]=array(
											'moduleid'=>$allmodule,
											'userid'=>$myid
											);
						
									
									}
									if(!empty(($insertpermissions))){
								$this->db->insert_batch('permissions', $insertpermissions); 
									}
								}
								
								
								$success=$this->db->delete('permissionsactions', array('userid' => $myid));

									
								
								if($success)
				{
					$insertdata = array();

					foreach($mypermissionactiondata as $permission_action)
					{
						list($actionid, $module) = explode('|', $permission_action);
						
						
						 $insertdata[]=array(
						'moduleid'=>$module,
						'actionid'=>$actionid,
						'userid'=>$myid
						);
						

					}
						 	if(!empty($insertdata)){
					$this->db->insert_batch('permissionsactions', $insertdata); 
							}
				}
								
								
		
								

						
			
						
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
						 redirect($view);																
							}
					   
					   } else  if ($this->input->post('btn_updateouryuser') == "user")
					   {
						   	
								$data=array(
								'firstname'=>$firstname,
								'gender'=>$gender,
								'idno'=>$idno,
								'idnumber'=>$idnumber,
								'status'=>$status,
								'email'=>trim($email),
								'surname'=>$surname,
								'surname'=>$surname,
								'password'=>$password,
									//'createdate'=>$createddate,
									
									'updatedat'=>$createddate,
								'phone'=>$phone,
								'code'=>$code,							
								'category'=>$category,
																					'dropdown'=>$dropdown,

								'usertype'=>$usertype,
							'companyid'=>trim($companyid),
  
				  	 'department' => $department, 

				 'manager' => $manager, 
				 'leavegroup' => $leavegroup, 
		 
								
								);
								$usr_result = $this->usermodel->updatemyuser($data,$myid) ;




							if ($usr_result ==TRUE) //active user record is present
							{
								
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
						 redirect($view);																
							}
						   
					   }  
					   else
					   {
							redirect('signup');
					   }
	    }
    }
	
	
	
	
	
	public function adduser()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	    
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  $createddate = date('Y-m-d h:i:sa');

		//$createddate=date('Y-m-d');
		        	 $status = trim($this->input->post("status"));

        	 $surname = trim($this->input->post("surname"));
		   	  $firstname = trim($this->input->post("firstname"));
		  	 $email = trim($this->input->post("email"));
			  $myid = $this->input->post("myid");
			  $phone = trim($this->input->post("phone"));
			  			  $view = trim($this->input->post("view"));
			  			  $dropdown = trim($this->input->post("dropdown"));

         	 $password = trim($this->input->post("password"));
			          	 $cpassword = trim($this->input->post("cpassword"));
$idno = $this->input->post("idno"); 
$gender = $this->input->post("gender"); 
$code = $this->input->post("code"); 
 $transactionid = $this->input->post("transactionid"); 
$role = $this->input->post("role"); 

$data['itemid']=$myid;












		    $length = strlen($password);
			$length1 = strlen($cpassword);
			
			if(($length <6)||($length1 <6)){
			    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your password must be 6 characters and above. Try again. </div>');
								
						   redirect('user/viewemployee');
			false;
			}
			
			
		
		//var_dump($mypermissionsdata);
		//exit;
		 //$permissionsid = $this->input->post("permissionsid");


						$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|max_length[100]|xss_clean');
						$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|min_length[6]|max_length[100]|xss_clean');
							//$this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[6]|max_length[100]|xss_clean');

							$this->form_validation->set_rules('surname', 'Surname', 'trim|required|min_length[2]|max_length[25]|xss_clean');
							$this->form_validation->set_rules('firstname', 'Other name', 'trim|required|min_length[2]|max_length[35]|xss_clean');
			//$this->form_validation->set_rules('email', 'Email Account', 'trim|required|valid_email|min_length[5]');

        		$data['member'] = $this->usermodel->populateallarray('people','id',$myid);

			$data['errors'] = validation_errors();
			
			
			
			
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
	
		$this->load->view("template/headerpagemin");
		
		$this->load->view('userdata/viewemployee',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_addmyuser') == "user")
					   {
						   
						   
						   
						              		$checkpassword= $this->usermodel->populateallarray('people','password',$password);

						   
						   
						   if($checkpassword==true){
							       $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during saving the new user. That password is weak or not accepted. Try again </div>');
								
						   redirect('user/viewemployee');
						   false;
							   
							   
							   
						   }
						   
						   
						   
						   
						   
						   
						   
						   
						  						$transactionid = time(). $userid;

						   
					
						   
						   
   			
								
								$data=array(
								'firstname'=>$firstname,
								'gender'=>$gender,
								'idno'=>$idno,
								'dropdown'=>$dropdown,
								'transactionid'=>$transactionid,
								'userid'=>$userid,
								'status'=>$status,
								'email'=>trim($email),
								'surname'=>$surname,
								//'surname'=>$surname,
								'password'=>$password,
									'createdate'=>$createddate,
								'phone'=>$phone,
								//'transactionid'=>$transactionid,

									'code'=>$code,
								'category'=>"user",

								'Service'=>'no',
							'companyid'=>trim($companyid),

								
								);
					
					$usr_result = $this->usermodel->add($data,'people');


							if ($usr_result ==TRUE) //active user record is present
							{
								
								  $getusers = $this->usermodel->populateallarray('people','transactionid',$transactionid);
							$myuserid=$getusers[0]["id"];
						
								

											$mypermissionsdata = $this->usermodel->populateallrole('rolepermissions','userid',$role);
									 	if(is_array($mypermissionsdata)){

									foreach($mypermissionsdata as $allmodule)
									{
											$moduleid= $allmodule->moduleid;
										
										$success = $this->db->insert('permissions',
										array(
										'moduleid'=>$moduleid,
										'userid'=>$myuserid));

										
									
									}
								}
								
								
											$mypermissionactiondata = $this->usermodel->populateallrole('rolepermissionsactions','userid',$role);

									
								
									 	if(is_array($mypermissionactiondata)){
				
					foreach($mypermissionactiondata as $permission_action)
					{
						$actionid= $permission_action->actionid;
						$moduleid= $permission_action->moduleid;
						$success = $this->db->insert('permissionsactions',
						array(
						'moduleid'=>$moduleid,
						'actionid'=>$actionid,
						'userid'=>$myuserid));
					}
				}
								
								
		
		
		
		
			$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
														   
						
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewmember');
						   

						   
						   return false;
						   }											
							
						  
						  $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


if($onlineoffline=="OSCU"){
				        $apiUrl = ''.$etimsurl.'/etims-api/saveBhfUser';		
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/branches/saveBrancheUsers';

			 }    
		
	
			   
	    $data = [
		  "tin" => $kra_pin,
            "bhfId" => $branch_id,
            "userId" => $idno,
            "userNm" => $email,
            "pwd" => $password,
            "adrs" => "Admin",
            "cntc" => $phone,
            "authCd" => null,
            "remark" => " Admin",
            "useYn" => "Y",
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"

        ];
		
		
		

        // Convert the data to JSON format
        $jsonData = json_encode($data);
		
		

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
        // Check for cURL errors
			
						
						
							    // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS customer :'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewemployee');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			 $resultMsg = $responseArray['resultMsg'];




            if ($resultCd == '000') {
						   
					$updatedataetims=array(
											
			'recoverpassword'=>"1",		

								);							
						$usr_result =$this->usermodel->updatedata($updatedataetims,'people','transactionid',$transactionid);
							   
						   
						   
						   
			}else{
			    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during saving  ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewemployee');
						   	
				
			}
		
		
		}		   
			
						   
	  }				    
		
		
		
		
		
		
		
		
		
		
		
		
		
		
								
							
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
						 redirect($view);																
							}
					   
					   }
					   else
					   {
							redirect('signup');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	public function updateuserroles()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$createddate=date('Y-m-d');
		       
			 $myid = $this->input->post("myid");
			
$data['itemid']=$myid;
				  
				  

				  		 		 $view = $this->input->post("view");		

				

		 $name = $this->input->post("name");		
	
	













		$mypermissionsdata = $this->input->post("permissions")!=false ? $this->input->post("permissions"):array();
		
		
		$mypermissionactiondata = $this->input->post("permissionctions")!=false ? $this->input->post("permissionctions"):array();









							$this->form_validation->set_rules('myid', 'Role name', 'trim|required|max_length[50]|xss_clean');
			//$this->form_validation->set_rules('email', 'Email Account', 'trim|required|valid_email|min_length[5]');

        		$data['role'] = $this->usermodel->populateallarray('roles','id',$myid);

			$data['errors'] = validation_errors();
			
			
			
			
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
	
		$this->load->view("template/headerpagemin");
		
		$this->load->view('userdata/editeroles',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			 
					   //validation succeeds
					   if ($this->input->post('btn_updateuserroles') == "roles")
					   {
						   
						
						   
			
						   

								
								$success=$this->db->delete('rolepermissions', array('userid' => $myid));

												
								if($success)
								{
														$insertpermissions = array();

									foreach($mypermissionsdata as $allmodule)
									{
										

										
											 $insertpermissions[]=array(
											'moduleid'=>$allmodule,
											'userid'=>$myid
											);
						
									
									}
								$this->db->insert_batch('rolepermissions', $insertpermissions); 

								}
								
								
								$success=$this->db->delete('rolepermissionsactions', array('userid' => $myid));

									
								
								if($success)
				{
					$insertdata = array();

					foreach($mypermissionactiondata as $permission_action)
					{
						list($actionid, $module) = explode('|', $permission_action);
						
						
						 $insertdata[]=array(
						'moduleid'=>$module,
						'actionid'=>$actionid,
						'userid'=>$myid
						);
						

					}
					$this->db->insert_batch('rolepermissionsactions', $insertdata); 

				}
								
								
		
								

						
			
						
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
						
					   
					   }   
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
		  public function viewrequistions() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$subtaskid=$_GET['randomitemidentifier'];
		$data['subtaskid']=$subtaskid;

				
				$config['base_url'] = base_url('Systemusers/viewrequistions');
									$config['total_rows'] = $this->usermodel->count_allwheredata('requisition','companyid',$companyid,'subtaskid',$subtaskid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'requisition','companyid',$companyid,'subtaskid',$subtaskid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewrequistions',$data);
				
		$this->load->view("template/footerpage");
	}
	
	}
	
	
	
	
	
		  public function viewrequesteditems() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$invoice=$_GET['randomitemidentifier'];
	

				
				$config['base_url'] = base_url('Systemusers/viewrequesteditems');
									$config['total_rows'] = $this->usermodel->count_allwheredata('requisitionitems','companyid',$companyid,'invoice',$invoice);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'requisitionitems','companyid',$companyid,'invoice',$invoice);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewrequesteditems',$data);
				
		$this->load->view("template/footerpage");
	}
	
	}
	
	
	
	
	
	
		  public function viewmytaskbudget() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$projectid=$_GET['randomitemidentifier'];
		$data['projectid']=$projectid;

				
				$config['base_url'] = base_url('Systemusers/viewmybudget');
									$config['total_rows'] = $this->usermodel->count_allwheredata('projectsbudgettasks','companyid',$companyid,'projectid',$projectid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'projectsbudgettasks','companyid',$companyid,'projectid',$projectid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewmytaskbudget',$data);
				
		$this->load->view("template/footerpage");
	}
	
	}
	
	
		  public function viewmybudget() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$projectid=$_GET['randomitemidentifier'];
		$data['projectid']=$projectid;

				
				$config['base_url'] = base_url('Systemusers/viewmybudget');
									$config['total_rows'] = $this->usermodel->count_allwheredata('projectsbudget','companyid',$companyid,'projectid',$projectid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'projectsbudget','companyid',$companyid,'projectid',$projectid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewmybudget',$data);
				
		$this->load->view("template/footerpage");
	}
	
	}
 
		  public function viewprojetstasks() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$projectid=$_GET['randomitemidentifier'];
		$data['projectid']=$projectid;

				
				$config['base_url'] = base_url('Systemusers/viewprojetstasks');
									$config['total_rows'] = $this->usermodel->count_allwheredata('projectstask','companyid',$companyid,'taskid',$projectid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'projectstask','companyid',$companyid,'taskid',$projectid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewprojetstasks',$data);
				
		$this->load->view("template/footerpage");
	}
	
	}
 
	
	
	
	
	
	
	  public function groupleavedaysandcalculations() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
 $itemid = $_GET['randomitemidentifier'];
   $mytype = $_GET['type'];
   
   
   
			 $days = $_GET['days'];
		
	
   
   if($mytype=="group"){
	   
	   		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','group',$itemid);

   }else
  
 {
		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','employeeno',$itemid);

						
 }
 
    
						   	  $myconfiguration = $this->usermodel->populateallarray('people','id',$itemid);
$fromdates=$myconfiguration[0]["entrydate"];
 $data['fromdates']=$fromdates;
$data['itemid']=$itemid;
$data['mytype']=$mytype;
$data['days']=$days;

 		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	

		
		 $this->load->view('userdata/groupleavedaysandcalculations', $data);
		$this->load->view("template/footerpage");
		
	}
  }

  
	  public function groupleavedays() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
 $itemid = $_GET['randomitemidentifier'];
   $mytype = $_GET['type'];
   if($mytype=="group"){
	   
	   		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','group',$itemid);

   }else
  
 {
		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','employeeno',$itemid);

						
 }
$data['itemid']=$itemid;
$data['mytype']=$mytype;


 		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	

		
		 $this->load->view('userdata/groupleavedays', $data);
		$this->load->view("template/footerpage");
		
	}
  }

	
	
	
	  public function groupleavedays222() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
 $itemid = $_GET['randomitemidentifier'];
   $mytype = $_GET['type'];
   
   
   
			 $days = $_GET['days'];
		
	
   
   if($mytype=="group"){
	   
	   		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','group',$itemid);

   }else
  
 {
		        		$data['assignedleave']= $this->usermodel->populateall('groupleavedays','employeeno',$itemid);

						
 }
 
    
						   	  $myconfiguration = $this->usermodel->populateallarray('people','id',$itemid);
$fromdates=$myconfiguration[0]["entrydate"];
 $data['fromdates']=$fromdates;
$data['itemid']=$itemid;
$data['mytype']=$mytype;
$data['days']=$days;

 		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	

		
		 $this->load->view('userdata/groupleavedays', $data);
		$this->load->view("template/footerpage");
		
	}
  }

  
  
  
	 public function assignbranches() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
  
  $data['assignedleave']= $this->usermodel->populateall('assignbranches','employeeno',$itemid);

						

$data['itemid']=$itemid;


 		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	

		
		 $this->load->view('userdata/assignbranches', $data);
		$this->load->view("template/footerpage");
		
	}
  }




	  public function postgroupleave()
    {
		
			$sessiondata = $this->session->userdata('logged_in');

   
 	$data['id'] = $sessiondata['id'];
	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 				 		 $myitemid = $this->input->post("itemid");

		 		 $type = $this->input->post("type");
				 		 		 $mytype = $this->input->post("mytype");
 $method = $this->input->post("method");
				 
				 
				
						   	  $getleavetype = $this->usermodel->populateallarray('leavegroup','id',$type);
	$startdate=$getleavetype[0]["startdate"]; 
$enddate=$getleavetype[0]["enddate"]; 

		if($method=="manual"){
					 
				$days = $this->input->post("days");		 
					 
				 }else{
			 $days=$getleavetype[0]["total"]; 

				 }

		   	 // $startdate = $this->input->post("startdate");
			  		   	  $description = $this->input->post("description");

						  		   	  //$enddate = $this->input->post("enddate");

		    
	
			$employeeno="";
			$itemid="";
		   if( $mytype =="single"){
			   
			   $employeeno=$myitemid;
			   $itemid =NULL; 

		   }else{
			   $employeeno=NULL;  
			    $itemid =$myitemid; 
		   }
		
		
		
		
		
					  		  $this->form_validation->set_rules("type", "type", "trim|required");

				

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/groupleavedays', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assignleave') == "assignleave")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			
		  	'description'=>$description,
			 	'startdate'=>$startdate,
										'enddate'=>$enddate,
	'group'=>$itemid,
		'employeeno'=>$employeeno,
						'days'=>$days,

			'createdate'=>$createdate,
							'companyid'=>$companyid,

			
								);
							$usr_result = $this->usermodel->add($data,'groupleavedays');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned a leave..</div>');	
							redirect('user/groupleavedays?randomitemidentifier='.$myitemid.'&type='.$mytype);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								
							redirect('user/groupleavedays?randomitemidentifier='.$myitemid.'&type='.$mytype);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  
  
	

	  public function postgroupleave2()
    {
		
			$sessiondata = $this->session->userdata('logged_in');

   
 	$data['id'] = $sessiondata['id'];
	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 				 		 $myitemid = $this->input->post("itemid");

		 		 $type = $this->input->post("type");
				 		 		 $mytype = $this->input->post("mytype");

				 
				 
				
						   	  $getleavetype = $this->usermodel->populateallarray('leavegroup','id',$type);
$days=$getleavetype[0]["total"]; 
	$startdate=$getleavetype[0]["startdate"]; 
$enddate=$getleavetype[0]["enddate"]; 
			 

		   	 // $startdate = $this->input->post("startdate");
			  		   	  $description = $this->input->post("description");

						  		   	  //$enddate = $this->input->post("enddate");

		    
		// $days = $this->input->post("days");
			$employeeno="";
			$itemid="";
		   if( $mytype =="single"){
			   
			   $employeeno=$myitemid;
			   $itemid =NULL; 

		   }else{
			   $employeeno=NULL;  
			    $itemid =$myitemid; 
		   }
		
		
		
		
		
					  		  $this->form_validation->set_rules("type", "type", "trim|required");

				

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/groupleavedays', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assignleave') == "assignleave")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			
		  	'description'=>$description,
			 	'startdate'=>$startdate,
										'enddate'=>$enddate,
	'group'=>$itemid,
		'employeeno'=>$employeeno,
						'days'=>$days,

			'createdate'=>$createdate,
							'companyid'=>$companyid,

			
								);
							$usr_result = $this->usermodel->add($data,'groupleavedays');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned a leave..</div>');	
							redirect('user/groupleavedays?randomitemidentifier='.$myitemid.'&type='.$mytype);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								
							redirect('user/groupleavedays?randomitemidentifier='.$myitemid.'&type='.$mytype);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  
  
	
	
	  public function postgroupleaveandcalculation()
    {
		
			$sessiondata = $this->session->userdata('logged_in');

   
 	$data['id'] = $sessiondata['id'];
	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 				 		 $myitemid = $this->input->post("itemid");
		 		 $mytype = $this->input->post("mytype");

		 		 $type = $this->input->post("type");

		   	  $startdate = $this->input->post("startdate");
			  		   	  $description = $this->input->post("description");

						  		   	  $enddate = $this->input->post("enddate");

		    
		 $days = $this->input->post("days");
			$employeeno="";
			$itemid="";
		   if( $mytype =="single"){
			   
			   $employeeno=$myitemid;
			   $itemid =NULL; 

		   }else{
			   $employeeno=NULL;  
			    $itemid =$myitemid; 
		   }
		
	//	echo $employeeno;

		
		
		
					  		  $this->form_validation->set_rules("startdate", "Start date", "trim|required");

				
			  		  $this->form_validation->set_rules("enddate", "End date", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/startbulkcheckinreservation', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   
					if ($this->input->post('btn_confirmleaves') == "confirms")
					   {
						   
							
			$mycurrentdate = strtotime(date($startdate));

			  $finaldate = strtotime(date($enddate));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
 $days=$days;
			
			   $days= (($days / 365) * 21);
		$days= $this->formatMoney($days, true);

			   			 $used= $this->usermodel->Getalluseddaysbytype($myitemid,$type);
					$useddays=$used[0]['duration'];


	
	$days=$days-$useddays;
			   
	   
			   
								//$data['days'] = $days;
							///$data['enddate'] = $enddate;
							//$data['fromdates'] = $startdate;   
			   							//$data['itemid'] = $myitemid;   
			   							//$data['mytype'] = $mytype;   

			   //exit;
			    //$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								//<strong>Success!</strong> You have successfully assigned a leave..</div>');	
							
							redirect('user/groupleavedaysandcalculations?randomitemidentifier='.$myitemid.'&type='.$mytype.'&days='.$days.'&enddate='.$enddate.'&fromdates='.$fromdates);																
						   //$this->load->view("template/headerpagemin");
	   		        		//$data['assignedleave']= $this->usermodel->populateall('offdays','groupid',$myitemid);

		
		// $this->load->view('userdata/groupleavedays', $data);
		//$this->load->view("template/footerpage");	
			   
						   
						   
					   }else if ($this->input->post('btn_assignleaveCalculate') == "assignleave")
					   {
						

					$this->usermodel->deletedatatwo("groupleavedays","employeeno",$myitemid,"type",$type);



						
					//	   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			
		  	'description'=>$description,
			 	'startdate'=>$startdate,
										'enddate'=>$enddate,
	'group'=>$itemid,
		'employeeno'=>$employeeno,
						'days'=>$days,

			'createdate'=>$createdate,
				
			
								);
							$usr_result = $this->usermodel->add($data,'groupleavedays');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned a leave..</div>');	
							redirect('user/groupleavedaysandcalculations?randomitemidentifier='.$myitemid.'&type='.$mytype.'&days='.$days);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								//
							redirect('user/groupleavedaysandcalculations?randomitemidentifier='.$myitemid.'&type='.$mytype.'&days='.$days);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
  
  
  
	
	
	  public function postassignbranches()
    {
		
			$sessiondata = $this->session->userdata('logged_in');

   
 	$data['id'] = $sessiondata['id'];
	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 				 		 $myitemid = $this->input->post("itemid");
		 		 $status = $this->input->post("status");

		 		
			  		   	  $description = $this->input->post("description");

			  		   	  $branchid = $this->input->post("branchid");

		    
		 
		
		
		
		
					  		  $this->form_validation->set_rules("itemid", "Employee number", "trim|required");

				

				
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/assignbranches', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assignbranch') == "branch")
					   {
						   
	$productname  = $this->usermodel->populatealldatanoarray('assignbranches','branchid', $branchid,'employeeno', $myitemid);
 
					
					  if ($productname ==true)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That employee has been assigned that branch already. Try different branch.</div>');

						  
							redirect('user/assignbranches?randomitemidentifier='.$myitemid);																
	   return false;
						   }		   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			
		  	'description'=>$description,
			 	
	'employeeno'=>$myitemid,
						'branchid'=>$branchid,
						'companyid'=>$companyid,

			'createdate'=>$createdate,
				
			
								);
							$usr_result = $this->usermodel->add($data,'assignbranches');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned employee to abranch..</div>');	
							redirect('user/assignbranches?randomitemidentifier='.$myitemid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data was not saved.. Try again</div>');
								
							redirect('user/assignbranches?randomitemidentifier='.$myitemid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  
	
	
	  public function postsupervisor()
    {
		
		
			$sessiondata = $this->session->userdata('logged_in');
 	
		 
   
 	$data['id'] = $sessiondata['id'];
	$data['branchid'] = $sessiondata['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 				 		 $itemid = $this->input->post("itemid");
		 		 $title = $this->input->post("title");
			  		   	  $type = $this->input->post("type");


		   	  $startdate = $this->input->post("startdate");
			  		   	  $description = $this->input->post("description");

						  		   	  $enddate = $this->input->post("enddate");

								  		   	  $department = $this->input->post("department");

		
		
		
		
		
		
					  		  $this->form_validation->set_rules("startdate", "Start date", "trim|required");

				
			  		  $this->form_validation->set_rules("enddate", "End date", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('admin/groupleaders', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_supervisor') == "supervisor")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'title'=>$title,
			
		  	'description'=>$description,
			 	'startdate'=>$startdate,
										'enddate'=>$enddate,

		'employeeno'=>$itemid,
					
			'department'=>$department,

			'createdate'=>$createdate,
					'companyid'=>$companyid,

			'branchid'=>$branchid,
			
								);
							$usr_result = $this->usermodel->add($data,'supervisor');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added the supervisor..</div>');	
							redirect('user/groupleaders?randomitemidentifier='.$itemid.'&type='.$type);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								
							redirect('user/groupleaders?randomitemidentifier='.$itemid.'&type='.$type);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
	
	
  
  
  
  
  
  
  
	public function groupleaders() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
 $itemid = $_GET['randomitemidentifier'];
   $type = $_GET['type'];
  
  
 
		        		$data['assignedleave']= $this->usermodel->populateall('supervisor','employeeno',$itemid);

						
 
$data['itemid']=$itemid;
$data['type']=$type;


 		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	

		
		 $this->load->view('userdata/groupleaders', $data);
		$this->load->view("template/footerpage");
		
	}
  }

	
	
	
	
	
	
	
	
	
	
	public function addmyuser()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$createddate=date('Y-m-d');
		        	 $status = trim($this->input->post("status"));

        	 $surname = trim($this->input->post("surname"));
		   	  $firstname = trim($this->input->post("firstname"));
		  	 $email = trim($this->input->post("email"));
			  $myid = $this->input->post("myid");
			  $phone = trim($this->input->post("phone"));
			  			  $view = trim($this->input->post("view"));

         	 $password = trim($this->input->post("password"));
			          	 $cpassword = trim($this->input->post("cpassword"));
$idno = $this->input->post("idno"); 
$gender = $this->input->post("gender"); 
$code = $this->input->post("code"); 

$data['itemid']=$myid;
		$mypermissionsdata = $this->input->post("permissions")!=false ? $this->input->post("permissions"):array();
		
		//var_dump($mypermissionsdata);
		//exit;
		 //$permissionsid = $this->input->post("permissionsid");

		$mypermissionactiondata = $this->input->post("permissionctions")!=false ? $this->input->post("permissionctions"):array();

							//$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[8]|max_length[100]|xss_clean');
							//$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|min_length[8]|max_length[100]|xss_clean');
							//$this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[6]|max_length[100]|xss_clean');

							$this->form_validation->set_rules('surname', 'Surname', 'trim|required|min_length[2]|max_length[25]|xss_clean');
							$this->form_validation->set_rules('firstname', 'Other name', 'trim|required|min_length[2]|max_length[35]|xss_clean');
			//$this->form_validation->set_rules('email', 'Email Account', 'trim|required|valid_email|min_length[5]');

        		$data['member'] = $this->usermodel->populateallarray('people','id',$myid);

			$data['errors'] = validation_errors();
			
			
			
			
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
	
		$this->load->view("template/headerpagemin");
		
		$this->load->view('userdata/viewemployee',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_addmyuser') == "user")
					   {
						   
						  
						              		$checkpassword= $this->usermodel->populateallarray('people','password',$password);

						   
						   
						   if($checkpassword==true){
							       $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during saving the new user. That password is weak or not accepted. Try again </div>');
								
						   redirect('user/viewemployee');
						   false;
							   
							   
							   
						   }
						   
						   
						   
						   
						   
						   
   			
								
								$data=array(
								'firstname'=>$firstname,
								'gender'=>$gender,
								'idno'=>$idno,
								'status'=>$status,
								'email'=>trim($email),
								'surname'=>$surname,
								'surname'=>$surname,
								'password'=>$password,
									'createdate'=>$createddate,
								'phone'=>$phone,
									'code'=>$code,
								'category'=>"user",

								'Service'=>'no',
							'companyid'=>trim($companyid),

								
								);
					
					$usr_result = $this->usermodel->add($data,'people');


							if ($usr_result ==TRUE) //active user record is present
							{
								
								$success=$this->db->delete('permissions', array('userid' => $myid));

												
								if($success)
								{
									foreach($mypermissionsdata as $allmodule)
									{
										$success = $this->db->insert('permissions',
										array(
										'moduleid'=>$allmodule,
										'userid'=>$myid));

										
									
									}
								}
								
								
								$success=$this->db->delete('permissionsactions', array('userid' => $myid));

									
								
								if($success)
				{
					foreach($mypermissionactiondata as $permission_action)
					{
						list($actionid, $module) = explode('|', $permission_action);
						$success = $this->db->insert('permissionsactions',
						array(
						'moduleid'=>$module,
						'actionid'=>$actionid,
						'userid'=>$myid));
					}
				}
								
								
		
								
							
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated  The data..</div>');	
						 redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data  was not updated.. Try again</div>');
								
						 redirect($view);																
							}
					   
					   }
					   else
					   {
							redirect('signup');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	

 
 public function searchallmembers()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		//$searchterm = trim($this->usermodel->allterms_handler($this->input->get_post('searchterm', TRUE)));
				//$view = trim($this->usermodel->allterms_handler($this->input->get_post('view', TRUE)));
				$searchterm= trim($this->usermodel->allterms_handler($this->input->get_post('searchterm', TRUE),'searchterm'));
				$view = trim($this->usermodel->allterms_handler($this->input->get_post('view', TRUE),'view'));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallmembers';
		$config['total_rows'] = $this->usermodel->search_record_count($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			$data['total_people'] = $this->usermodel->countMembers($companyid); 
		$data['viewmember'] = $this->usermodel->searchallamembers($searchterm,$limit);
		
		//
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view($view,$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 
 
 
 public function searchallusers()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallusers';
		$query = $this->usermodel->searchallusers($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['viewemployee'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewemployee',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
 public function searchallusersLeave()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallusers';
		$query = $this->usermodel->searchallusers($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['viewemployee'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/leavebalance',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
 
 public function searchallquotation()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallquotation';
		$query = $this->usermodel->searchallquotation($searchterm,$limit,$companyid);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['viewpurchases'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/allquatation',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 
 public function searchallmyevents()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallmyevents';
		$query = $this->usermodel->searchallevents($searchterm,$limit,$companyid);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['viewevents'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewevents',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
 public function searchtimer()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchtimer';
		$query = $this->usermodel->searchtimer($searchterm,$limit,$companyid);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 60;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['timer'] = $query['data'];

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewtimer',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
 
 public function searchallmydeals()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallmembers';
		$config['total_rows'] = $this->usermodel->search_dealscount($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viedeals'] = $this->usermodel->searchallmydeals($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
 public function viewleaves()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		

		$config['base_url'] = base_url() . 'Systemusers/viewleaves';
				$query  = $this->usermodel->displayalldatatwo($config["per_page"], $page,'leaves','userid',$userid,'companyid',$companyid);


		$config['total_rows'] = $query['records'];
		
	
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['report'] = $query['data'];
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewleaves",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 
    public function addggestion()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$postedtime =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 	
				  

				  $title = $this->input->post("title");

		   	  $description = $this->input->post("description");
			  
		  $this->form_validation->set_rules("description", "Description", "trim|required");
		    
			
			
			
			
			
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/postsuggestion', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcomment') == "comment")
					   {
												$data=array(		
			'userid'=>$userid,
		  	'description'=>$description,
			'postedtime'=>$postedtime,
				'title'=>$title,
				'status'=>"active",

				
			// 
			
								);
														$usr_result = $this->usermodel->add($data,'suggestions');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Posted a new  comment..</div>');	
										
																 redirect('user/suggestion');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
								 redirect('user/suggestion');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 public function announcement()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		

		$config['base_url'] = base_url() . 'Systemusers/announcement';
				$query  = $this->usermodel->displayalldatatwo($config["per_page"], $page,'announcement','id >',1,'companyid',$companyid);


		$config['total_rows'] = $query['records'];
		
	
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['announcement'] = $query['data'];
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/announcement",$data);
				
		$this->load->view("template/footerpage");
		
	}
	public function leavetypes()
	{ 
		 $this->load->view("template/headerpagemin");
	
		 $this->load->view("template/tableheader");

	
$data['Leave'] = $this->usermodel->populatealldata('leavetypes','id','DESC');

				$this->load->view('userdata/leavetypes',$data);
		$this->load->view("template/footerpage");
	
	}
	
		public function addnewpost()
    {
  $postedtime = date('Y-m-d h:i:sa');
		
		  	 $name = $this->input->post("name");
			 
		   	  $description = $this->input->post("description");
		  $this->form_validation->set_rules("name", "Post Name", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		 $this->load->view('admindata/addpost',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_addpost') == "post")
					   {
								
								$data=array(		
			'name'=>$name,
			'createdat'=>$postedtime,
		  	'description'=>$description,
				
								);
												$usr_result =$this->usermodel->add($data,'post');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new Post!</div>');
								
								 redirect('user/addpost');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
								 redirect('user/addpost');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	  
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
			 public function groupoffdays() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
	

	   
	   		        		$data['assignedleave']= $this->usermodel->populateall('offdays','groupid',$itemid);





 		 $this->load->view("template/headerpagemin");
	 		 $this->load->view("template/tableheader");
$data['itemid']=$itemid;

		
		 $this->load->view('userdata/groupoffdays', $data);
		$this->load->view("template/footerpage");
		
	}
  }

		
		
	
	
	
	public function postgroupoffdays()
    {
		
			$sessiondata = $this->session->userdata('adminlogged_in');

   
 	$data['userid'] = $sessiondata['userid'];
	$data['companyid'] = $sessiondata['companyid'];
	 $companyid = $data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$createdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['userid'];
		 
		 				 		 $itemid = $this->input->post("itemid");
		 		

		 		 $type = $this->input->post("type");

		   	  $offday = $this->input->post("offday");

						  		   	  $title = $this->input->post("title");

		    						  		   	  $fromdate = $this->input->post("fromdate");
		    						  		   	  $todate = $this->input->post("todate");

		 		    						  		   	  $day = $this->input->post("day");

		$myoffdays="";
		
		
		
					  		  $this->form_validation->set_rules("offday", "Off date", "trim|required");

				
			  		  $this->form_validation->set_rules("type", "Type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/groupoffdays', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assignoffdays') == "offdays")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			
			 	'offday'=>$offday,
										'title'=>$title,
	'groupid'=>$itemid,
	

			'createdate'=>$createdate,
				
			
								);
							$usr_result = $this->usermodel->add($data,'offdays');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned a off day..</div>');	
							redirect('user/groupoffdays?randomitemidentifier='.$itemid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								
							redirect('user/groupoffdays?randomitemidentifier='.$itemid);																
							}
					   } else if ($this->input->post('btn_assigmultiplenoffdays') == "offdays")
					   {
						   
						   
						   
								  for ($i = strtotime($fromdate); $i <= strtotime($todate); $i = strtotime('+1 day', $i)) {
  if (date('N', $i) == $day){
	  
	  
  //Monday == 1
     $myoffdays=date('Y-m-d', $i);

   
						   
					
			  

			   
						   
												$data=array(		
			'userid'=>$userid,
			
				'type'=>$type,
			
			 	'offday'=>$myoffdays,
										'title'=>$title,
	'groupid'=>$itemid,
	

			'createdate'=>$createdate,
				
			
								);
							$usr_result = $this->usermodel->uploadata($data);

						$usr_result = $this->usermodel->uploadata($data,'offdays');
						} }
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully assigned a off day..</div>');	
							redirect('user/groupoffdays?randomitemidentifier='.$itemid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Date was not saved.. Try again</div>');
								
							redirect('user/groupoffdays?randomitemidentifier='.$itemid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

		public function supervisor()
	{ 
		 $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
	
		
	
$data['supervisor'] = $this->usermodel->populatealldata('supervisor','id','ASCE');

				$this->load->view('userdata/supervisor',$data);
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	public function addLeavegroup()
    {
  $postedtime = date('Y-m-d h:i:sa');
		
		  	 $name = $this->input->post("name");
			  $startdate = $this->input->post("startdate");
			  $enddate = $this->input->post("enddate");
		
			  			  $total = $this->input->post("total");

			  		   	  $defaultleavetype = $this->input->post("defaultleavetype");

		   	  $description = $this->input->post("description");
		  $this->form_validation->set_rules("name", "Group Leave Name", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		 $this->load->view('userdata/leavetypes',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_Leavetgroup') == "Group")
					   {
								
								$data=array(		
			'name'=>$name,
			'enddate'=>$enddate,
		  	'startdate'=>$startdate,
				'defaultleavetype'=>$defaultleavetype,
								'description'=>$description,
																'total'=>$total,


								);
							
					$usr_result =$this->usermodel->add($data,'leavegroup');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new Leave group!</div>');
								
								 redirect('user/leavegroup');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
								 redirect('user/leavegroup');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

public function leavegroup()
	{ 
		
 		 $this->load->view("template/headerpagemin");
	 		 $this->load->view("template/tableheader");
		
	
$data['leavegroup'] = $this->usermodel->populatealldata('leavegroup','id','ASCE');

				$this->load->view('userdata/leavegroup',$data);
		$this->load->view("template/footerpage");
	
	}
			 public function adddepartment()
    {
         		  	 //$code = $this->input->post("code");

		  	 $name = $this->input->post("name");
		   	  $description = $this->input->post("description");
		  $this->form_validation->set_rules("name", "department Name", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		 $this->load->view('userdata/department',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_department') == "department")
					   {
								
								$data=array(		
			'name'=>$name,
		  	'description'=>$description,
			
								);
		$usr_result = $this->usermodel->add($data,'department');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new department!</div>');
								
								 redirect('user/department');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
								 redirect('user/department');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
							public function department()
	{ 
		 $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
$data['department'] = $this->usermodel->populatealldata('department','id','DESC');

				$this->load->view('userdata/department',$data);
		$this->load->view("template/footerpage");
	}
	
								public function addpost()
	{ 
		 $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");

				$this->load->view('userdata/addpost');
		$this->load->view("template/footerpage");
	}
		
	
	
	public function addLeave()
    {
  $postedtime = date('Y-m-d h:i:sa');
		
		  	 $name = $this->input->post("name");
			  $gender = $this->input->post("gender");
			  			  $deduct = $this->input->post("deduct");

		   	  $description = $this->input->post("description");
		  $this->form_validation->set_rules("name", "Leave Name", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		 $this->load->view('userdata/leavetypes',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_Leavetype') == "Leave")
					   {
								
								$data=array(		
			'name'=>$name,
			'createdate'=>$postedtime,
		  	'description'=>$description,
					  	'deduct'=>$deduct,

				'gender'=>$gender,
								);
													$usr_result = $this->usermodel->add($data,'leavetypes');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new Leave type!</div>');
								
								 redirect('user/leavetypes');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. Try again</div>');
								
								 redirect('admin/leavetypes');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
		  public function manageleave() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];

   	$data['itemid'] = $itemid;
	
	

 		 $this->load->view("template/headerpagemin");
	

		
		 $this->load->view('userdata/manageleave', $data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  
	public function postleaves()
    {
         if ($this->input->post('btn_postrejectleaves') == "leaves")
					   {
							  
		
 $session_data = $this->session->userdata('logged_in');

     $dateposted = date('Y-m-d H:i:s');
	 
	   $correctime = date("d/m/Y H:i", strtotime($dateposted));
									  
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
         //$postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
		     $postedtime = date('Y-m-d H:i:s');

 		//$postedtime =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];	
 $approval = $this->input->post("approval");
 $status = $this->input->post("status");

		   	  $comments = $this->input->post("comments");

		   	  $itemid = $this->input->post("itemid");

  $leaves = $this->usermodel->populateallarray('leaves','id',$itemid);
$previouscomments=$leaves[0]["comments"];
$finalcomment="";
  $mycustomer=$this->usermodel->populateallarray('people','id', $leaves[0]["userid"]);

			$contact=$mycustomer[0]['phone'];
			$firstname=$mycustomer[0]['firstname'];
			 $mystatus=$this->usermodel->populateallarray('status','id', $status);

			$leavestatus=$mystatus[0]['name'];
						   			$actiondone="Your leave has been ". $leavestatus.".on: ". $correctime ." Comments are:  ". $comments.".";
  						   			$message="Dear ".$firstname.", Your leave has been ". $leavestatus." on ". $correctime .".Check your erp for comments.";

  
  
  
if($previouscomments !=""){
	$finalcomment=$previouscomments.$actiondone;
	
}else{
		$finalcomment=$actiondone;

	
}
 if($approval !="no"){
	 
	 
	 
	 		$data=array(
			'manager'=>$approval,						
		'updateddate'=>$postedtime,	
			'updatedby'=>$userid,
		  	'status'=>$status,
					  	'comments'=>$finalcomment,

			
         
								);

	 
 }else{
	 	$data=array(
		'updateddate'=>$postedtime,	
			'updatedby'=>$userid,
		  	'status'=>$status,
					  	'comments'=>$finalcomment,

			
         
								);
	 
 }








		 
						

								
								
								
								$usr_result = $this->usermodel->updatedata($data,'leaves','id',$itemid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									$myview="user/viewotherleaves";				  
		  $this->addallpushedsms($message,$contact,$myview);
		  
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"> <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Approved the leave days.</div>');
							redirect('user/viewotherleaves');
								 
							}
							else if ($usr_result ==FALSE) 
							{     
							redirect('user/viewotherleaves');
						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"> <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Leave days was not approved.. Try again</div>');
								
								
								}
							}
					   else
					   {
							redirect('login');
					   }
	    
    }
	
	
	
    
  
  
  
  
	public function allleaves()
	{ 
		 $this->load->view("template/headerpagemin");
			$session_data = $this->session->userdata('logged_in');

	$data['id'] = $session_data['id'];
 		
	$userid= $data['id'] ;
	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
			  		        		$data['report']= $this->usermodel->populatealldatawhere('leaves','id','DESC','companyid',$companyid);
		 $this->load->view("template/tableheader");


				$this->load->view('userdata/viewotherleaves',$data);
		$this->load->view("template/footerpage");
	}
  
  
  
  
  
  
  
  
  
	public function viewotherleaves()
	{ 
		 $this->load->view("template/headerpagemin");
			$session_data = $this->session->userdata('logged_in');

	$data['id'] = $session_data['id'];
 		
	$userid= $data['id'] ;
	
	
			  		        		$data['report']= $this->usermodel->populatealldatawhere('leaves','id','DESC','manager',$userid);


				$this->load->view('userdata/viewotherleaves',$data);
		$this->load->view("template/footerpage");
	}
	public function myleaves()
	{ 
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$postedtime =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		$biodata= $this->usermodel->populateallarray('people','id',$userid);
		
$group=$biodata[0]['leavegroup'];
		
	
		$data['announcement'] = $this->usermodel->GetBalanceDaysByGroup($userid,$group);

				$this->load->view('userdata/myleaves',$data);
		$this->load->view("template/footerpage");
	}
			public function getmyleaves()
	{ 
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $userid = $_GET['randomitemidentifier'];
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$postedtime =  ($postedtime)." ".$currenttime ;
		
				$this->load->view("template/headerpagemin");
		$biodata= $this->usermodel->populateallarray('people','id',$userid);
		
$group=$biodata[0]['leavegroup'];
		
	
		$data['announcement'] = $this->usermodel->GetBalanceDaysByGroup($userid,$group);

				$this->load->view('userdata/myleaves',$data);
		$this->load->view("template/footerpage");
	}
	}
	public function postmyleave()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:s');
 		$postedtime =  ($postedtime)." ".$currenttime ;
	 $userid = $data['id'];
		
			  if (isset($_GET['randomitemidentifier'])){

//$userid=	$_GET['userid'];

$randomitemidentifier = $_GET['randomitemidentifier'];

		 $this->load->view("template/headerpagemin");
		
		$myleave= $this->usermodel->populateallarray('leaves','id',$randomitemidentifier);


		$duration=$myleave[0]['duration'] ;
						 $enddate =	$myleave[0]['enddate'];
						$status =$type=$myleave[0]['type'] ;
						 $incharge=	$myleave[0]['status'] ;
						$description=	$myleave[0]['incharge'] ;
							$description=$myleave[0]['description'] ;
							$startdate=$myleave[0]['startdate'];
							
					$data['duration'] = $duration;
							$data['enddate'] = $enddate;
							$data['type'] = $type;
							$data['status'] = $status;
							$data['incharge'] = $incharge;
							$data['description'] = $description;
							$data['startdate'] = $startdate;
							$data['controller'] = $controller;

							$data['applicationid'] =$randomitemidentifier;

				$this->load->view('userdata/applyleave',$data);
		$this->load->view("template/footerpage");
    

			  } else {
		
		
		
	

		
		
		 // $userid = $this->input->post("userid");
		
		 
				  $status = $this->input->post("status");
			
		 		 $type = $this->input->post("type");
				 
				 
				 		 		 $applicationid = $this->input->post("applicationid");

				 
				 
				 
				 

		   	  $description = $this->input->post("description");
			  
		    			$controller = $this->input->post("controller");

			$enddate = $this->input->post("enddate");
			  $startdate = $this->input->post("startdate");
			
								  $myduration = $this->input->post("duration");

				

		
			  $incharge = $this->input->post("incharge");
					  $this->form_validation->set_rules("type", "Leave type", "trim|required");

			
			
			$mycurrentdate = strtotime(date($startdate));

			  $finaldate = strtotime(date($enddate));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
$days=$days+1;			
			
			
			
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/applyleave', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			
			
		
			
			
			
			
			
			
				$biodata= $this->usermodel->populateallarray('people','id',$userid);
		
 $group=$biodata[0]['leavegroup'];
$manager=$biodata[0]['manager'];

		$finaltotaldays=0;	
						$usr_resultDaysByuser = $this->usermodel->GetRemainingDaysByuser($userid,$type);
						$userdays=$usr_resultDaysByuser[0]['days'];

							$usr_resultDaysBygroup = $this->usermodel->GetRemainingDaysByGroup($group,$type);
							$usr_resultRemainingDays = $this->usermodel-> GettheUsedDaysByuser($userid,$type);
							 $useddays=$usr_resultRemainingDays[0]['duration'];
if($usr_resultDaysBygroup[0]['days']==""){
	$groupdays=0;
}else{
$groupdays=$usr_resultDaysBygroup[0]['days'];	
}
			//echo $userdays;		
			//exit;
				$finaltotaldays=(($groupdays+$userdays)-$useddays);
			
		
			
			$totaloffdays= $this->usermodel->GetOffDays($group,$startdate,$enddate);
			 $offday=$totaloffdays[0]['offday'];
			 
			 $totalhalfoffdays= $this->usermodel->GethalfOffDays($group,$startdate,$enddate);
			 $halfoffdays=($totalhalfoffdays[0]['offday']/2);
			
		
	  $duration  =$days-$offday-$halfoffdays;
		
			
			
			
			
			
		
			
			
					   //validation succeeds
					 	if ($this->input->post('btn_leave') == "leave")
					   {
						   
						   if($duration>$finaltotaldays){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not apply for more than remaining/entitled leave days which is currently :'.$finaltotaldays.'. Try again </div>');
								
								 redirect('user/applyleave');
								 return false;
				
								}
			
						   
						   
						   
						   if($days < 1){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not apply for negative days. Try again </div>');
								
								 redirect('user/applyleave');
								 return false;
				
								}
			   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						 if($controller !="Pick"){
							 
							$manager=$controller;
						 }
						   
						
						   
						   
						   				$updata=array(		
		  	'description'=>$description,
			'updateddate'=>$postedtime,
			'type'=>$type,
			'status'=>$status,
			'enddate'=>$enddate,
					'duration'=>$duration,
					'manager'=>$manager,

			'incharge'=>$incharge,
			
						'updatedby'=>$userid,

								);
						   
												$data=array(		
			'userid'=>$userid,
		  	'description'=>$description,
			'postedtime'=>$postedtime,
			'type'=>$type,
			'startdate'=>$startdate,
			'status'=>$status,
			'enddate'=>$enddate,
					'duration'=>$duration,
					'manager'=>$manager,

			'incharge'=>$incharge,
			
			
								);
							//$usr_result = $this->studentbiodatamodel->addnewissue($data);
						
					
						
							 if($applicationid==""){
						$usr_result = $this->usermodel->add($data,'leaves');

							}else{
								$usr_result = $this->usermodel->updatedata($updata,'leaves','id',$applicationid);

								}
							
								

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Submitted a new  leave request..</div>');	
										$this->uploadlostfoundimage($img_id) ;
																 redirect('user/viewleaves');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Leave was not submitted  Try again</div>');
								
								 redirect('user/applyleave');
							}
							
					   }
					   else if ($this->input->post('btn_confirmleave') == "confirm")
					   {
						$data['duration'] = $duration;
							$data['enddate'] = $enddate;
							$data['type'] = $type;
							$data['status'] = $status;
							$data['incharge'] = $incharge;
							$data['description'] = $description;
							$data['startdate'] = $startdate;
							$data['applicationid'] = $applicationid;
									$data['controller'] = $controller;

							
							  $this->load->view("template/headerpagemin");

		
							 $this->load->view('userdata/applyleave', $data);
							$this->load->view("template/footerpage");
												
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	}
public function posotherleave()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$postedtime =  ($postedtime)." ".$currenttime ;
		// $userid = $data['id'];
		
			  if (isset($_GET['randomitemidentifier'])){

$userid=	$_GET['userid'];

$randomitemidentifier = $_GET['randomitemidentifier'];

		 $this->load->view("template/headerpagemin");
		
		$myleave= $this->usermodel->populateallarray('leaves','id',$randomitemidentifier);


		$duration=$myleave[0]['duration'] ;
						 $enddate =	$myleave[0]['enddate'];
						$status =$type=$myleave[0]['type'] ;
						 $incharge=	$myleave[0]['status'] ;
						$description=	$myleave[0]['incharge'] ;
							$description=$myleave[0]['description'] ;
							$startdate=$myleave[0]['startdate'];
							
					$data['duration'] = $duration;
							$data['enddate'] = $enddate;
							$data['type'] = $type;
							$data['status'] = $status;
							$data['incharge'] = $incharge;
							$data['description'] = $description;
							$data['startdate'] = $startdate;

							$data['applicationid'] =$randomitemidentifier;

				$this->load->view('userdata/applyleaveforothers',$data);
		$this->load->view("template/footerpage");
    	
			  } else {
		
	
		
		
		
		
		   $userid = $this->input->post("userid");
		
		 
				  $status = $this->input->post("status");
			
		 		 $type = $this->input->post("type");
				 
				 
				 		 		 $applicationid = $this->input->post("applicationid");

				 
 
				 

		   	  $description = $this->input->post("description");
			  
		    
			$enddate = $this->input->post("enddate");
			  $startdate = $this->input->post("startdate");
			
								  $myduration = $this->input->post("duration");

				

		
			  $incharge = $this->input->post("incharge");
					  $this->form_validation->set_rules("type", "Leave type", "trim|required");

			
			
			$mycurrentdate = strtotime(date($startdate));

			  $finaldate = strtotime(date($enddate));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
$days=$days+1;			
			
			
			
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/applyleaveforothers', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			
			
		
			
			$leavetypes= $this->usermodel->populateallarray('leavetypes','id',$type);
		
 $leavename=$leavetypes[0]['name'];
			
			
			
			
				$biodata= $this->usermodel->populateallarray('people','id',$userid);
		
 $group=$biodata[0]['leavegroup'];
$manager=$biodata[0]['manager'];

		$finaltotaldays=0;	
						$usr_resultDaysByuser = $this->usermodel->GetRemainingDaysByuser($userid,$type);
						$userdays=$usr_resultDaysByuser[0]['days'];

							$usr_resultDaysBygroup = $this->usermodel->GetRemainingDaysByGroup($group,$type);
							$usr_resultRemainingDays = $this->usermodel-> GettheUsedDaysByuser($userid,$type);
							 $useddays=$usr_resultRemainingDays[0]['duration'];

				$groupdays=$usr_resultDaysBygroup[0]['days'];
			
				$finaltotaldays=(($groupdays+$userdays)-$useddays);
			
		
			
			$totaloffdays= $this->usermodel->GetOffDays($group,$startdate,$enddate);
			 $offday=$totaloffdays[0]['offday'];
			 
			 $totalhalfoffdays= $this->usermodel->GethalfOffDays($group,$startdate,$enddate);
			 
			 
			/// var_dump($totalhalfoffdays);
			 
			  $halfoffdays=($totalhalfoffdays[0]['offday']/2);

	   $duration = $days-$offday-$halfoffdays;

			
			
			
			
			
		
			
			
					   //validation succeeds
					 	if ($this->input->post('btn_leave') == "leave")
					   {
						   
						   if($duration > $finaltotaldays){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not apply for more than remaining/entitled ('.$leavename.')  days which is currently :'.$finaltotaldays.'. Try again </div>');
								
								 redirect('user/applyleaveforothers');
								 return false;
				
			}
			
						   
						   
						 
						   if($days < 1){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not apply for negative days. Try again </div>');
								
								 redirect('user/applyleaveforothers');
								 return false;
				
								}
			     
						   
						   
						   
						   
						   				$updata=array(		
		  	'description'=>$description,
			'updateddate'=>$postedtime,
			'type'=>$type,
			'status'=>$status,
			'enddate'=>$enddate,
					'duration'=>$duration,
					'manager'=>$manager,

			'incharge'=>$incharge,
			
						'updatedby'=>$userid,

								);
						   
												$data=array(		
			'userid'=>$userid,
		  	'description'=>$description,
			'postedtime'=>$postedtime,
			'type'=>$type,
			'startdate'=>$startdate,
			'status'=>$status,
			'enddate'=>$enddate,
					'duration'=>$duration,
					'manager'=>$manager,

			'incharge'=>$incharge,
			
			
								);
							//$usr_result = $this->studentbiodatamodel->addnewissue($data);
						
					
						
							 if($applicationid==""){
						$usr_result = $this->usermodel->add($data,'leaves');

							}else{
								$usr_result = $this->usermodel->updatedata($updata,'leaves','id',$applicationid);

								}
							
								

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Submitted a new  leave request..</div>');	
										$this->uploadlostfoundimage($img_id) ;
																 redirect('user/viewleaves');
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Leave was not submitted  Try again</div>');
								
								 redirect('user/applyleaveforothers');
							}
							
					   }
					   else if ($this->input->post('btn_confirmleave') == "confirm")
					   {
						$data['duration'] = $duration;
							$data['enddate'] = $enddate;
							$data['type'] = $type;
							$data['status'] = $status;
							$data['incharge'] = $incharge;
							$data['description'] = $description;
							$data['startdate'] = $startdate;
							$data['applicationid'] = $applicationid;
							$data['myuserid'] = $userid;
							
							  $this->load->view("template/headerpagemin");

		
							 $this->load->view('userdata/applyleaveforothers', $data);
							$this->load->view("template/footerpage");
												
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	}
 	
		public function applyleave()
	{ 
	
	
	
	
	
	
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/applyleave');
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
			public function viewemployeenote()
	{ 
	
	
	
	
	
	
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/viewemployeenote');
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function applyleaveforothers()
	{ 
	
	
	
	
	
	
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/applyleaveforothers');
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	 public function editquotation()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	

		
		
	$codes = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($codes[0]));
	  $mode = trim($this->input->post("mode"));  


 
 //
 
 
$qty = trim($this->input->post("myqty"));
	  $discount = trim($this->input->post("discount"));
	  $myview = trim($this->input->post("view"));  
	  
	  
	  
	  
	  
	  
	  $unit = trim($this->input->post("unit"));
	  
	  if(($unit=="")||($unit==0)){
		$unit=1;  
	  }
	 
	  
	  $description = trim($this->input->post("description"));
	  $totalweight = trim($this->input->post("totalweight"));  
	  	  		  $deliverymethod = trim($this->input->post("deliverymethod"));
	  	  		  $buyingprice = trim($this->input->post("buyingprice"));

	  	  $sellingprice = trim($this->input->post("sellingprice"));  

	  
	  


		  $mycategoryid = trim($this->input->post("mycategoryid"));

  
		      $invoice = trim($this->input->post("invoice")); 
						      $productname=$this->usermodel->populateallarray('products','code',$code);
							

						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
							redirect($myview);	
	
								
							//redirect('user/viewsales');						   
						   return false;
						   }
						  $productid=$productname[0]['id'];  
 $newbuyingprice=$productname[0]['buyingprice']; 
      $newsellingprice=trim($productname[0]['sellingprice']); 
	  
	  
	  if($newsellingprice!=$sellingprice){
		  
		  $sellingprice=$sellingprice;
	  }else{
		  
		   $sellingprice=$newsellingprice; 
	  }
	  
		
		
	
		
	
		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 


			$maincapital = $this->usermodel->populateallarray('quotation','invoice',$invoice);

	    $currentamount=trim($maincapital[0]['amount']);

//exit;

	if($deliverymethod=="requisition"){
		 $buyingprice=$buyingprice-$discount;
  $finaldiscount= ($discount*$qty);
     $amount= (($qty)* ($buyingprice));
	  $sellingprice=$newsellingprice;
	}else{
	 $sellingprice=$sellingprice-$discount;
  $finaldiscount= ($discount*$qty);
     $amount= (($qty)* ($sellingprice));	
	 $buyingprice=$newbuyingprice;
		
	}

$finalamount=$currentamount+$amount;
   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
	 $taxtype=trim($productname[0]['taxtype']);
							 $finaltax=0;
							 
							
			
						 $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);	   
						   $tax2rate=$myconfiguration[0]["tax2rate"];

							$display2=$myconfiguration[0]["display2"]; 
			
			
			
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								// $mytax=1+($tax_included/100); 
								// $vatable=($sellingprice/$mytax);
								 //$myfinaltax=(($sellingprice-$vatable)*$qty);
								
								//$finaltax= $this->formatMoney($myfinaltax, true);
								 
								 
								 
								 
									 //
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 $vatable=((double)$sellingprice  * (double)$qty);	

								  $getvatable=($sellingprice*$mytax);	
								 $finaltax=(((double)$getvatable-(double)$sellingprice)*$qty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{
	
								 $mytax=1+($tax_included/100); 
								  $vatable=(($sellingprice/$mytax) *(double)$qty );
								   $finaltax=(($sellingprice*$qty)-(double)$vatable);

									}
								 	 
								 if($display2=="yes"){

	
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$qty)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	 $taxable= $this->formatMoney($ttoltaxable, true);

			
			
				
			
			//exit;

			
			

	}else{
	 $finaltax2=0;
		$taxable= $this->formatMoney(($vatable), true);


	}
					
							 	$finaltax= $this->formatMoney($finaltax, true); 
			
			
			
			
			
							 }
			
			
		
			
			
			
			
		
			
			
			
			///
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    																												redirect($myview);	
	//redirect('user/viewnewquotation?randomitemidentifier='.$invoice);	

		}
		 else
		{
			
			
					   					$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branchid, 
		  				'type'=>'QT',

		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
						'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
							'mode' => $mode, 

						'unit' => $unit,
				'description' => $description, 
							'totalweight' => $totalweight, 
							
							'taxable'=>$taxable,
'tax2'=>$finaltax2,
			
								);
								
												
								
							//$usr_result = $this->usermodel->add($data,'purchaseorderlist');
						$usr_result =$this->usermodel->updatedata($data,'purchaseorderlist','id',$mycategoryid);

							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
								
					 $ourtotal= $this->usermodel->geteallQUOTES_orderCounter($invoice,$deliverymethod);
	//
									$myfinalamount= round(($ourtotal[0]["amount"]));
			
								$amountdata=array(		
												'amount'=>$myfinalamount,
													);
								
			$this->usermodel->updatedata($amountdata,'quotation','invoice',$invoice);
									

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product is updated successfully </div>');	
							
							//redirect('user/viewnewquotation?randomitemidentifier='.$invoice);	
	
																														redirect($myview);	


							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
										
										//redirect('user/viewsales');	
							//redirect('user/viewnewquotation?randomitemidentifier='.$invoice);	


																						redirect($myview);	

															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
 
 
	
 public function searchallmyinvoices()
	{
		 $session_data = $this->session->userdata('logged_in');
					

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	  		if (isset($_GET['searchterm'])){
				$searchterm=$_GET['searchterm'];
				$view=$_GET['view'];

				}else{
						$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

			  	$view = trim($this->input->get_post('view', TRUE));
					
				}
	
	 
	 
	 
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchallmyinvoices';
						$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['salesreport'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view($view,$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
 public function searchserials()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$page = trim($this->usermodel->searchterm_handler($this->input->get_post('page', TRUE)));
				$searchtype = trim($this->usermodel->searchterm_handler($this->input->get_post('searchtype', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchserials';
						$query = $this->usermodel->searchserials(($searchterm),$limit,$companyid,$searchtype);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['delivery'] = $query['data'];
				$data['page'] = $page;

		
	
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/recorddelivery",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	 public function searchvisitor()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$page = trim($this->usermodel->searchterm_handler($this->input->get_post('page', TRUE)));
				$searchtype = trim($this->usermodel->searchterm_handler($this->input->get_post('searchtype', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchvisitor';
						$query = $this->usermodel->searchserials(($searchterm),$limit,$companyid,$searchtype);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['delivery'] = $query['data'];
				$data['page'] = $page;

		
	
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/recorddelivery",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
 public function searchforleaseditems()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				///$page = trim($this->usermodel->searchterm_handler($this->input->get_post('page', TRUE)));
				$searchtype = trim($this->usermodel->searchterm_handler($this->input->get_post('searchtype', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchforleaseditems';
						$query = $this->usermodel->searchforleaseditems($searchterm,$limit,$companyid,$searchtype);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewlease'] = $query['data'];
			//	$data['page'] = $page;

		
	
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewlease",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
 public function searchfordamageditems()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				///$page = trim($this->usermodel->searchterm_handler($this->input->get_post('page', TRUE)));
				$searchtype = trim($this->usermodel->searchterm_handler($this->input->get_post('searchtype', TRUE)));

		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/viewdamages';
						$query = $this->usermodel->searchserialsdamageditems($searchterm,$limit,$companyid,$searchtype);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewdamages'] = $query['data'];
			//	$data['page'] = $page;

		
	
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewdamages",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
 public function searchbanks()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchbanks';
						$query = $this->usermodel->searchbanks($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewbanks'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewbanks",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
		 	public function viewupgrade()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewupgrade');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('upgrade','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	

        $data["viewupgrade"] = $this->usermodel->displayall($config["per_page"], $page,'upgrade','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewupgrade',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
		
 public function Reconcilesale()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 	// $branchid = $data['branchid'];	

	 
	 		if (isset($_GET['searchterm'])){
				$invoice=$_GET['searchterm'];
				
				$type=$_GET['type'];
								 $branchid=$_GET['branch'];

			
				
				
					//$paymentmode = $this->usermodel->populateallarray('smsconfig','mode', 'After Bill');
												$accountname=0;
										if(($type=="Credit")|| ($type=="Invoice")){
												
												$accountname=1100;
											}else{
											$accountname=1000;	
											}
			

						   $finaltotalamount=0;
											  		$viewreceivings = $this->usermodel->populateallsales('sales_order','invoice',$invoice);
   $currentamount=0;
				 	$this->usermodel->deletedata($invoice,"code","debitcredit");
				//								$this->usermodel->deletedatatwo("debitcredit","code",$invoice,"type <>","payment");
 $salesdetails = $this->usermodel->populateallarray('sales','invoice', $invoice);
					$customerid=$salesdetails[0]['customer'];
												//	 $insertcostofgoodsolddata = array();

		   	if(is_array($viewreceivings)) {
				   	 $salesaccount="";	
					 
					 	$costofgoodsold="";	
						$inventoryaccount="";	

							 $creditdata = array();
					$finalcode="";			
				$ttbrice=0;

					foreach ($viewreceivings as $row){ 
					$myqty= $row->qty;
										$transactionid= $row->id;
										$mybranch= $row->branch;
$orderdate= $row->date;
					$currentamount=($row->qty*$row->sprice);
					//$mytotal= $row->amount;
					//$finalamount=$finalamount+$row->amount;
					$finaltotalamount=$finaltotalamount+$currentamount;
					
					$accountcode = $this->usermodel->populateallarray('products','code', $row->code);
					$salesaccount=$accountcode[0]['salesaccount'];
					 					   
					  
					 
					  
					  $producttype=trim($accountcode[0]['producttype']); 
				  $costofgoodsold=$accountcode[0]['expenseaccount'];
	   $inventoryaccount=$accountcode[0]['assetaccount'];
	   
	   
	    $mybprice=$row->bprice;
		  $correctqty=$row->qty;
		  $finalbprice=($mybprice*$correctqty);
		  
		  
  if($costofgoodsold!=""){ $costofgoodsold=$accountcode[0]['expenseaccount'];}else{ $costofgoodsold=5500; }
 if($inventoryaccount!=""){ $inventoryaccount=$accountcode[0]['assetaccount'];}else{ $inventoryaccount=1110; }	  
						  
					  
 if($salesaccount!=""){ $salesaccount=$accountcode[0]['salesaccount'];}else{ $salesaccount=4000; }
 if($currentamount>0){
					
 $creditdata[]=array('refno'=>$transactionid, 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$currentamount,'description'=>"Sales order",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid,'balance'=> 0);

						}
						
			if(($producttype!="Service") && ($mybprice!="")){
		
		$ttbrice = $ttbrice + $finalbprice;
			 $insertinventorydata=array('refno'=>$transactionid, 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$finalbprice,'description'=>"Inventory sold",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'sales' ,'supplier'=> $customerid);
			if($finalbprice >0){
	 $this->usermodel->add($insertinventorydata,'debitcredit');


}	
					
		
	
	
	}			
																
		
						
						
					}
				
					
						if($finaltotalamount>0){

		$this->db->insert_batch('debitcredit', $creditdata); 
		
		
$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finaltotalamount,'description'=>"Sales order (A/R)",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0);

				//$this->usermodel->add($debitdata,'debitcredit');
$usr_result = $this->usermodel->add($debitdata,'debitcredit');




			}
			
			if($ttbrice>0){
					$insertcostofgoodsolddata=array( 'userid'=>$userid,'account'=>$costofgoodsold,'debit'=>$ttbrice,'description'=>"Cost of goods sold",'code'=>$invoice,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $customerid);
											$usr_result = $this->usermodel->add($insertcostofgoodsolddata,'debitcredit');




}
			
			
			
			
					
					
					}  		
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Updated GL Accounts a new  Supplier..</div>');	
							redirect('user/startsales');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> GL Account was not updated fully since may be some sales all sales were retuned.. Try again</div>');
								
								 redirect('user/startsales');
							}	
							
							
			}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	 public function searchGL()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 

						 $searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

			  
					
				
			

	 
	 
	 
	 
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchGL';
						$query = $this->usermodel->searchGL($searchterm,$limit);
						
						
						
						
		$config['total_rows'] = $query['records'];
		
		
		
		$config['per_page'] = 500;

		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewjournalentry'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewjournalentry",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 public function searchJE()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 		if (isset($_GET['searchterm'])){
				$searchterm=$_GET['searchterm'];
			

				}else{
						$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

			  
					
				}
							
			

	 
	 
	 
	 
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchJE';
						$query = $this->usermodel->searchJE($searchterm,$limit);

		$config['total_rows'] = $query['records'];
		
		
			if (isset($_GET['searchterm'])){
		$config['per_page'] = 500;
			

				}else{
		$config['per_page'] = 500;

			  
					
				}
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['generalledger'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/generalledger",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
 public function viewbaks()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $bankname = $this->input->post("bankname");   

		 	 $startdate = $this->input->post("startdate");   
			     
			    $enddate = $this->input->post("enddate");  
		//$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/viewbaks';
						$query = $this->usermodel->viewbaks($limit, $bankname,$startdate,$enddate,$companyid);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewbanks'] = $query['data'];
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewbanks",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 public function searchallmysalesorder()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	    if (isset($_GET['searchterm'])){

    
$searchterm = $_GET['searchterm'];    }
    else {
     
	 		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

	 
	}
	 
	 
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchallmysalesorder';
						$query = $this->usermodel->searchallmysalesorder($searchterm,$limit);
		$this->load->view("template/tableheader");

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewpurchases'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
				$this->load->view("template/tableheader");


		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewpurchases",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
 public function searchpurchase()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	    if (isset($_GET['searchterm'])){

    
$searchterm = $_GET['searchterm'];    }
    else {
     
	 		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));

	 
	}
	 
	 
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;

		$config['base_url'] = base_url() . 'Systemusers/searchpurchase';
						$query = $this->usermodel->searchpurchase($searchterm,$limit);
		$this->load->view("template/tableheader");

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
			
		
		//$query = $this->usermodel->searchallmyinvoices($searchterm,$limit);
		$data['viewpurchases'] = $query['data'];
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewpurchases",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 public function searchallmyexpenses()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallmyexpenses';
		$config['total_rows'] = $this->usermodel->search_expensecount($searchterm);
		$config['per_page'] = 100;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewexpenses'] = $this->usermodel->searchallmyexpenses($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view("userdata/viewexpenses",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
 public function searchallmyrequest()
	{
		 $session_data = $this->session->userdata('logged_in');
						$view = trim($this->input->get_post('view', TRUE));

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $finalsalesid = $userid.time();

 $data['finalsalesid']="EXP-".$finalsalesid;
		$searchterm = trim($this->usermodel->search_expenserequestcount($this->input->get_post('searchterm', TRUE)));
	
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallmyrequest';
		$config['total_rows'] = $this->usermodel->search_expensecount($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewexpenses'] = $this->usermodel->searchallmyexpensesrequest($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				if(isset($view)){
									//$this->load->view($view,$data);
									$this->load->view("userdata/viewrequest",$data);

				}else{
									$this->load->view("userdata/viewrequest",$data);

				}
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
  public function addemployee()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
 $firstname = $this->input->post("firstname");
$lastname = $this->input->post("lastname");
	  $email = $this->input->post("email");
	  $phone = $this->input->post("phone");		  
		  $address_1 = $this->input->post("address_1");    
		 $gender = $this->input->post("gender");   
		  $city = $this->input->post("city");   
		   $zip = $this->input->post("zip");   
		    $country = $this->input->post("country");   
			 $comments = $this->input->post("comments");   
			  $image_id = $this->input->post("image_id");   
			   $category = $this->input->post("category");   
			    $status = $this->input->post("status");   
				 $company = $this->input->post("company");   
				  $account = $this->input->post("account"); 
 $website = $this->input->post("website"); 
 $idno = $this->input->post("idno"); 
 $balance = $this->input->post("balance");  
				
			  		  $this->form_validation->set_rules("firstname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmember', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addemployee') == "employee")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'firstname'=>$firstname,
			'lastname'=>$lastname,
		  	'email'=>$email,
			
			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $address_1,    
		 'gender' => $gender,   
		  'city' => $city,   
		   'zip' => $zip,   
		    'country' => $country,   
			 'comments' => $comments,   
			  
			   'category' => $category,   
			    'status' => $status,  
				'company' => $company,   
				  'account' => $account, 
				 'website' => $website, 
				 'idno' => $idno, 
				 'balance' => $balance,  
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'people');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Supplier..</div>');	
							redirect('user/viewemployees');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Supplier  was not added.. Try again</div>');
								
								 redirect('user/viewemployees');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 public function addtasks()
    {
		
			$session_data = $this->session->userdata('logged_in');
	
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
 	 		 $category = $this->input->post("category");

 $taskowner = $this->input->post("taskowner");
$subject = $this->input->post("subject");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $contact = $this->input->post("contact");    
		 $status = $this->input->post("status");   
		  $controller = $this->input->post("controller");   
		   $priority = $this->input->post("priority");   
		     $notification = $this->input->post("notification");   
			 $comments = $this->input->post("comments");   
			  $repeated = $this->input->post("repeated");   
			     
			    $status = $this->input->post("status");   
				  
  	  $target = $this->input->post("target");   
			     
			    $measurements = $this->input->post("measurements");  
			
			  		  $this->form_validation->set_rules("taskowner", "Task Person", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsuppliers', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addtask') == "task")
					   {
						   
						   $taskmessage="";
						   
						  
						   
						   	  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$fromemail=$myconfiguration[0]["email"];
		   

						   
						   $confirmsendercontact= $this->usermodel->geteuser($controller);
						      $confirmacontact= $this->usermodel->geteuser($taskowner);
						  $mycontact= $confirmacontact[0]['phone'];
						  	 $contact= $confirmacontact[0]['phone'];

						  						  $toemail= $confirmacontact[0]['email'];
						  						  $surname= $confirmacontact[0]['firstname']."   ".$confirmacontact[0]['surname'];
								$sendersurname= $confirmsendercontact[0]['surname'];
								$cc= $confirmsendercontact[0]['email'];
						//	$this->sendmyMail1();
					
							  $document="";
								   
								  
								   	   $duedate = date("d/m/Y H:i", strtotime($todate));
									  

		 	$taskmessage = "Dear ". $confirmacontact[0]['surname'] .",Your have new task regarding ". $subject ." from  ". $confirmsendercontact[0]['surname'] ." due on ". $duedate .".Kindly check your email/ERP.Automatic sms.";

						   
				

						   
						   
						  
					  
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'taskowner'=>$taskowner,
			'subject'=>$subject,
		  	'fromdate'=>$fromdate,
			
			
			'dateposted'=>$dateposted,
			'todate' => $todate,		  
		  'contact' => $mycontact,    
		 'status' => $status,   
		  'controller' => $controller,   
		   'priority' => $priority,   
		    'notification' => $notification,   
			 'comments' => $comments,   
			     'repeated' => $repeated,  
			   			    'companyid' => $companyid,  

			    'category' => $category,  
			   			    'branchid' => $branchid,  

				 'measurements' => $measurements,  
			   			    'target' => $target,  
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'tasks');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	
	$emailtype="Newtask";
			$myview="user/viewtasks";				  
	
														   											  $this->sendTasktoEmail($fromemail,$toemail,$surname,$duedate,$sendersurname,$subject,$comments,$cc,$emailtype);
	
		if($repeated=="Yes"){
								
							  $this->addallpushedsms($taskmessage,$contact,$myview);

																		
$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully assigned a new  Task and the email alert has been sent to '.$toemail.'</div>');	
							redirect('user/viewtasks');	
											
								
							   }else{
								   
																		
$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully assigned a new  Task and the email alert has been sent to '.$toemail.'</div>');	
							redirect('user/viewtasks');	
											   
							   }

						   

								 
						 															
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Task  was not added.. Try again</div>');
								
								 redirect('user/viewtasks');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
 
 public function addtickettasks()
    {
		
			$session_data = $this->session->userdata('logged_in');
	
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
 	 		 $category = $this->input->post("category");

 $taskowner = $this->input->post("taskowner");
$subject = $this->input->post("subject");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $contact = $this->input->post("contact");    
		 $status = $this->input->post("status");   
		  $controller = $this->input->post("controller");   
		   $priority = $this->input->post("priority");   
		     $notification = $this->input->post("notification");   
			 $comments = $this->input->post("comments");   
			  $repeated = $this->input->post("repeated");   
			     
			    $status = $this->input->post("status");   
				  
  	  $target = $this->input->post("target");   
			     
			    $measurements = $this->input->post("measurements");  
			
			  		  $this->form_validation->set_rules("taskowner", "Task Person", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsuppliers', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addtask') == "task")
					   {
						   
						   $taskmessage="";
						   
						  
						   
						   	  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$fromemail=$myconfiguration[0]["email"];
		   

						   
						   $confirmsendercontact= $this->usermodel->geteuser($controller);
						      $confirmacontact= $this->usermodel->geteuser($taskowner);
						  $mycontact= $confirmacontact[0]['phone'];
						  	// $contact= $confirmacontact[0]['phone'];

						  						  $toemail= $confirmacontact[0]['email'];
						  						  $surname= $confirmacontact[0]['firstname']."   ".$confirmacontact[0]['surname'];
								$sendersurname= $confirmsendercontact[0]['surname'];
								$cc= $confirmsendercontact[0]['email'];
						//	$this->sendmyMail1();
					
							  $document="";
								   
								  
								   	   $duedate = date("d/m/Y H:i", strtotime($todate));
									  

		 	$taskmessage = "Dear ". $confirmacontact[0]['surname'] .",Your have new task regarding ". $subject ." from  ". $confirmsendercontact[0]['surname'] ." due on ". $duedate .".Kindly check your email/ERP.Automatic sms.";

						   
				

						   
						   
						  
					  
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'taskowner'=>$taskowner,
			'subject'=>$subject,
		  	'fromdate'=>$fromdate,
			
			
			'dateposted'=>$dateposted,
			'todate' => $todate,		  
		  'contact' => $contact,    
		 'status' => $status,   
		  'controller' => $controller,   
		   'priority' => $priority,   
		    'notification' => $notification,   
			 'comments' => $comments,   
			     'repeated' => $repeated,  
			   			    'companyid' => $companyid,  

			    'category' => $category,  
			   			    'branchid' => $branchid,  

				 'measurements' => $measurements,  
			   			    'target' => $target,  
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'tasks');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	
	$emailtype="Newtask";
			$myview="user/viewtasks";				  
	
														   											  $this->sendTasktoEmail($fromemail,$toemail,$surname,$duedate,$sendersurname,$subject,$comments,$cc,$emailtype);
	
		if($repeated=="Yes"){
								
							  $this->addallpushedsms($taskmessage,$contact,$myview);

																		
$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully assigned a new  Task and the email alert has been sent to '.$toemail.'</div>');	
							redirect('user/viewtasks');	
											
								
							   }else{
								   
																		
$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully assigned a new  Task and the email alert has been sent to '.$toemail.'</div>');	
							redirect('user/viewtasks');	
											   
							   }

						   

								 
						 															
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Task  was not added.. Try again</div>');
								
								 redirect('user/viewtasks');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 public function addevents()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

	$data['id'] = $session_data['id'];
	 $userid = $data['id'];

         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 
 	 		
 $location = $this->input->post("location");
$title = $this->input->post("title");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $host = $this->input->post("host");    
		    
		  $participants = $this->input->post("participants");   
		     
			 $comments = $this->input->post("comments");   
			  $repeated = $this->input->post("repeated");   
			     
			    $status = $this->input->post("status");   
				  
  			    $mycategoryid = $this->input->post("mycategoryid");   
  			    $action = $this->input->post("action");   

				
			  		  $this->form_validation->set_rules("location", "Task Location", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewevents ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addevent') == "event")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'location'=>$location,
			'title'=>$title,
		  	'fromdate'=>$fromdate,
			
			
			'dateposted'=>$dateposted,
			'todate' => $todate,		  
		  'host' => $host,    
		 'status' => $status,   
		  'participants' => $participants,   
		   
			 'comments' => $comments,   
			  
			       'repeated' => $repeated,  
			    'status' => $status, 
				
			   			    'companyid' => $companyid,  

				
			
			
			
								);
								
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'events');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'events','id',$mycategoryid);

								}
							
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Event..</div>');	
							redirect('user/viewevents');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Event  was not added.. Try again</div>');
								
								 redirect('user/viewevents');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 
 
 public function addeventsfarm()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

	$data['id'] = $session_data['id'];
	 $userid = $data['id'];

         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 
 	 		
 $location = $this->input->post("location");
$title = $this->input->post("title");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $host = $this->input->post("host");    
		    
		  $participants = $this->input->post("participants");   
		     
			 $comments = $this->input->post("comments");   
			  $repeated = $this->input->post("repeated");   
			     
			    $status = $this->input->post("status");  


 $one = $this->input->post("one");   
			  $two = $this->input->post("two");   
			     
			    $three = $this->input->post("three");
			    $four = $this->input->post("four");



				
				  
  			    $mycategoryid = $this->input->post("mycategoryid");   
  			    $action = $this->input->post("action");   

				
			  		  $this->form_validation->set_rules("location", "Task Location", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewevents ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addevent') == "event")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'location'=>$location,
			'title'=>$title,
		  	'fromdate'=>$fromdate,
			
				'one'=>$one,
			'two' => $two,		  
		  'three' => $three,  
			 'four' => $four,  
			
			
			'dateposted'=>$dateposted,
			'todate' => $todate,		  
		  'host' => $host,    
		 'status' => $status,   
		  'participants' => $participants,   
		   
			 'comments' => $comments,   
			  
			       'repeated' => $repeated,  
			    'status' => $status, 
				
			   			    'companyid' => $companyid,  

				
			
			
			
								);
								
								
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'events');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'events','id',$mycategoryid);

								}
							
								
								
								
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a farm  products..</div>');	
							redirect('user/viewevents');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Farm products  was not added.. Try again</div>');
								
								 redirect('user/viewevents');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 public function addpurchases()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $view = $this->input->post("view");
 $action = $this->input->post("action");
 $mycategoryid = $this->input->post("mycategoryid");
 $invoice_number = $this->input->post("invoice_number");
 $paid = $this->input->post("paid");

 	 		
 $invoice_number = $this->input->post("invoice_number");

$suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers[0]));
	  $fromdate = $this->input->post("fromdate");
	  $paiddate = $this->input->post("paiddate");		  
		  $amount = $this->input->post("amount");    
		   $mybranchid = $this->input->post("branchid");   




 $withholdingamount = (double)$this->input->post("withholdingamount");    
$withholdingrate = (double)$this->input->post("withholdingrate");   



					  

		 // $remarks = $this->input->post("remarks");   
		     
		   

$remarkss = explode(':=',$this->input->post("remarks"));
  $remarks = htmlspecialchars(trim($remarkss[0]));

		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
			 $ordernumber = $this->input->post("ordernumber");    
		    
		  $shippingto = $this->input->post("shippingto");   
		     	  
  		  $branchto = $this->input->post("branchto");   
  		  $status = $this->input->post("status");   

  
     $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
				
					  
	  $fromdate=$fromdate." ".$frotime;
	  	  $paiddate=$paiddate." ".$totime;
	  
  
  
	  $vattype = $this->input->post("vattype");		  
		  $vatrate = $this->input->post("vatrate");    
		    
		  $vat = $this->input->post("vat"); 
		  		  $taxable = $this->input->post("taxable"); 

				
			  		  $this->form_validation->set_rules("invoice_number", "Invoice invoice_number", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewpurchases', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_purchase') == "purchase")
					   {
						   
						  
						   
								
						$confirminvoice  = $this->usermodel->populatethreenoarray('purchaseorder','companyid', $companyid,'ordernumber' ,$ordernumber,'supplier',$supplier);

						
						if(($confirminvoice !=FALSE ) && ($action=="insert")){
							$createdate=$confirminvoice[0]["createdate"];
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This purchase with invoice number ('.$ordernumber.').   had  been created  already on ('.$createdate.'). Try again other purchases</div>');
								
							redirect('user/viewpurchases');	
								 
								 return false;
							
						}			   
						   
 $confirmsupplier = $this->usermodel->populateallarray('people','id',$supplier);
				
				
	
  if($confirmsupplier==FALSE){
	
 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>That supplier or customer is not available in the system. Kindly try again.</div>');
						  
						  
						  
						  
								
							redirect('user/viewpurchases');	
	   return false;	
  }


						   
						   
						   
						   
						   
						   
					
							 if($action=="insert"){
								 
								 
								/// $myuser=$this->usermodel->geteuser($supplier);
     $pin=$confirmsupplier[0]['idnumber'];


							}else 	if($action=="update"){
  	  $pin = $this->input->post("pin");

								}   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   	 $finaltax=0;
							 $vatable=0;
							 
							 		 
							 if($vattype=="VATABLE"){
								  $mytax=1+($vatrate/100); 
								  
								  
								 $vatable=($amount/$mytax);
								 $myfinaltax=(($amount-$vatable));
								
								$finaltax= $this->formatMoney($myfinaltax, true);
								$vatable= $this->formatMoney($vatable, true);

							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
						
						   
						   
						   $vat=$finaltax;
						      $taxable=$vatable;
						   
						   
						   
	if(($withholdingamount =="") || ($withholdingamount ==0)){
	
	$withholdingamount=$this->formatMoney((($withholdingrate/100)*$vat), true);

}
   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'invoice'=>$invoice_number,
			'supplier'=>$supplier,
		  	'fromdate'=>$fromdate,
					  	'status'=>$status,
			'paid'=>$paid,

			
			'createdate'=>$dateposted,
			'paiddate' => $paiddate,		  
		  'amount' => $amount,    
	
		  'description' => $remarks,   
		   			    'ordernumber' => $ordernumber,  
			    'shippingto' => $shippingto,  
			    'branchid' => $mybranchid,  

						    'branchto' => $branchto,  

			    'companyid' => $companyid,  
				
			   
						  'pin'=>$pin,
					'vattype' => $vattype,		  
				  'vatrate' => $vatrate,    
			
			//
				'withholdingrate' => $withholdingrate,		  
				  'withholdingamount' => $withholdingamount,  
				  
				  
				  
				  'vat' => $vat,   
		   'taxable' => $taxable,  
								);
							
							
							
							
							 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'purchaseorder');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'purchaseorder','id',$mycategoryid);

								}
							
							
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  item purchased..</div>');	
								

							 if($action=="insert"){
								redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);

							}else 	if($action=="update"){
							redirect('user/viewpurchases');		

								}

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> item purchased  was not added.. Try again</div>');
								
							redirect('user/viewpurchases');		
								 
								 
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
public	function formatMoney($number, $fractional=false) {
						if ($fractional) {
							$number = sprintf('%.2f', $number);
						}
						while (true) {
							$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1$2', $number);
							if ($replaced != $number) {
								$number = $replaced;
							} else {
								break;
							}
						}
						return $number;
					}
						
 
 
  
public	function MyformatMoney($number, $fractional=false) {
						if ($fractional) {
							$number = sprintf('%.2f', $number);
						}
						while (true) {
							$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1$2', $number);
							if ($replaced != $number) {
								$number = $replaced;
							} else {
								break;
							}
						}
						return $number;
					}
						
 
 
 
  public function addwholesale()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	 		

 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];



			 $code = htmlspecialchars(trim($this->input->post("code")));
$qty = $this->input->post("qty");
	  $discount = $this->input->post("discount");
	  $mode = $this->input->post("mode");		  
		  $type = $this->input->post("type");    
		  		  $salestype = $this->input->post("salestype");    

		    
		      $invoice = $this->input->post("invoice"); 

				        $productname = $this->usermodel->geteproductlistbyid($code,$branchid);
						
 


						  if ($productname ==false)
						   {
							  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">That product code does not exist. Try again.</div>');
								
							redirect('user/viewwholesales');						   
						   return false;
						   }
  $buyingprice=trim($productname[0]['buyingprice']); 
    $productid=trim($productname[0]['id']); 
	  $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 

	 
	  $newsellingprice=trim($productname[0]['wholesaleprice']); 
 $sellingprice=$newsellingprice-$discount;
	 
	 
	 
	 
  
    $finaldiscount= ($discount*$qty);
    $amount= ($sellingprice*$qty);
  
  

   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
							
							 
							 	 $finaltax=0;
							 
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								 $mytax=1+($tax_included/100); 
								 $vatable=($sellingprice/$mytax);
								 $myfinaltax=(($sellingprice-$vatable)*$qty);
								
								$finaltax= $this->formatMoney($myfinaltax, true);
								 
							 }
							 
													$myinventory = $this->usermodel->populateallarray('products','code',$code);
	  $inventorytype=trim($productname[0]['producttype']); 
if(( $inventorytype=="Inventory") || ( $inventorytype=="None Inventory")){				
   if($available<$qty ){
	    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity ('.$available.') is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  
						  
						  
								
							redirect('user/viewwholesales');	
	   return false;
   }
	}			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewwholesales ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsale') == "sale")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
			'mode' => $mode,		  
		  'type' => $type,    
		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
					'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
			
			
			
								);
								
												$productdata=array(		
												'qty'=>$finalqty,
													);
								
								
							$usr_result = $this->usermodel->add($data,'sales_order');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								if(( $inventorytype=="Inventory")|| ( $inventorytype=="None Inventory")){	
							 $this->usermodel->updatedata($productdata,'productlist','id',$productid); 
								    }

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Sales Added </div>');	
							redirect('user/viewwholesales');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not added.. Try again</div>');
								
								 redirect('user/viewwholesales');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 
 
    public function addcollections()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		//$dateposted =  ($postedtime);
		 	  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		 
		 							 $sendsms = $this->input->post("sendsms");
		 							 $creditnote = $this->input->post("creditnote");
					 $advance = $this->input->post("advance");

					 $view = $this->input->post("view");
		 		 $cash = $this->input->post("cash");
							   $name = $this->input->post("name");

			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$entrydate = $this->input->post("entrydate");
				$controller = $this->input->post("controller");
				$idno = $this->input->post("idno");
				  $mpesa = $this->input->post("mpesa");		  
	  	        $cheque = $this->input->post("cheque");		  
	            $card = $this->input->post("card");	
		    	$voucher = $this->input->post("voucher");
		 			$credit = $this->input->post("credit");
					$openingbalance=0;
							 			$myopeningbalance = $this->input->post("openingbalance");
									$openingbalance2 = $this->input->post("openingbalance2");

							 			$closingbalance = $this->input->post("closingbalance");

										$cashcollected = $this->input->post("cashcollected");
											$totalsales = $this->input->post("totalsales");

														
			
											$debt = $this->input->post("debt");

											$totime = $this->input->post("totime");



	  	




														
							 			$points = $this->input->post("points");
							 			$contact = $this->input->post("contact");
							 			$expense = $this->input->post("expense");
							 			$sortmoney = $this->input->post("sortmoney");
							 			$tax = $this->input->post("tax");
							 			$branchid = $this->input->post("branchid");
							 			$mydate = $this->input->post("entrydate");
						      $myentrydate = date("d/m/Y H:i", strtotime($mydate));


			  		  $this->form_validation->set_rules("entrydate", "Date of income ", "trim|required");
			  		  $this->form_validation->set_rules("controller", "Approver ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdailycollections', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcollections') == "collections")
					   {
						   
						   
	  	  $entrydate=$entrydate." ".$totime;
	
						   
						   
						   
						   if($openingbalance2 > 0){
	$openingbalance=$openingbalance2;

						   }else{
	$openingbalance=$myopeningbalance;



						   }							   
						   
						   
						   
						  if($openingbalance==""){
							 $openingbalance=0;  
						   }

						   $alldetais="Total sales for ".$myentrydate." are follows: ";
						   if($sendsms=="yes"){
						
												
							
						 
						 if($cash!=""){
							 $alldetais.= "cash:".$cash.",";
						 }
						  
						  if($mpesa!=""){
							 $alldetais.= "mpesa:".$mpesa.",";
						 }
						
						  if($cheque!=""){
							 $alldetais.= "cheque:".$cheque.",";
						 }
						 
						  if($card!=""){
						 $alldetais.= "card:".$card.",";

						 }
						 if($voucher!=""){
							 $alldetais.= "voucher:".$voucher.",";
						 }
						  
						  if($credit!=""){
							 $alldetais.= "credit:".$credit.",";
						 }
						
						  if($points!=""){
							 $alldetais.= "points:".$points.",";
						 }
						 
						  if($creditnote!=""){
							  							 $alldetais.="creditnote:". $creditnote.",";

						 }
						 	
							
						if($totalsales!=""){
							  							 $alldetais.="GRAND TOTAL:". $totalsales.",";

						 }
						 			if($expense!=""){
							  							 $alldetais.="Total Expense:". $expense.",";

										}
									if($openingbalance!=""){
							  							 $alldetais.="O/B:". $openingbalance.",";

										}
										
										 
										if($cashcollected!=""){
							  							 $alldetais.="Banked:". $cashcollected.",";

										}
											if($closingbalance!=""){
							  							 $alldetais.="C/B:". $closingbalance.",";

										}
						
						 	
								
						   }
						   
						   
						   
						   
							   
						   $shortmoney=((double)$cash+(double)$mpesa+(double)$cheque+(double)$card+(double)$voucher+(double)$credit+(double)$points+(double)$creditnote+(double)$openingbalance);
											
							//$cashcollected = $this->input->post("cashcollected");
											/// $totalsales = $this->input->post("totalsales");							
											//	
							//$MYsortmoney=$shortmoney-$cashcollected; 	
							//$MYsortmoney=(((double)$cash + (double)$openingbalance)-(double)$cashcollected-(double)$closingbalance); 				
							
							$MYsortmoney=(((double)$cash + (double)$openingbalance)-(double)$cashcollected-(double)$closingbalance-(double)$expense+(double)$tax); 				
				
												
												$data=array(		
				 	'companyid'=>$companyid,
			 'cash' => $cash,  
		  'mpesa' => $mpesa,    
		     'cheque' => $cheque,  
		     'card' => $card, 
			   'voucher' => $voucher, 
			   'credit' => $credit, 
				'points' => $points,
				'expense' => $expense,
	'tax' => $tax,
				'sortmoney' => $MYsortmoney,
								
		  	'description'=>$description,
		'entrydate'=>$entrydate,
			'createdat'=>$dateposted,
			
			'openingbalance'=>$openingbalance,
			'controller' =>$controller,
				'idno' =>$idno,
				'contact'=>$contact,
				'userid'=>$userid,
						'name'=>$name,	
							'branchid'=>$branchid,	
									'totalsales' => $totalsales, 
			   'cashcollected' => $cashcollected, 
				'closingbalance' => $closingbalance,
				'debt' => $debt,
				'amount' => $advance,

			
								);
							$usr_result = $this->usermodel->add($data,'dailycollections');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									
									//
								if($sendsms=="yes"){
	$appriver=$this->usermodel->populateallarray('smsconfig','id', $companyid);
		$authorizer=$appriver[0]['paymenttypes'];
		
		
							$approver=$this->usermodel->populateallarray('people','id', $authorizer);

			 $contact=$approver[0]['phone'];
			$firstname=$approver[0]['firstname'];


	   
	   	$message="Dear ".$firstname.", ".$alldetais;

  
														
													
									$myview=$view;				  
		  $this->addallpushedsms($message,$contact,$myview);
						 
						 
								}
  
							   
						   									
									
									
									
									
									
									
									
									
									
									
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new Income  ..</div>');	
								 redirect($view);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Income  was not created.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   
   
 
 
 
 
 
 
 
	
 
 
 
 
 function containsDecimal( $value ) {
    if ( strpos( $value, "." ) !== false ) {
        return true;
	
    }

    return false;
}

	
  public function addsale()
    {
		//
		//
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$dateposted2 =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 $mainbranchid=$branchid ;
			
			  $productdiscountaction=$this->usermodel->populatuserpermissionsdataarray('sales','productdiscount',$userid);
	 
							 		  $salebelowsprice=$this->usermodel->populatuserpermissionsdataarray('sales','salesbeyondbprice',$userid);
							 		  $sellusingserialonly=$this->usermodel->populatuserpermissionsdataarray('wholesale','sellusingserialonly',$userid);

 	 		$dateposted = $this->input->post("dateposted");
 	 		$mode = $this->input->post("mode");

 	 		$productcategory = $this->input->post("productcategory");
		
  	 		$taxindicator = $this->input->post("taxindicator");
  	 		$myuom = $this->input->post("uom");


 			$codes = explode(':=',$this->input->post("code"));

 
 
 if($mode=="COMBINED"){
	 
	 
	 
	 $exactdata = substr($this->input->post("code"),0); 



	  $code= substr($exactdata, 0, 7);

  $discount= substr($exactdata, -6,-1);
 

	
 }else{
  $code = htmlspecialchars(trim($codes[0]));
$discount = trim($this->input->post("discount"));
  
 }
 

 
 
 $code=trim($code);
 
 
 
$qty = 1;
$myqty = trim($this->input->post("qty"));




	
 






	  $myview = trim($this->input->post("view"));  
	

	  $view = trim($this->input->post("view"));  
	  $type = trim($this->input->post("type"));  
	
	  $return = trim($this->input->post("return"));
	  $message = trim($this->input->post("message"));    

	$myinvoice =  $userid.time().$this->createRandomPasswordForsales();
	

	  $productname ="";
	  
	  
	 
	  
	 $myfinalqty=0;
	
		  		  $salestype = trim($this->input->post("salestype"));    
  $serial="";
		    
		      $invoice = trim($this->input->post("invoice")); 
			  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$salesmethod=$myconfiguration[0]["salesmethod"];
$sharedb=$myconfiguration[0]["maindiscount"];
	if (trim($sharedb)=="Shared DB"){
		$branchid="1";
		
	}

			if (($salesmethod=="Serial Only")||($sellusingserialonly==true)){
						   
							  
						
						 						 $myserialname = $this->usermodel->geteproductlistbyserial($code,$branchid);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 

							$qty=$myserialname[0]['qty'];						  
							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$branchid);
	$buyingprice=$myserialname[0]['buyingprice']; 
	 $newsellingprice=trim($myserialname[0]['sellingprice']); 
	   //$promoprice=trim($myserialname[0]['sellingprice']); 
	   
	   
						
							
							
							
						   }else{
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That Serial Number  does not exist. Try again or Deactivate the sales on serial Mode..</div>');
							
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="") && (isset($_GET['invoice']))) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
							//redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															//redirect('user/viewsales');	
								redirect($myview);	

								}
							//redirect('user/viewsales');						   
						   return false;
						   }	   
							   
							 
						   } else if ($salesmethod=="General"){
						    
							   
					
							   
							   

				        $productname = $this->usermodel->geteproductlistbyid($code,$branchid);
				
		
	     
						  if ($productname==false)
						   {//
							   			
							 						 $myserialname = $this->usermodel->geteproductlistbyserial($code,$branchid);
  
						
						 
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
							$qty=$myserialname[0]['qty'];
							
							
							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$branchid);
								//$promoprice=$myserialname[0]['promoprice']; 
								
							
													  $buyingprice=trim($myserialname[0]['buyingprice']); 

								
								
						  $newsellingprice=trim($myserialname[0]['sellingprice']); 

	
						   }else{
							 
			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					 <strong>Error!</strong> That product code does not exist or deactivated. Try again.</div>');
							//redirect($view ,$data);
							
						//	redirect("user/viewsales");	
						
					redirect('user/notavailable?invoice='.$invoice);	

						
											redirect($myview);	

						return false;
						
							
						  		if($productcategory !=""){
									
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else if(($productcategory!="") &&($return!="") && (isset($_GET['invoice']))) {
							
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						
							//redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}else{
$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Error!</strong> That product code does not exist or deactivated. Try again.</div>');
						
							
							redirect($myview);	
														   return false;


								}
								
								redirect($myview);	
						   return false;
						   
						   
						   
						   
						
						   }
						   
						   
					
						   
						   
						   
						   
						   }else{
		$buyingprice=$productname[0]['buyingprice']; 
       // $newsellingprice=trim($productname[0]['sellingprice']); 
		
				$code=$productname[0]['code']; 
		 if($salestype=="wholesale"){
		        $newsellingprice=trim($productname[0]['wholesaleprice']); 

	  }else{
		  							   $promoprice=trim($productname[0]['promoprice']); 
									   
									   if(($promoprice==null) || ($promoprice=="") ||($promoprice==0)){
										 $promoprice=0; 
									   }
									   
									   

		  	  if(($mode !="Money") ||($mode!="DIRECT")){
				

		
				  if(($myqty >= $promoprice) && ($promoprice !=0) && ($productname[0]['wholesaleprice'])!=0) {
					  
					  							   $newsellingprice=trim($productname[0]['wholesaleprice']); 
		  }else{
							   $newsellingprice=trim($productname[0]['sellingprice']); 
  
				  }
					  
	
					}else{
							   $newsellingprice=trim($productname[0]['sellingprice']); 
	
						}
							
		    // $newsellingprice=trim($productname[0]['start_date']);

  $start_date=trim($productname[0]['start_date']);
$end_date=trim($productname[0]['end_date']);

if(($start_date !="") && ($end_date !="")){
	
	  if($end_date >= $postedtime){

		 if($start_date <= $postedtime){
		 $newsellingprice=trim($productname[0]['wholesaleprice']); 
		
		 }
  
	  }
	
}



		        //$newsellingprice=trim($productname[0]['wholesaleprice']); 


			
  
	  }
	  

						   }
						   
						   	

						   
						   
	}		














	
		   $taxtype=$productname[0]['taxtype']; 

						  $productid=$productname[0]['id'];  
  //$buyingprice=$productname[0]['buyingprice']; 
      //$newsellingprice=trim($productname[0]['sellingprice']); 
	        $uom=trim($productname[0]['uom']); 

				
if($mode=="COMBINED"){
	
	//$myqty = trim($this->input->post("qty"));
	
$qty =$discount/$newsellingprice;
$discount=0;
//echo$qty ;
//exit; 
}else  if(($mode=="Money")){
			
					 
	$myqty = trim($this->input->post("qty"));
	
$qty =$myqty/$newsellingprice;
}else  if(($mode=="TWOSTEPS")){
	
	if($discount!=0){
		$qty=$myqty* $discount;
	
	}else{
		$qty=$myqty* 1;
	
	}
	$discount = 0;

}else{
$qty = trim($this->input->post("qty"));
	
}
	 
	  
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 

			
			
			
			if($mode=="PC"){
			
				$mydiscount=($newsellingprice* ($discount/100));	
				$discount= $this->formatMoney($mydiscount, true);
					
			}else if($mode=="DIRECT")  {
			
			 $currentprice=$this->formatMoney(($discount/$qty));
			$newsellingprices= ($discount/$qty);
				 $mydiscount=$this->formatMoney(($newsellingprice -$currentprice),true);
		
			
			
		
			
			
			$ttdiscount=($mydiscount*$qty);	

				//$mydiscount=($newsellingprice * ($discount/100));	
				$discount= $this->formatMoney($mydiscount, true);
				 $sellingprice= $currentprice;

					
			}else{
			$discount=(double)$discount;	
				
			}
		
 $sellingprice=(double)$newsellingprice-(double)$discount;

  $finaldiscount= ((double)$discount*$qty);
//exit; $amount

	$salebelowsprice=$this->usermodel->populatuserpermissionsdataarray('sales','salesbeyondbprice',$userid);
			$salebelowbprice=$this->usermodel->populatuserpermissionsdataarray('sales','salebelowbprice',$userid);


if(($sellingprice < $buyingprice) && ($salebelowbprice==false)) {
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set buying price and you do not have the right. Try again </div>');
								redirect($view ,$data);
		
								

								return false;
		}
		

if($discount >0){
if(($mode=="PC") ||($mode=="AMT")) {


if(($sellingprice<$newsellingprice) && ($productdiscountaction==false)) {
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set selling price('.$oldsellingprice.'). Try again </div>');
								redirect($view ,$data);
		
		
		
								//

								return false;
		}
		if(($sellingprice<$buyingprice) && ($salebelowbprice==false)) {
			 $this->session->set_flashdata('updatemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your selling price is less than the set buying price and you do not have the right. Try again </div>');
								redirect($view ,$data);
		
								

								return false;
		}
}
}

if( $qty <= 0){
 $negativesales=$this->usermodel->populatuserpermissionsdataarray('sales','negativesales',$userid);
if( $negativesales !=true){
	
 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You can not sale items with zero or less quantity. Try again</div>');
								
		redirect($myview);
			return false;
	
	
}
	
	
	
}


//

//
						
			




   if(trim($myuom) !=""){

$uomchild = $this->usermodel->populatealldataarrayfour('uomproducts','code',$code,'branch',$branchid,'status',"active",'uom',$myuom);

if($uomchild==false){
	
 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! The UOM ('.$myuom.') Selected has not been assigned to that product. Try assign or select different  UOM then try again</div>');
								
		redirect($myview);
			return false;
	
	
}else{

	 $sellingprice=($uomchild[0]["price"]/$uomchild[0]["qty"]);
		$buyingprice=($uomchild[0]["brice"]/$uomchild[0]["qty"]);
$uomqty=$uomchild[0]["qty"];
	$uom=$myuom;
$qty=$qty*$uomqty;

	
}




   }










   $available=trim($productname[0]['qty']); 
   //$finalqty=($available-$qty); 
   
   	 $myfinalqty=($available-$qty); 

	 
						$finaltax = 0.00;
						$finaltax2 = 0.00;
						$vattype = "";
	 						$taxable = "";

	   if ($taxindicator=="no"){
		   //
							   
							   	 $finaltax = 0.00;
							   	 $finaltax2 = 0.00;
								$vattype = "EXEMPTED";
	 						$taxable = 0.00;

						$tax_included=trim($productname[0]['tax_included']);	   
							   
						   }else{
 
	 
		$tax_included=trim($productname[0]['tax_included']);
	    $tax_vattype=trim($productname[0]['vattype']);
		$vattype = trim($productname[0]['vattype']);

							if (($tax_included < 0 ) || ($tax_included =="")){				
							$finaltax=0; 
							$finaltax2=0;
							$vattype = $vattype;
	 						$taxable = 0.00;

							 }else{
								 
								 
						
							   
						   
						   if(($vattype =="EXEMPTED")||($vattype =="ZERO RATED")||($vattype =="NON VAT")){
							   $tax_included=0;
						   }else{
							   $tax_included=$tax_included;
							   
						   }
			 
								 
								 
								 
								 
								 
								 
								 
				
									if($taxtype=="Exclusive"){
									
								$mytax=1+($tax_included/100); 
								$vatable=($sellingprice);	

								$getvatable=($sellingprice*$mytax);	
								$myfinaltax=(($getvatable-$sellingprice)*$qty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{
								
								$mytax=1+($tax_included/100); 
								$vatable=($sellingprice/$mytax);
								$myfinaltax=(($sellingprice-$vatable)*$qty);

									}


								
								
								
	$finaltax= $this->formatMoney($myfinaltax, true);

$display2=$myconfiguration[0]["display2"]; 

	if($display2=="yes"){
//echo $tax_included
	$tax2rate=$myconfiguration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$qty)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	//$taxable= $this->formatMoney($ttoltaxable, true);
		$taxable= $this->formatMoney(($ttoltaxable), true);

	}else{
	 $finaltax2=0;
	//$taxable= $this->formatMoney($vatable, true);
	$taxable= $this->formatMoney(($vatable*$qty), true);


	}	
								 	//echo  $finaltax;
								//exit;
	 }
							 
							 
	
	}
	
	
		  $itemtype=trim($productname[0]['orderamount']); 
		  
		  
		  
		  
		  
	  $inventorytype=trim($productname[0]['producttype']); 
	
	  if($itemtype=="accompaniment"){
		  						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The product you want to sell belongs to  accompaniment/production category hence you can not  sell it.  Try again.</div>');
			
							redirect($myview);	

								
		  							return false;

	  }
	 

	  if(( $inventorytype=="Inventory")  && ($itemtype !="production")&& ($itemtype !="subitem") && ($itemtype !="Sub-Single-item") && ( $available<$qty)){
		  						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity is less than what you want sell('.$qty.').  Try again.</div>');
						redirect('user/notavailable?invoice='.$invoice);

						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  



redirect('user/notavailable?invoice='.$invoice);
							
							//redirect('user/viewsales');	
	   return false;
		  
	  }  
		  
		
	
	  if( ($inventorytype=="Inventory")&&($itemtype=="production")){
	

	$uomproducts = $this->usermodel->populatealldatanoarrayfour('uomproducts','code', $code,'status',"child",'branch',$branchid,'companyid',$companyid);


	if(is_array($uomproducts)){
	$mytotalcost=0;
		$finalmainqty=0;

$insertstockdata = array();
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);

	$finalmainqty=$myproductlist[0]['qty']+$qty;
$mytotal = $qty*$c->qty;
$availableuomqty=$myproductlist[0]['qty'];

if($myproductlist[0]['producttype'] !="Service"){

if($availableuomqty >= $mytotal){
	$myid =$myproductlist[0]['id'];

	$mytotalcost=  $mytotalcost+ ($c->qty * $myproductlist[0]['buyingprice']);
		//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);

	   $finalqty=($availableuomqty-$mytotal);
	   
$myname=$myproductlist[0]['name'];
							

	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$finalqty,
);	


	 $insertstockdata[]	=array(		
			'total'=>-$mytotal,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$uomcode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Automatic Production adjustment',
				'type'=>$branchid,
				'balance'=>$finalqty,
				'item_id1'=>$availableuomqty,


								);
						
		

							


			}
			else{
				
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The accompaniment product does not have enough quantity ('.$mytotal.') to be deducted from('.$availableuomqty.'). Kindly restock the products first the  continue.  Try again..For product code('.$uomcode.')</div>');
			
							redirect($myview);	
	}
	
}		
	}
		$buyingprice=$mytotalcost;

		
	
	//
									$usr_result =$this->db->insert_batch('newstock', $insertstockdata); 

						//$this->db->update_batch('productlist',$updateArray, 'id'); 

							if($this->db->affected_rows() > 0)
						{
						$this->db->update_batch('productlist',$updateArray, 'id'); 

						
						
						 $productlistdata	=array(		
			'total'=>$qty,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>'Internal',
				'type'=>$branchid,
				'balance'=>($available+$qty),
				'item_id1'=>$available,


								);
						
				$this->usermodel->add($productlistdata,'newstock');

						

		
	
							
							}
	
	
	
	
	
	}else{
		
$buyingprice=$buyingprice;

						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity  is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
		
	}
	
	
	


		



   }




   
    
    if (($itemtype=="subitem") && ($available<$qty)) {
	
	$uomproducts = $this->usermodel->populatethreenoarray('uomproducts','uom', $code,'status',"child",'companyid', $companyid);
if($uomproducts!=FALSE){
$uomcode=$uomproducts[0]['code'];
$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);
$mytotalquantity=0;
$different = ($qty*$uomproducts[0]['qty']);
$checker= $this->containsDecimal($different);
$mytotalquantity=$different;
if($checker==FALSE){
//$mytotalquantity=$different;
}else{
//$figuredata = explode('.', $different);
//$figure=$figuredata[0] ;
//$mytotalquantity=$figure+1;
}


$mytotal=($mytotalquantity);
$listqty=$myproductlist[0]['qty'];



if($listqty>=$mytotalquantity){
	 $availableqty=$myproductlist[0]['qty'];
   $finalqty=($availableqty-$mytotalquantity);

$myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);
$myname=$myproducts[0]['name'];
$mainavailableqty=$myproducts[0]['qty'];
  $finalmainqty=($mainavailableqty+$mytotal);
    $myfinalqty=($finalmainqty-$qty); 
		$descriptisons="Sold through Subitem: ".$code;

	$stockdata=array(		
			'total'=>"-".$mytotal,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$uomcode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
				'stockto'=>$descriptisons,
				'type'=>$branchid,
								'balance'=>$finalqty,
								'item_id1'=>$availableqty,


								);
								
											$productmaindata=array(		
												'qty'=>$finalqty,

						);
				
	 $productlistdata=array(	

'qty'=>$finalmainqty,	 
						);
							
						$myusr_result=	$this->usermodel->updatedatabytwo($productmaindata,'productlist','code',$uomcode,'branch',$branchid);
					 //$this->usermodel->updatedatabytwo($productlistdata,'productlist','code',$code,'branch',$branchid);



	if ($myusr_result ==TRUE) //active user record is present
							{
											$this->usermodel->add($stockdata,'newstock');

					
		

					
}
							else if ($usr_result ==FALSE) 
							{     


						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity  is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
								
								}	
	
	
	
	
	
	
	
			}else{
				
				
				
				

						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity  is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
				
			}
	
	}else{
		

			
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
		
	}
	
	
	


		



   }
		


		
		
		
		
		
		  if (($itemtype=="Sub-Single-item") && ($available<$qty)) {
		
		

		
			
 
	$uomproducts = $this->usermodel->populatethreenoarray('uomproducts','uom', $code,'status',"child",'companyid', $companyid);
if($uomproducts!=FALSE){
$uomcode=$uomproducts[0]['code'];
$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);
$mytotalquantity=0;
$different = ($qty/$uomproducts[0]['qty']);
$checker= $this->containsDecimal($different);
if($checker==FALSE){
$mytotalquantity=$different;
}else{
$figuredata = explode('.', $different);
$figure=$figuredata[0] ;
$mytotalquantity=$figure+1;
}
$mytotal=($uomproducts[0]['qty']* $mytotalquantity);
$listqty=$myproductlist[0]['qty'];



if($listqty>=$mytotalquantity){
	 $availableqty=$myproductlist[0]['qty'];
   $finalqty=($availableqty-$mytotalquantity);

$myproducts = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);
$myname=$myproducts[0]['name'];
$mainavailableqty=$myproducts[0]['qty'];
  $finalmainqty=($mainavailableqty+$mytotal);
  
   
   $myfinalqty=($finalmainqty-$qty); 

	
	$available= $myfinalqty;
	$stockdata=array(		
			'total'=>$mytotal,
			'date'=>$dateposted,
				'name'=>$myname,
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$uomcode,
				'stockfrom'=>$branchid,
				'stockto'=>'Automatic adjustment',
				'type'=>$branchid,
								'balance'=>$finalmainqty,
								'item_id1'=>$mainavailableqty,


								);
								$myusr_result =	$this->usermodel->add($stockdata,'newstock');

	if ($myusr_result ==TRUE) //active user record is present
							{
							
								$productmaindata=array(		
												'qty'=>$finalqty,

						);
		
		
		
	 $productlistdata=array(	

'qty'=>$finalmainqty,	 
						);
							
						$this->usermodel->updatedatabytwo($productmaindata,'productlist','code',$uomcode,'branch',$branchid);


					 $this->usermodel->updatedatabytwo($productlistdata,'productlist','code',$code,'branch',$branchid);
}
							else if ($usr_result ==FALSE) 
							{     


						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity  is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
								
								}	
	
	
	
	
	
	
	
			}else{
				
				
				
				

						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
				
			}
	
	}else{
		

			
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity is less than what you want sell('.$qty.').  Try again.</div>');
						  
						  		if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
						//	redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
															redirect($myview);	
	
								}
						  




							
							//redirect('user/viewsales');	
	   return false;
		
	}
	
	
	


		



   }
		
		
		
		
		
		
		
		

/////		
		
		
											$myinventory = $this->usermodel->populateallarray('products','code',$code);

		
		
		
	
		
		
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view($myview, $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			//exit;

			
			     $amount= (($qty)* ($sellingprice));

					  $getproductaccounts = $this->usermodel->populateallarrayproducts('products','code',$code);
$assetaccount=$getproductaccounts[0]["assetaccount"];
$salesaccount=$getproductaccounts[0]["salesaccount"];
$expenseaccount=$getproductaccounts[0]["expenseaccount"];
$producttype=$getproductaccounts[0]["producttype"];

		
			
		
			
					   					$data=array(
	'assetaccount'=>$assetaccount,
	'customer'=>$mode,
					'mode'=>$tax_included,

				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,										
			
			'userid'=>$userid,
						'taxtype'=>$taxtype,

				'code'=>$code,
			'qty'=>$qty,
						'uomqty'=>$qty,

					  	'serial'=>$serial,

		  	'discount'=>$finaldiscount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$mainbranchid, 
		  'type' => $type,    
		  		   'address' => $message, 
		  		   'vattype' => $vattype, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 
				  			      'myinvoice' => $myinvoice, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
								 'taxcode' => $productname[0]['itemtax'],

			   			      'bprice' => $buyingprice, 
						'tax' => $finaltax,
						'tax2' => $finaltax2,

				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 

			
				'stockbefore' => $available, 
							'stockafter' => $myfinalqty, 
			
								);
								
												$productdata=array(		
												'qty'=>$myfinalqty,
													);
													
													
						$insertmystock=array(					
			'total'=>-$qty,
			'date'=>$dateposted,
				'name'=>$productname[0]['name'],
		  	'item_id'=>$code,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code,
				'stockfrom'=>$branchid,
								'stockto'=>$branchid,
							'itemstatus'=>"sold",
							//
							'sellingprice' => $sellingprice, 
				'buyingprice' => $buyingprice, 
				'invoice' => $myinvoice, 
				'invoice_number' => $invoice, 
				'type'=>$branchid,
				'balance'=>$myfinalqty,
				'item_id1'=>$available,


								);			
													
								

							$usr_result = $this->usermodel->add($data,'sales_orderraw');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								//
								if($serial !=""){
					 $deactivateserialstatus=$this->usermodel->populatuserpermissionsdataarray('wholesale','deactivateserialstatus',$userid);

if($deactivateserialstatus==false){
									$serialdata=array(		
												'status'=>"used",
													);
							$this->usermodel->updatedata($serialdata,'serials','id',$serialid); 
}
								}
								
								
								 if(( $inventorytype=="Inventory")  && ($itemtype=="production")&& ($available >=  $qty)){
							 $this->usermodel->updatedata($productdata,'productlist','id',$productid); 

								}else{
										  
								}
								
							 if(( $inventorytype=="Inventory")  && ($itemtype=="Sub-Single-item") ){
							 $this->usermodel->updatedata($productdata,'productlist','id',$productid); 

								}else{
								}
								
								 if(( $inventorytype=="Inventory")  && ($itemtype=="subitem") && ($available >= $qty)){
							 $this->usermodel->updatedata($productdata,'productlist','id',$productid); 

								}else{
								}
								
								
								if(( $inventorytype=="Inventory")&& ($itemtype=="mainitem")){	
							 $this->usermodel->updatedata($productdata,'productlist','id',$productid); 
							 														 $this->usermodel->add($insertmystock,'newstock');

							 

								    }
									
									
									
										if( $inventorytype=="None Inventory"){	
										$this->usermodel->updatedata($productdata,'productlist','id',$productid); 
								    														 $this->usermodel->add($insertmystock,'newstock');

									}
									
									
									
								
									
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Sales Added </div>');	
							
								if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
							//redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
									//$this->load->helper('url');

//redirect($_SERVER['REQUEST_URI'], 'refresh'); 
													redirect($myview,"'refresh");	
	
								}

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not added.. Try again</div>');
										if(($productcategory="") &&($return!="")){
															//redirect('user/viewsales');	
													redirect($myview);	


								}else
									if($productcategory!=""){
							//redirect('user/viewsales?productcategory='.$productcategory);	
							redirect($myview);	

								}else
								if(($productcategory!="") &&($return!="")) {
							//redirect('user/viewmysales?invoice='.$return.'&productcategory='.$productcategory);	
							redirect($myview);	

								} else if(($return!="") && (isset($_GET['invoice']))){
							//redirect('user/viewmysales?invoice='.$return);	
							redirect($myview);	

								}
								
								
								else{
																						redirect($myview);	

															//redirect('user/viewsales');	
	
								}
							}
					 
					 
	    }
    }
 
 
 
 
 	public function bulkdispatchorder() {
 
  if ($this->input->post('btn_editdispatch')=="dispatch")
					   {
						   
						
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

							 $view = trim($this->input->post("view"));
							 
													 $code = ($this->input->post("code"));

							  $myid = ($this->input->post("myid"));
							  $myview = ($this->input->post("myview"));

	  $stockfrom = ($this->input->post("stockfrom"));
							  $stocktostockto = ($this->input->post("stockto"));


						$buyingprice = $this->input->post("buyingprice");
						
						
						$type ="P.O";
						
															  $description = ($this->input->post("description"));

							
															  $total = ($this->input->post("total"));

											 $branch = ($this->input->post("branch"));
											  $batchno = ($this->input->post("batchno"));
											  $batchid = ($this->input->post("batchid"));

											  $finalsalesid = ($this->input->post("finalsalesid"));
											  $producttype = ($this->input->post("producttype"));

											 
											 $qty = ($this->input->post("qty"));
											 											 $to = ($this->input->post("to"));
					
  $ordernumber=0;
  	
		 		 //$PO = $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
						 //$orderdate=$PO[0]['orderdate'];
						 /// $mysupplier=$PO[0]['supplier'];
				
				
	
  $latest = $this->usermodel->populatelatestidcounter('batchlist', 'invoice',$finalsalesid);
  if($latest==FALSE){
	    $ordernumber=$ordernumber+1;
	  
  }else{
	  
	     $ordernumber= $latest+1; 
  }


																						 
												$count =count((array)$myid);
									 $mydata=array(
		'type' =>"P.O",				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'batchid'=>$batchid,
			'batchno'=>$ordernumber,
	'description'=>$description,
							
								);
												
						$myusr_result="";
$finaltotalamount=0;
	$insertdebit = array();
						$inventoryaccount="";

						//active user record is present
						
   for($i=0; $i< $count; $i++) {
   
   $myfinalqty=0;
		 $myqty=0;
					$newstock = $this->usermodel->populateallarray('newstock','id', $myid[$i]);
					$realqty=$newstock[0]['total'];
										$mybuyingprice=$newstock[0]['buyingprice'];

					$remqty=$newstock[0]['qty'];
					$balance=$realqty-$remqty;
				
					$totalamount=$total[$i]*$buyingprice[$i];	
					
$finaltotalamount=$finaltotalamount+$totalamount;




					
				
      $data=array(
		'type' =>$type,				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'qty'=>$total[$i],
        'itemid' =>$myid[$i],
		 'batchid' =>$batchno[$i],
	'code' =>$code[$i],
	
							
								);
						
				
				
					 if($realqty > $remqty ){
						 $myusr_result=$this->usermodel->add($data,'orderlist');
					
	if ( $myusr_result==TRUE) {
		
				
				 
				
			
			 	if($producttype[$i]!="Service"){
		
			  	if(($to[$i]=="Main")){
					$available = $this->usermodel->populateallarray('products','code', $code[$i]);
					$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal+$total[$i]);
											$mainstockdata=array(		
												'qty'=>$finalqty,
												
													);
				//$this->usermodel->mainstockdata($mainstockdata,$code[$i]); 
				$this->usermodel->updateproduct($mainstockdata,$code[$i]); 

													
				}else{
					 $available = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $to[$i]);

  
						   			$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal+$total[$i]);
											
						   $branchdata=array(		
												'qty'=>$finalqty,
											
													);
					
					 $this->usermodel->updateproductlist($branchdata,$code[$i],$to[$i]);
				}
				
				
				
				}
				
				
					$myfinalqty=($remqty+$total[$i]);
											$maindata=array(		
												'qty'=>$myfinalqty,
												'date'=>$mydate,
												'updatedby'=>$userid,
												'updatedat' =>$mydate,

													'item_id1'=>$availabletotal,
			
													'balance'=>$finalqty,
													);
		$this->usermodel->updatedata($maindata,'newstock','id',$myid[$i]);


				
			  
	

			  
		
   

	}
  								 
   }
   }
 

											
													
										
   
   
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							
								$this->usermodel->add($mydata,'batchlist');
													
													
	 					
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Stock Received  successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have already received all the products. try again </div>');
							redirect($myview);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
 
 
 
 
 
 

 
 
 
 
 	public function bulkpurchaseorder() {
 
  if ($this->input->post('btn_editpurchases') == "myeditpurchase")
					   {
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

							 $view = trim($this->input->post("view"));
							 
													 $code = ($this->input->post("code"));

							  $myid = ($this->input->post("myid"));
							  $myview = ($this->input->post("myview"));

						$buyingprice = $this->input->post("buyingprice");
						
						
						$type ="P.O";
						
															  $description = ($this->input->post("description"));

							
															  $total = ($this->input->post("total"));

											 $branch = ($this->input->post("branch"));
											  $batchno = ($this->input->post("batchno"));
											  $batchid = ($this->input->post("batchid"));

											  $finalsalesid = ($this->input->post("finalsalesid"));
											  $producttype = ($this->input->post("producttype"));

											 
											 $qty = ($this->input->post("qty"));
											 											 $to = ($this->input->post("to"));
					
  $ordernumber=0;
  	
		 		 $PO = $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
						 $orderdate=$PO[0]['orderdate'];
						  $mysupplier=$PO[0]['supplier'];
				
				
	
  $latest = $this->usermodel->populatelatestidcounter('batchlist', 'invoice',$finalsalesid);
  if($latest==FALSE){
	    $ordernumber=$ordernumber+1;
	  
  }else{
	  
	     $ordernumber= $latest+1; 
  }


																						 
												$count =count((array)$myid);
									 $mydata=array(
		'type' =>"P.O",				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'batchid'=>$batchid,
			'batchno'=>$ordernumber,
	'description'=>$description,
							
								);
												
						$myusr_result="";
$finaltotalamount=0;
	$insertdebit = array();
						$inventoryaccount="";

						//active user record is present
							
   for($i=0; $i< $count; $i++) {
   
   $myfinalqty=0;
		 $myqty=0;
					$newstock = $this->usermodel->populateallarray('newstock','id', $myid[$i]);
					$realqty=$newstock[0]['total'];
										$mybuyingprice=$newstock[0]['buyingprice'];

					$remqty=$newstock[0]['qty'];
					$balance=(float)$remqty-(float)$realqty;
					
				//$currenttotal=$remqty*$mybuyingprice;
		//$finaltotalamount=$finaltotalamount+ $currenttotal;
				
					$totalamount=$total[$i]*$buyingprice[$i];	
					
$finaltotalamount=$finaltotalamount+$totalamount;




					
				
      $data=array(
		'type' =>$type,				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'qty'=>$total[$i],
        'itemid' =>$myid[$i],
		 'batchid' =>$batchno[$i],
	'code' =>$code[$i],
	
							
								);
						
				
				
					 if($realqty < $remqty ){
						 $myusr_result=$this->usermodel->add($data,'orderlist');
					
	if ( $myusr_result==TRUE) {
		
				
				 
					$myfinalqty=($realqty+$total[$i]);
											$maindata=array(		
												'total'=>$myfinalqty,
												'date'=>$mydate,
													);
			
		if($this->usermodel->updatedata($maindata,'newstock','id',$myid[$i])){
			 	if($producttype[$i]!="Service"){
		
			  	if(($to[$i]=="Main")){
					$available = $this->usermodel->populateallarray('products','code', $code[$i]);
					$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal+$total[$i]);
											$mainstockdata=array(		
												'qty'=>$finalqty,
												
													);
				//$this->usermodel->mainstockdata($mainstockdata,$code[$i]); 
				$this->usermodel->updateproduct($mainstockdata,$code[$i]); 

													
				}else{
					 $available = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $to[$i]);

  
						   			$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal+$total[$i]);
											
						   $branchdata=array(		
												'qty'=>$finalqty,
											
													);
					
					 $this->usermodel->updateproductlist($branchdata,$code[$i],$to[$i]);
				}
				
				
				
				}
				//$totalamount=$buyingprice[$i]*$total[$i];
									$correctavailable = $this->usermodel->populateallarray('products','code', $code[$i]);

									 if($inventoryaccount!=""){ $inventoryaccount=$correctavailable	[0]['assetaccount'];}else{ $inventoryaccount=1110; }	

				
			  
	}

			  
		
  					if($totalamount>0){
 $insertdebit[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$totalamount,'description'=>"Inventory ",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'type'=> 'inventory');
}
	  

	}
  								 
   }
   }
 

											
													
										
   
   
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							
								$this->usermodel->add($mydata,'batchlist');
													
													
	 					
 //$insertdebit[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$totalamount,'description'=>"Inventory ",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'type'=> 'inventory');



								
								// $debitdata=array( 'userid'=>$userid,'account'=>1110,'debit'=>$finaltotalamount,'description'=>"Purchases",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'balance'=>0);

	   
  					if($finaltotalamount>0){

$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$finaltotalamount,'description'=>"Purchases",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result =$this->db->insert_batch('debitcredit', $insertdebit); 
							
							
							$people = $this->usermodel->populateallarray('people','id',$mysupplier);
									$supplierbalance=$people[0]["supplierbalance"];
									$peopleid=$people[0]["id"];
									
									
											$finalcustomerbalance=$supplierbalance+$finaltotalamount;
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
										'lastbalancedate'=>$mydate,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
							
							
							
							}
							
								
									
									
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Data Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect($myview);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
 
 
 
 
 
 	public function bulkitemdispatch() {
 
  if ($this->input->post('btn_editpurchases') == "myeditpurchase")
					   {
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

							 $view = trim($this->input->post("view"));
							 
													 $code = ($this->input->post("code"));

							  $myid = ($this->input->post("myid"));
							  $myview = ($this->input->post("myview"));

						$buyingprice = $this->input->post("buyingprice");
						
						
						$type ="P.O";
						
															  $description = ($this->input->post("description"));

							
															  $total = ($this->input->post("total"));

											 $branch = ($this->input->post("branch"));
											  $batchno = ($this->input->post("batchno"));
											  $batchid = ($this->input->post("batchid"));
											  
											  
											  
											  
											  
											  

											  $finalsalesid = ($this->input->post("finalsalesid"));
											  $producttype = ($this->input->post("producttype"));

											 
											 $qty = ($this->input->post("qty"));
								 $to = ($this->input->post("to"));
								  $from = ($this->input->post("from"));
					
  $ordernumber=0;
  	
		 		 $PO = $this->usermodel->populateallarray('quotation','invoice',$finalsalesid);
						 $orderdate=$PO[0]['orderdate'];
						  $mysupplier=$PO[0]['supplier'];
				
				
	
  $latest = $this->usermodel->populatelatestidcounter('batchlist', 'invoice',$finalsalesid);
  if($latest==FALSE){
	    $ordernumber=(double)$ordernumber+1;
	  
  }else{
	  
	     $ordernumber=(double) $latest+1; 
  }


			$count = count($myid);
									 $mydata=array(
		'type' =>"P.O",				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'batchid'=>$batchid,
			'batchno'=>$ordernumber,
	'description'=>$description,
							
								);
												
						$myusr_result="";
$finaltotalamount=0;
	$insertdebit = array();
						$inventoryaccount="";

						//active user record is present
							
   for($i=0; $i< $count; $i++) {
   
   $myfinalqty=0;
		 $myqty=0;
					$newstock = $this->usermodel->populateallarray('purchaseorderlist','id', $myid[$i]);
					$realqty=$newstock[0]['total'];
					$mybuyingprice=$newstock[0]['bprice'];
					$ourids=$newstock[0]['id'];
					$remqty=(double)$newstock[0]['qty'];
					$balance=(float)$remqty-(float)$realqty;
				if(($realqty < $remqty ) && ($balance >= $total[$i] )) {
					
						 	if($producttype[$i]!="Service"){
		
			  	if(($from[$i]=="Main")){
					$available = $this->usermodel->populateallarray('products','code', $code[$i]);
					$availabletotal=$available[0]['qty'];
					
					
					
	   
  					if($availabletotal < $total[$i]){

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The product('.$available[0]['name'].'-'.$code[$i].') was not dispatched! Your dispatch of ('.$total[$i].') products is less than what is in stock('.$availabletotal.'). Try again </div>');
							redirect($view);
							return false;
					}

					
					
					
					
					
				$finalqty=((double)$availabletotal-(double)$total[$i]);
											$mainstockdata=array(		
												'qty'=>$finalqty,
												
													);
									$this->usermodel->updateproduct($mainstockdata,$code[$i]); 

													
				}else{
					 $available = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $from[$i]);

  
						   			$availabletotal=$available[0]['qty'];
					
					
					
						   
  					if($availabletotal < $total[$i]){

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The product('.$available[0]['name'].'-'.$code[$i].') was not dispatched! Your dispatch of ('.$total[$i].') products is less than what is in stock('.$availabletotal.'). Try again </div>');
							redirect($view);
							return false;
					}

					
					
					
					
				$finalqty=((double)$availabletotal-(double)$total[$i]);
											
						   $branchdata=array(		
												'qty'=>$finalqty,
											
													);
					
					 $this->usermodel->updateproductlist($branchdata,$code[$i],$from[$i]);
				}
				
				
				
							}
				

				//$currenttotal=$remqty*$mybuyingprice;
		//$finaltotalamount=$finaltotalamount+ $currenttotal;
				
					$totalamount=(double)$total[$i]*(double)$buyingprice[$i];	
					
$finaltotalamount=(double)$finaltotalamount+(double)$totalamount;
					
				
      $data=array(
		'type' =>$type,				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'qty'=>$total[$i],
        'itemid' =>$myid[$i],
		 'batchid' =>$batchno[$i],
	'code' =>$code[$i],
	
							
								);
						
				
				
					 if($realqty < $remqty ){
						 $myusr_result=$this->usermodel->add($data,'orderlist');
					
	if ( $myusr_result==TRUE) {
		
				
				 ////
					
											$maindata=array(		
												'total'=>$myfinalqty,
												'date'=>$mydate,
													);
	$myfinalqtydispatch=((double)$realqty+(double)$total[$i]);
			$mybalance=((double)$realqty-(double)$myfinalqtydispatch);
												$maindatadispatch=array(		
												'total'=>$myfinalqtydispatch,
												'date'=>$mydate,
												'balance'=>$mybalance,
													);	
				if($this->usermodel->updatedata($maindatadispatch,'purchaseorderlist','id',$ourids)){
		
				
		
		
			 	if($producttype[$i]!="Service"){

		
			
			

				
				
				
				
				
			  	if(($to[$i]=="Main")){
					$available2 = $this->usermodel->populateallarray('products','code', $code[$i]);
					$availabletotal2=$available2[0]['qty'];
					
				$finalqty2=((double)$availabletotal2+(double)$total[$i]);
											$mainstockdata2=array(		
												'qty'=>$finalqty2,
												
													);
									$this->usermodel->updateproduct($mainstockdata2,$code[$i]); 

													
				}else{
					 $available2 = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $to[$i]);

  
						   			$availabletotal2=$available2[0]['qty'];
					
				$finalqty2=((double)$availabletotal2+(double)$total[$i]);
											
						   $branchdata2=array(		
												'qty'=>$finalqty2,
											
													);
					
					 $this->usermodel->updateproductlist($branchdata2,$code[$i],$to[$i]);
				}
				
				
				
				
				
				
				
							 $maindata	=array(		
			'total'=>$total[$i],
			'date'=>$mydate,
				'name'=>$available[0]['sellingprice'],
		  	'item_id'=>$code[$i],
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$code[$i],
				'stockfrom'=>$from[$i],
				'stockto'=>$to[$i],
				'type'=>$branchid,
				'buyingprice'=>$mybuyingprice,
				'sellingprice'=>$available[0]['sellingprice'],
				'balance'=>$finalqty2,
				'item_id1'=>$available2[0]['qty'],
	'frombefore'=>$availabletotal,
		'fromremoved'=>$total[$i],
			'fromafter'=>$finalqty,
	
								);
							//		$this->usermodel->updatedata($maindata,'newstock','id',$myid[$i]);
	
			$this->usermodel->add($maindata,'newstock');

						
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				}
				//$totalamount=$buyingprice[$i]*$total[$i];
									$correctavailable = $this->usermodel->populateallarray('products','code', $code[$i]);

									 if($inventoryaccount!=""){ $inventoryaccount=$correctavailable	[0]['assetaccount'];}else{ $inventoryaccount=1110; }	

				
			  
	}

			  
		
  					if($totalamount>0){
 $insertdebit[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$totalamount,'description'=>"Inventory ",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'type'=> 'inventory');
}
	  

	}
  								 
   }
   }
 
}
											
													
										
   
   
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							
							//	$this->usermodel->add($mydata,'batchlist');
													
													
	 					
 //$insertdebit[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$totalamount,'description'=>"Inventory ",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'type'=> 'inventory');



								
								// $debitdata=array( 'userid'=>$userid,'account'=>1110,'debit'=>$finaltotalamount,'description'=>"Purchases",'code'=>$finalsalesid,'crateddate'=>$mydate,'branch' => $branchid,'companyid'=> $companyid,'balance'=>0);

	   
  					if($finaltotalamount>0){









$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$finaltotalamount,'description'=>"Purchases",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0);

						//	$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							//$usr_result =$this->db->insert_batch('debitcredit', $insertdebit); 
							
							
							$people = $this->usermodel->populateallarray('people','id',$mysupplier);
									$supplierbalance=$people[0]["supplierbalance"];
									$peopleid=$people[0]["id"];
									
									
											$finalcustomerbalance=(double)$supplierbalance+(double)$finaltotalamount;
						$customerbalance=array(		
			
				'supplierbalance'=>$finalcustomerbalance,
										'lastbalancedate'=>$mydate,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
							
							
							
							}
							
								
									
									
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Data Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have dispatched all the quantities or No delivery entered. try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
 
 
 
 
 
 

 

 
 
 

 
 	public function bulkdelivery() {
 
  if ($this->input->post('btn_bulkdelivery') == "bulk")
					   {
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
     		  $dateposted=date("Y-m-d H:i:s");

	
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

							 $view = trim($this->input->post("view"));
							 
													 $code = ($this->input->post("code"));

							  $myid = ($this->input->post("myid"));
	  $serial = ($this->input->post("serial"));
						$buyingprice = $this->input->post("buyingprice");
						$sprice = $this->input->post("sprice");
												$bprice = $this->input->post("bprice");

						$type ="P.O";
						
															  $description = ($this->input->post("description"));

							
															  $total = ($this->input->post("total"));

											 $branch = ($this->input->post("branch"));
											  $batchno = ($this->input->post("batchno"));
											  $batchid = ($this->input->post("batchid"));

											  $finalsalesid = ($this->input->post("finalsalesid"));
											  $producttype = ($this->input->post("producttype"));
$ttbrice=0;
											 
											 $qty = ($this->input->post("qty"));
										
											 											 $to = ($this->input->post("to"));
					
  $ordernumber=0;
  	
				
	
  $latest = $this->usermodel->populatelatestidcounter('batchlist', 'invoice',$finalsalesid);
  
  
 $PO = $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
						 $orderdate=$PO[0]['orderdate'];
   $supplier=$PO[0]['supplier'];

  if($latest==FALSE){
	    $ordernumber=$ordernumber+1;
	  
  }else{
	  
	     $ordernumber= $latest+1; 
  }

  

  
  
										$count =count((array)$myid);
									 $mydata=array(
		'type' =>"S.O",				
	   'userid' =>$userid,
	    'branchid'=>$branchid,
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'batchid'=>$batchid,
			'batchno'=>$ordernumber,
	'description'=>$description,
		
							
								);
							$producttype="";
				
						$myusr_result="";
						$finaltotalamount=0;

						//active user record is present
					$insertdata = array();
					$insertinventorydata = array();

$salesaccount="";	
$inventoryaccount="";
	$costofgoodsold="";		
   for($i=0; $i< $count; $i++) {
   if($total[$i]>0) {

   $myfinalqty=0;
		 $myqty=0;
					$newstock = $this->usermodel->populateallarray('sales_order','id', $myid[$i]);
					$realqty=$newstock[0]['qty'];
					$remqty=$newstock[0]['sales'];
					$balance=(float)$remqty-(float)$realqty;
					
					if(($to[$i]=="Main")){
						
					$accountcode = $this->usermodel->populateallarray('products','code', $code[$i]);

					}else{
						
					 $accountcode = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $to[$i]);

						
					}
					
					
										 $myinventorytype=trim($accountcode[0]['producttype']);
					$availabletotals=$accountcode[0]['qty'];

if(($availabletotals < $total[$i]) && ($myinventorytype !="Service")) {
				   							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not  sell('.$total[$i].') more than what you have ('.$availabletotals.'). Try again.</div>');


		redirect($view);
			return false;			   	

}
	
					
					
					
					
					
					
					
					
					
					$salesaccount=$accountcode[0]['salesaccount'];
					   $transactionid=$newstock[0]['id'];
						$mybranch=$newstock[0]['branch']; 	

	  $producttype=$accountcode[0]['producttype'];
	

	 
		 
	  $costofgoodsold=$accountcode[0]['expenseaccount'];
	   $inventoryaccount=$accountcode[0]['assetaccount'];
	   
  if($costofgoodsold!=""){ $costofgoodsold=$accountcode[0]['expenseaccount'];}else{ $costofgoodsold=5500; }
 if($inventoryaccount!=""){ $inventoryaccount=$accountcode[0]['assetaccount'];}else{ $inventoryaccount=1110; }						
					  
					  
 if($salesaccount!=""){ $salesaccount=$accountcode[0]['salesaccount'];}else{ $salesaccount=4000; }
			
			
			
			
					
		$totalamount=(double)$total[$i]*(double)$sprice[$i];	
$finaltotalamount=(double)$finaltotalamount+(double)$totalamount;	










      $data=array(
	  
		'type' =>$type,				
	   'userid' =>$userid,
	    'branchid'=>$to[$i],
		 'companyid' =>$companyid,
	   'exactime' =>$mydate,
		'invoice'=>$finalsalesid,
		'qty'=>$total[$i],
        'itemid' =>$myid[$i],
		 'batchid' =>$batchno[$i],
	'code' =>$code[$i],
	
	'amount'=>$totalamount,
	
							
								);
						
				
				
					 if($realqty < $remqty ){
						 $myusr_result=$this->usermodel->add($data,'orderlist');
					
	if ( $myusr_result==TRUE) {
		
				
				
				if ( $serial !="") {	
				$serialdata=array(		
						'status'=>"used",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$serial[$i]);

				}
				
				
				
				
				
				
					$myinvoices =  $userid.time().$this->createRandomPasswordForsales();

				
				
				 
					$myfinalqty=((double)$realqty+(double)$total[$i]);
											$maindata=array(		
												'qty'=>$myfinalqty,
												//'myinvoice'=>$myinvoices.[$i],
												
													);
			
		if($this->usermodel->updatedata($maindata,'sales_order','id',$myid[$i])){
			 	if($producttype[$i]!="Service"){
		
			  	if(($to[$i]=="Main")){
					$available = $this->usermodel->populateallarray('products','code', $code[$i]);
					$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal-$total[$i]);
											$mainstockdata=array(		
												'qty'=>$finalqty,
												
													);
									$this->usermodel->mainstockdata($mainstockdata,$code[$i]); 

													
				}else{
					 $available = $this->usermodel->populatealldataarray('productlist','code', $code[$i],'branch', $to[$i]);

  
						   			$availabletotal=$available[0]['qty'];
					
				$finalqty=($availabletotal-$total[$i]);
											
						   $branchdata=array(		
												'qty'=>$finalqty,
											
													);
					
					 $this->usermodel->updateproductlist($branchdata,$code[$i],$to[$i]);
					 
					 
		
				} 
					 
							
		  $finalbprice=($bprice[$i]*$total[$i]);

					 
						if($finalbprice!=""){
		
		$ttbrice=$ttbrice+ $finalbprice;
		 $insertinventorydata[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$finalbprice,'description'=>"Inventory sold",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'sales','supplier'=>$supplier);
	 
					 
					 
					 
				}
				
				
				
				
				
				
				
				
				
				}
			  
	}

			  
			  

	}
  								 
   }
   
   
   
   
   

 
   
  					if($totalamount>0){
 $insertdata[]=array('refno'=>$code[$i], 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$totalamount,'description'=>"Sales order",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $mybranch,'companyid'=> $companyid,'type'=> 'sales','supplier'=>$supplier);
}


   
   }
					   }
 

												if ($myusr_result ==TRUE) {
													$this->usermodel->add($mydata,'batchlist');
													
				


				
if($ttbrice!=0){
	$this->db->insert_batch('debitcredit', $insertinventorydata); 

$insertcostofgoodsolddata=array( 'userid'=>$userid,'account'=>$costofgoodsold,'debit'=>$ttbrice,'description'=>"Cost of goods sold",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','supplier'=>$supplier);
$this->usermodel->add($insertcostofgoodsolddata,'debitcredit');

}

								
								 $creditdata=array( 'userid'=>$userid,'account'=>4000,'credit'=>$finaltotalamount,'description'=>"Sales order",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','supplier'=>$supplier);


$debitdata=array( 'userid'=>$userid,'account'=>1100,'debit'=>$finaltotalamount,'description'=>"Sales order",'code'=>$finalsalesid,'crateddate'=>$orderdate,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','supplier'=>$supplier);

							$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
								$usr_result =$this->db->insert_batch('debitcredit', $insertdata); 
					
													
													
													
													
													
													
												}
   
   
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							
								
									
									
								
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Delivery done successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Delivery failed! May be because  you have not edited any price or no pending delivery . try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
 
 
 
 
 
 public function bulktableupdate() {
 	
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $oldid = $this->input->post("oldid");
		   	  //$newid = $this->input->post("newid");

		   	  $newid = $this->input->post("newid");
			  		 $column = $this->input->post("column");

		    
		
				
			  		  $this->form_validation->set_rules("oldid", "Previous uSER ID", "trim|required");

			  
 
  	 	if ($this->input->post('btn_updatebulktables') == "bulkupdate")
					   {
						   	 $database="robisear_myerp";

						   									$bulkupdate= $this->usermodel->populatealltables($database);


								
												
						$myusr_result="";

							
							 	if(is_array($bulkupdate)){
	 
	 foreach ($bulkupdate as $c){
		 
		  $tablename=trim($c->table_name);
		  if(($tablename!="permissions")){
			  
		 	
		       $confirmdata=$this->usermodel->confirmuser($tablename,$column, $oldid);

						  if ($confirmdata ==true)
						   {
							 
							 
	
   $data=array(		
       $column=>$newid,
       

				);
					$myusr_result = $this->usermodel->updatedata($data,$tablename, $column,$oldid);

   			
	   }
	 }	   
   }
}
 ////$usr_result =$this->db->update_batch('stock',$updateArray, 'id'); 


														
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								
							
								 
						 $this->session->set_flashdata('mymsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the tables..</div>');	
							
							redirect('user/bulkupdate');

							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('mymsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some tables were not updated due to wrong column name or lack of records.Try again</div>');
								
							redirect('user/bulkupdate');


							}
  
  
	}
  
  
  
  

    
	}
 
 
 
 
 public function bulkvatpdate() {
 	
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $oldvat = $this->input->post("oldvat");

		   	  $newvat = $this->input->post("newvat");

		    		   	  $type = $this->input->post("type");

		
				
			  		  $this->form_validation->set_rules("oldvat", "Previous VAT", "trim|required");

			  
 
  	 	if ($this->input->post('btn_updatevat') == "bulkvat")
					   {

	
												
						$myusr_result="";

	
	
		$data=array(		
		
       		  'tax_included' => $newvat,    


				);
										$myusr_result = $this->usermodel->updatedata($data,'products','tax_included',$oldvat);







														
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
							$this->usermodel->updatedata($data,'productlist','tax_included',$oldvat);

							if($type=="All"){
		$maindata=array(		
		
       		  'tax1rate' => $newvat,    


				);
								 
								 
								 
								 
								 
								 
								 							$this->usermodel->updatedata($maindata,'smsconfig','tax1rate',$oldvat);

							}
								 
								 
								 
								 
						 $this->session->set_flashdata('mymsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the new tax to '. $newvat.' %</div>');	
							
							redirect('user/bulkupdate');

							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('mymsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> VAT Details were not updated .Try again</div>');
								
							redirect('user/bulkupdate');


							}
  
 }
    
	}
 
 
 
 
 
 
	
	public function uploadvisitors()
        {

          if(isset($_POST["btn_uploadvisitors"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  	// $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		
		   $currenttime = date('Y-m-d H:i:s');
		
					    $fromdate = $this->input->post("fromdate");
					  
	

  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
					
				$type="customer";	
					
				
				
     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
						
				if($emapData['A']!=""){
				
          $accounttype = $emapData['C'];
					
            $correctime = date("Y-m-d", strtotime($fromdate));

						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
								
			'name'=>$emapData['A'],
				'idno'=>$emapData['B'],
				'phone'=>$emapData['C'],
			

				'subject'=>$emapData['D'],
				'business'=>$emapData['E'],


		  	'description'=>$emapData['F'],
			'vehicleno'=>$emapData['G'],
				 'companyid'=>$companyid,
			
				 	'checkindate'=>$fromdate,
				'createdate'=>$correctime,
				 	 


                                );
                    
                        $usr_result = $this->usermodel->uploadalldata("gatepass",$mydata);
						
                    

	
	
	
	
	   $i++;
				}
	
                   	  }               
              
			  
			
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded Visitors!</div>');
								
								 redirect('user/viewgatepass');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some  Data was not uploaded.. No data was saved.Try again</div>');
								
								 redirect('user/viewgatepass');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


		
		
	
	
	
	
	
	
	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 public function updatedkitchenprinter() {
 	
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $kitchen = $this->input->post("kitchen");
		 		 $myid = $this->input->post("myid");


		    		   	  $kitchenid = $this->input->post("kitchenid");

		
				
			  		  $this->form_validation->set_rules("kitchen", "Kitchen Mode", "trim|required");

			  
 
  	 	if ($this->input->post('btn_updatedkitchenprinter') == "printer")
					   {

	
												
						$myusr_result="";

	
	
		$data=array(		
		       		  'kitchen' => $kitchen,    

       		  'kitchenid' => $kitchenid,    


				);
				$myusr_result = $this->usermodel->updatedata($data,'smsconfig','id',$myid);







														
							//check if username and password is correct
							if ($myusr_result ==TRUE) //active user record is present
							{
								

							
								 
								 
								 
								 
						 $this->session->set_flashdata('mymsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the Kitchen Printer.</div>');	
							
							redirect('user/kitchenprinter');

							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('mymsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Kitchen update failed .Try again</div>');
								
							redirect('user/kitchenprinter');


							}
  
 }
    
	}
 
 
	
	
	public function allattendance()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	          $this->load->view("template/headerpagemin");

				
				$config['base_url'] = base_url('Systemusers/allattendance');
			
		
  
		
		
		//$query  = $this->usermodel->displayallsalesdata($config["per_page"], $page,'sales_order','invoice',$finalsalesid,'status','new');
							$config['total_rows'] = $this->usermodel->count_allwhere('attendance','attendance.id >',0);
		     


		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";

		$this->pagination->initialize($config);
		//$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        //$data["allattendance"] = $this->usermodel->displayallattendance($config["per_page"], $page,'attendance','attendance.id >',0);
			$data["allattendance"]  = $this->usermodel->displayallinone($config["per_page"], $page,'attendance','attendance.id >',0);

		        //$data["allattendance"] = $this->usermodel->displayall($config["per_page"], $page,'attendance','attendance.id >',0);
	$this->load->view("template/tableheader");

		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allattendance',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
public function addattendance()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
 	 		
			$idno = trim($this->input->post("idno"));
			$date = $this->input->post("date");
			$timein = $this->input->post("timein");
			$type = $this->input->post("type");		  
			$comment = $this->input->post("comment");    
		
		
				  
  
				
			 $this->form_validation->set_rules("idno", "idno/admno", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/allattendance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
										  $new_date=date("Y-m-d H:i:s");

					   //validation succeeds
					 	if ($this->input->post('btn_addattenance') == "attenance")
					   {
												$data=array(		
			
				'idno'=>$idno,
			'date'=>$date,
		  	'timein'=>$timein,
			
			
			
			'type' => $type,		  
		  'comment' => $comment,    
		 
		   		  'createddate' => $new_date,    

		
			  
			   
			 
			   
				
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'attendance');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted a new  attenance..</div>');	
							redirect('user/allattendance');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Attendance  was not added.. Try again</div>');
								
								 redirect('user/allattendance');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
  
  public function adddevice()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewdevices', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adddeactivation') == "device")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'device');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  device..</div>');	
							redirect('user/viewdevices');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Device  was not added.. Try again</div>');
								
								 redirect('user/viewdevices');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
 
	public function searchattendance()
	{ 
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $fromdate = $this->input->post("fromdate");
	  $type = $this->input->post("type");
	  

	  
	  $todate = $this->input->post("todate");
	  $category = $this->input->post("category");
		  $dublicate = $this->input->post("dublicate");
		  $sms = $this->input->post("sms");

  $myidno = explode(':=',$this->input->post("idno"));

 
  $idno = htmlspecialchars(trim($myidno[0]));









				$this->load->view("template/headerpagemin");
						  
			$data['links']="";
			

	
		$query = $this->usermodel->viewattandance($fromdate,$todate,$category,$type,$dublicate,$sms,$idno);

		
		
		$data['allattendance'] = $query['records'];
$data['total_rows'] = $query['count'];



		
		
				$this->load->view('userdata/allattendance',$data);
		$this->load->view("template/footerpage");
	}
	
 
 
 
 
 
 
 
 
 
 
 
 	public function syncattandencenow()
	{ 
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	

	  $type = $this->input->post("type");
	  
  $createdate = date('Y-m-d H:i:s');
	  
	   $todate = $this->input->post("todate");
 $totime = $this->input->post("totime");
 $frotime = $this->input->post("frotime");
	  $fromdate = $this->input->post("fromdate");
	  
	   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;

$data['todate']=$todate;
$data['fromdate']=$fromdate;
	  
	  
	  
	  
	  
	  
	 
		 echo $code = $this->input->post("code");
		  $month = $this->input->post("month");

				$this->load->view("template/headerpage");
						  
			$data['links']="";
			///

	
		$query = $this->usermodel->viewallattandance($fromdate,$todate,$companyid);


		   
						   
if(is_array($query)) {

$insertdata = array();
   foreach($query as $row){
	     
			    $idno=trim($row->idno);
								  

				 $allusers=$this->usermodel->populateallarray('people','idno', $idno);
				 $employeeid=$allusers[0]['id'];
	
	
	$products = $this->usermodel->populatealldataarray('employeecharges','code', $code,'memberid', $employeeid);

			   $products=$this->usermodel->populateallarray('employeecharges','code', $code);
									
				$rate=$products[0]['amount'];
	   
	 
	   		$fromdate = strtotime(date($row->date));
		$todate = strtotime(date($row->checkoutime));
		
			$hours=trim($row->timediffrence);
				//$hours= round(($todate-$fromdate) / 3600,2);

    $exactdate=trim($row->date);

  $total=$rate*$hours;
	  
	  
	  	$insertdata[]=array(		
						
				 	'userid'=>$userid,
			
				'code'=>$code,
				'employeeid'=>$idno,
				'createdate'=>$createdate,
				'month'=>$month,
				'rate'=>$rate,
				'total'=>$total,








				'description'=>"Attendance",
				'branch'=>$branchid,
				'qty'=>$hours,


				 'companyid'=>$companyid,
				 'exactdate'=>$exactdate,


											);
											
	  
	  
	  
	  
	  
	  
	  
	  
   
   }
   
   
   $this->db->insert_batch('labour', $insertdata); 

   
   
   
        if($this->db->affected_rows() > 0)
	{
		
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully synced the attenance   ..</div>');	
							redirect("user/viewlabour");																
							}else {
							   

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> attenance were not uploaded into the system.. Try again</div>');

							redirect("user/viewlabour");																
							}
   
   
   
}else{
	
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> attenance were not uploaded into the system..It seems there is no data. Try again</div>');

							redirect("user/viewlabour");	
}








		
		
		//$data['allattendance'] = $query['records'];
//$data['total_rows'] = $query['count'];



		
		
		//$this->load->view("template/footerpage");
	}
	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
  public function updateattendance()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $type = $this->input->post("type");
		 			 		 $view = $this->input->post("view");

			  
		    
		
				
			  		  $this->form_validation->set_rules("type", "Status type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/allattendance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateattendance') == "attenance")
					   {
												$data=array(		
			
			
		  	'timediffrence'=>$type,
			 	
				
			
								);
														$usr_result = $this->usermodel->updatedata($data,'attendance','id >',0);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the status..</div>');	
							redirect('user/allattendance');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Status  was not Updated.. Try again</div>');
								
								 redirect('user/allattendance');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
 
 
 
  
 
 public function bulkclosingstock() {
 
 					
						   
						   
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

						  $myid = $this->input->post("myid");
		 			  $method = $this->input->post("method");

		  $balance = $this->input->post("balance");
		  $action = $this->input->post("action");

	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
		  $department = $this->input->post("department");
		  $mybranch = $this->input->post("mybranch");
		  $code = $this->input->post("code");
		  $added = $this->input->post("added");

			  		  $this->form_validation->set_rules("balance", "Closing balance", "trim|required");

 
  	 	if ($this->input->post('btn_bulkclosingstock') == "mybulk")
					   {

										$count =count((array)$myid);
								
												
						$myusr_result="";

						//active user record is present
							
   for($i=0; $i< $count; $i++) {
	
   
 			 $updateArray[] = array(
        'id'=>$myid[$i],
       'balance'=>$balance[$i],
	          'added'=>$added[$i],

    );
    /*  $data=array(
	  
		
	    'balance'=>$balance[$i],
			);
						
		$usr_result = $this->usermodel->updatedata($data,'stock','id',$myid[$i]);
if ($usr_result ==TRUE){
	
							$this->usermodel->updatedatabytwo($productdata,'productlist','code',$code[$i],'branch',$mybranch[$i]);

} 
	*/						
													$productdata[] =array(	
														'code'=>$code[$i],													
													'qty'=>$balance[$i],
													);	
											
   }
 
 $usr_result =$this->db->update_batch('stock',$updateArray, 'id'); 


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								if($action=="Yes"){
									 $this->db->where('branch',$mybranch);
								$usr_result =$this->db->update_batch('productlist',$productdata, 'code'); 
  	
								}
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the stock..</div>');	
							
							redirect('user/enterallclosingstock?startdate='.$startdate.'&department='.$department.'&branchid='.$branchid.'&method='.$method.'&action='.$action);	

		//$this->enterallclosingstock($startdate,$branchid,$department);
return true;
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not Updated.. You did not put any  new closing stock. Try again</div>');
								
							redirect('user/enterallclosingstock?startdate='.$startdate.'&department='.$department.'&branchid='.$branchid.'&method='.$method.'&action='.$action);	


							}
  
  
	}
  
  
  
  

    
	}
 
 
 
 	public function bulksuplierpayment() {
 
 					
						   
						   
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	   $TOTALPAID=0;
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

						  $myid = $this->input->post("myid");
		 			  $supplier = $this->input->post("supplier");
		 			  $mysupplier = $this->input->post("supplier");

		  $invoice = $this->input->post("invoice");
		  $action = $this->input->post("action");
		  		  $originalamount = $this->input->post("originalamount");


	  $expamount = $this->input->post("amount");
	  $paid = $this->input->post("paid");
		  $dateposted = $this->input->post("paiddate");
		  		  $makepayment = $this->input->post("makepayment");
$supplier="";
$difference=0;

		  $bankid = $this->input->post("bankname");
		  $payment = $this->input->post("payment");
		  $billid = $this->input->post("myid");
		  $description = $this->input->post("description");
		  $paymentmethodes = $this->input->post("bankname");
		  $transactioncode = $this->input->post("transactioncode");

			  		  $this->form_validation->set_rules("invoice", "Invoice", "trim|required");

 $finalsupplier="";
 	$finalinvoice="";
  	 	if ($this->input->post('btn_bulksuplierpayment') == "bulkpayment")
					   {

		if($transactioncode !=""){
						 $confimcode = $this->usermodel->populateallarray('collection','transactioncode', $transactioncode);

if($confimcode !=false){
	   	$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Payment  was not posted!</strong> This transaction / Ref No/ Cheque Number has been used.:('.$transactioncode.'). Try again.</div>');

						  
							redirect('user/viewpurchases');						   
						  return false;
	
}
					}

//abuna
//







										$count =count((array)$myid);
								
												
						$myusr_result="";

						//active user record is present
							
   for($i=0; $i< $count; $i++) {
	   if(($makepayment[$i]=="yes") && ($payment[$i]>0)){
	
	 $glaccounts = $this->usermodel->populateallarray('glaccounts','number', $bankid[$i]);
						 $availablebalance=$glaccounts[0]['amount'];
	 $finalglbalance=$availablebalance-$payment[$i];
	 
	 
	   $nextglaccounts = $this->usermodel->populateallarray('glaccounts','number', 2130);
						  $nextavailablebalance=$nextglaccounts[0]['amount'];
	 $nextfinalbalance=$nextavailablebalance-$payment[$i];
	 $TOTALPAID=$TOTALPAID+$payment[$i];
						   
					
						 $currentbalance = $this->usermodel->populateallarray('purchaseorder','id', $billid[$i]);

	 $mybalance=$currentbalance[0]['balance'];
$mypayment=$currentbalance[0]['paid'];	

	$supplier=$currentbalance[0]['supplier'];
		   
	$myorignalamount=$currentbalance[0]['amount'];	

	 $bankdata=array(		
												'amount'=>$finalglbalance,
													);
													$nextbankdata=array(		
												'amount'=>$nextfinalbalance,
													);
								
								
								









	$finalbank="";
		$finaldate="";
			$finaldescription="";				 
						$mystatus=""; 
						
						   
					$myfinalbalance= (float)$myorignalamount-((float)$mypayment);

						$finalbalance= (float)$myorignalamount-((float)$mypayment+ (float)$payment[$i]);
						$finalpaymant=((float)$mypayment+ (float)$payment[$i]);
						   
						    if ($finalpaymant>$myfinalbalance)
						   {
							   	 //$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 // <strong>Payment was not posted for this invoice('.$invoice[$i].')!</strong> The  amount('.$payment[$i].') you are trying to pay is higher than the pending balance('.$myfinalbalance.'). Try again.</div>');

						  
							 //redirect('user/viewpurchases');						   
						   //return false;
						   }
						   if($finalbalance<=0){
							   
							 	$mystatus="closed"; 
						   }else{
							   $mystatus="active"; 
						   }
	$billdata=array(		
			

								);
   
 			 $Paymentdata = array(
        
			  'userid'=>$userid,
			 'name'=>"paid",
				'amount'=>$payment[$i],
							'supplier'=>$supplier,

		  	'remarks'=>$description[$i],
			 	'companyid'=>$companyid,
						'invoice'=>$invoice[$i],
'createdate'=>$dateposted[$i],
			'paiddate'=>$dateposted[$i],
								'transactioncode'=>$transactioncode,

					'balance'=>$finalbalance,
				'paymentmethodes'=>$paymentmethodes[$i],

    );
    				
	 		$usr_result = $this->usermodel->add($Paymentdata,'collection');
if ($usr_result ==TRUE){
		$updatedata=array(		
			
				'paid'=>$finalpaymant,
			
		 
			 	
						'transactionstatus'=>$mystatus,
				'updatedid'=>$userid,
			'companyid'=>$companyid,
			'updateddate'=>$dateposted[$i],
				'balance'=>$finalbalance,
			
								);
$this->usermodel->updatedata($updatedata,'purchaseorder','id',$billid[$i]);



															
$debitdata=array( 'transactioncode'=>$transactioncode,'type'=>"supplier payment", 'userid'=>$userid,'account'=>2130,'debit'=>$payment[$i],'description'=>$description[$i],'code'=>$invoice[$i],'crateddate'=>$dateposted[$i],'branch' => $branchid,'companyid'=> $companyid,'balance'=> $nextfinalbalance,'supplier'=>$supplier);



							$usr_result = $this->usermodel->add($debitdata,'debitcredit');		


$finalbank=$bankid[$i];
		$finaldate=$dateposted[$i];		
 $finalsupplier=$supplier[$i];	
		 $finaldescription="Bulk ".$description[$i];	
$finalinvoice=$invoice[$i];
										

}

   }									
   }
 


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								

								$creditdata=array('transactioncode'=>$transactioncode,'type'=>"supplier payment",  'userid'=>$userid,'account'=>$finalbank,'credit'=>$originalamount,'description'=>$finaldescription,'code'=>$finalinvoice,'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier);
							$this->usermodel->add($creditdata,'debitcredit');


$difference=$originalamount-$TOTALPAID;

							
							if($difference>0){
								
							$overpaymentdebitdata=array('transactioncode'=>$transactioncode,'type'=>"supplier payment",  'userid'=>$userid,'account'=>2130,'debit'=>$difference,'description'=>"overpayment to supplier",'code'=>$finalinvoice,'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier);

							$this->usermodel->add($overpaymentdebitdata,'debitcredit');
								
								
							}
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the stock..</div>');	
							
							 redirect('user/viewpurchases');						   

		//$this->enterallclosingstock($startdate,$branchid,$department);
return true;
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock  was not Updated.. You did not put any  new closing stock. Try again</div>');
								
							 redirect('user/viewpurchases');						   


							}
  
  
	}
  
  
  
  

    
	}
 
 
 
 
 
 
 
 
 
 
 
 	public function bulkcustomerpayment() {
 
 			//uruani	
						   
						   
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        //
 
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	   $TOTALPAID=0;
					   $myfinalqty=0;
     		  $mydate=date("Y-m-d H:i:s");

						  $myid = $this->input->post("myid");
		 			  $supplier = $this->input->post("supplier");

		  $invoice = $this->input->post("invoice");
		  $action = $this->input->post("action");

	  $expamount = $this->input->post("amount");
	  $paid = $this->input->post("paid");
		  $dateposted = $this->input->post("paiddate");
		  		  $makepayment = $this->input->post("makepayment");

		  $bankid = $this->input->post("bankname");
		  $payment = $this->input->post("payment");
		  $billid = $this->input->post("myid");
		  $description = $this->input->post("description");
		   $paymentmethodes = $this->input->post("paymentmethodes");
		 
		  	  $finainvoice = "";
		  
		  $difference=0;
		  
		  
		    $originalamount = $this->input->post("originalamount");
	  	  $transactioncode = $this->input->post("transactioncode");
		
  
	   
	   

			  		  $this->form_validation->set_rules("invoice", "Invoice", "trim|required");
$name="payment";
 $finalsupplier="";
  	 	if ($this->input->post('btn_bulkreceivedcustomerpayment') == "bulkpayment")
					   {

										$count =count((array)$myid);
								
												
						$myusr_result="";

						$people = $this->usermodel->populateallarray('people','id',$supplier);
									$customerbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
							
   for($i=0; $i< $count; $i++) {
	   if(($makepayment[$i]=="yes") && ($payment[$i]>0)){
	

					$viewsales = $this->usermodel->populateallarray('sales', 'invoice',$invoice[$i]);
									 $mainbalance=$viewsales[0]['balance'];
									  $maintotal=$viewsales[0]['total'];
									  $maincash=$viewsales[0][$paymentmethodes];
									   $maincredit=$viewsales[0]['credit'];
									     $mycustomer=$viewsales[0]['customer'];
										 $finalcustomerbalance=0;
										 
	
										 
										 
										 
										 
										 
     $finalcash=$maincash+$payment[$i]; 
 $mybalance=$payment[$i]+$mainbalance;
			 $finalcredit=$maincredit-$payment[$i];		   
					
						
								
								







	$finalbank="";
		$finaldate="";
			$finaldescription="";				 
						$mystatus=""; 
						
						   
						   						//$myfinalbalance= $myorignalamount-($mypayment);

						//$finalbalance= $myorignalamount-($mypayment+ $payment[$i]);
					//	$finalpaymant=($mypayment+ $payment[$i]);
						   
						   
						   
						   
						  if( (-$payment[$i])< ($mainbalance)){
						   
							   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Payment was not posted for this invoice('.$invoice[$i].')!</strong> The  amount('.$payment[$i].') you are trying to receive is higher than the pending balance('.$mybalance.'). Try again.</div>');

						  
							 redirect('user/allinvoices');						   
						   return false;
						   }
						  
						
						  
						  
						  	
	$TOTALPAID=$TOTALPAID+$payment[$i];
						  
				  
						  
						  
						  
						  
						  
	$billdata=array(		
			

								);
   
 			 $Paymentdata = array(
        
			  'userid'=>$userid,
				'name'=>$name,

				'amount'=>$payment[$i],
		'remarks'=>$paymentmethodes,

		  	//'remarks'=>$description[$i],
			 	'companyid'=>$companyid,
						'invoice'=>$invoice[$i],
			'createdate'=>$dateposted[$i],

			'paiddate'=>$dateposted[$i],
					'balance'=>$mybalance,
				'paymentmethodes'=>$bankid[$i],

    );
    	
		



		  	  $finainvoice =$invoice[$i];




				
	 		$usr_result = $this->usermodel->add($Paymentdata,'collection');
if ($usr_result ==TRUE){
		
	$updatedata=array(	
								'credit'=>$finalcredit,

						'balance'=>$mybalance,
						$paymentmethodes=>$finalcash,
								);
	
						$this->usermodel->updatedata($updatedata,'sales','invoice',$invoice[$i]);
						
								 

															
$creditdata=array( 'userid'=>$userid,'account'=>1100,'credit'=>$payment[$i],'description'=>$description[$i],'code'=>$invoice[$i],'crateddate'=>$dateposted[$i],'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$supplier);



							$usr_result = $this->usermodel->add($creditdata,'debitcredit');		


$finalbank=$bankid[$i];
		$finaldate=$dateposted[$i];		

		 $finaldescription="Bulk ".$description[$i];	

										

}

   }									
   

   }


												
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
						
								$debitdata=array( 'userid'=>$userid,'code'=>$finainvoice, 'account'=>$finalbank,'debit'=>$originalamount,'description'=>$finaldescription,'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$supplier  ,'transactioncode'=>$transactioncode);

								
								//$debitdata=array( 'userid'=>$userid,'code'=>"Bulk payment", 'account'=>$finalbank,'debit'=>$originalamount,'description'=>$finaldescription,'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$supplier  ,'transactioncode'=>$transactioncode);

							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
								

$difference=$originalamount-$TOTALPAID;

							
							if($difference>0){
								
								$overpaymentdebitdata=array( 'userid'=>$userid,'code'=>$finainvoice, 'account'=>1100,'credit'=>$difference,'description'=>"customer overpayment",'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$supplier  ,'transactioncode'=>$transactioncode);

							$this->usermodel->add($overpaymentdebitdata,'debitcredit');
								
								
							}
								
								
								
								
										 
								 if($TOTALPAID>0){

										$finalcustomerbalance=$customerbalance-$originalamount;
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
			'lastbalancedate'=>$finaldate,
			
								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$supplier);
				
									
								
									 
								 }
								 
								 
								 
								 
								 
								if($paymentmethodes=="mpesa"){
										  	  	

										 $productdatass=array(		
												'used'=>1,
													);
								$this->usermodel->updatedata($productdatass,'sms_in','code',$transactioncode); 


								}
										 
								 
								 
								 
								 

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the invoice..</div>');	
							
							 redirect('user/allinvoices');						   

						return true;
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> invoice  was not Updated. Try again</div>');
								
							 redirect('user/allinvoices');						   


							}
  
  
	}
  
  
  
  

    
	
 
 
 
 	}
 
 
 
    public function addpurchaseorderdata()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	

		
 //$code = htmlspecialchars(trim($this->input->post("code")));
 
 $codes = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($codes[0]));

 
 
		$qty = trim($this->input->post("qty"));
	  $discount = trim($this->input->post("discount"));
	    $tax = trim($this->input->post("tax"));
	
	  
	  $myview = trim($this->input->post("view"));  

  
		    
		      $invoice = trim($this->input->post("invoice")); 
						      $productname=$this->usermodel->populateallarray('products','code',$code);

						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
							redirect('user/viewnewpurchaseorder?randomitemidentifier='.$invoice);	
	
								
							//redirect('user/viewsales');						   
						   return false;
						   }
						   
						   
						   if($tax=="pick"){
							 $tax=$productname[0]['vattype'];  
							   
						   }
						   
						  
						   
						   
						  $productid=$productname[0]['id'];  
  $buyingprice=$productname[0]['buyingprice']; 
      $newsellingprice=trim($productname[0]['sellingprice']); 
	  
		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 


			$maincapital = $this->usermodel->populateallarray('purchaseorder','invoice',$invoice);

	    $currentamount=trim($maincapital[0]['amount']);
 //$sellingprice=$buyingprice-$discount;
  $sellingprice=(double)$buyingprice-(double)$discount;

  $finaldiscount= ((double)$discount*(double)$qty);
     $amount= (((double)$qty)* ((double)$buyingprice));
//exit;
$finalamount=(double)$currentamount+(double)$amount;
   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
							 $finaltax=0;
							 
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								 $mytax=1+($tax_included/100); 
								 $vatable=($sellingprice/$mytax);
								 $myfinaltax=(($sellingprice-$vatable)*$qty);
								
								$finaltax= $this->formatMoney($myfinaltax, true);
								 
							 }
							 
			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    							redirect('user/viewnewpurchaseorder?randomitemidentifier='.$invoice);	

		}
		 else
		{
			

			
					   					$data=array(		
			'userid'=>$userid,
			
				'item_id'=>$code,
			'qty'=>$qty,
		  	'discount'=>$finaldiscount,
			
			'companyid'=>$companyid,

			'date'=>$dateposted,
					 'type'=>$branchid, 
		  				'status'=>'PO',
		     'invoice_number' => $invoice,  

		     'invoice' => $invoice,  

			      'amount' => $amount, 
			   			      'buyingprice' => $buyingprice, 
							   'sellingprice' => $sellingprice, 
							'tax' => $tax,  
					  	'vatrate'=>$tax_included,
						'vat' => $finaltax,
			
			
			
								);
								
												
								
							$usr_result = $this->usermodel->add($data,'newstock');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'purchaseorder','invoice',$invoice);

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product Added </div>');	
							
							redirect('user/viewnewpurchaseorder?randomitemidentifier='.$invoice);	
	
								

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
															//redirect('user/viewsales');	
							redirect('user/viewnewpurchaseorder?randomitemidentifier='.$invoice);	


																						redirect($myview);	

															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
   public function addsalesorderdata()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	
			  $codes = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($codes[0]));

		
 //$code = htmlspecialchars(trim($this->input->post("code")));
 						  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

 
 
 
 
 
 
 

 $myvattype = trim($this->input->post("vattype"));

 
$qty = trim($this->input->post("qty"));
	  $discount = trim($this->input->post("discount"));
	  $myview = trim($this->input->post("view"));  

	
  
		    
		      $invoice = trim($this->input->post("invoice")); 
						      $productname=$this->usermodel->populateallarray('products','code',$code);

						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
							redirect('user/viewnewsalesorder?randomitemidentifier='.$invoice);	
	
								
							//redirect('user/viewsales');						   
						   return false;
						   }
						   
						   
						   
					 $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);	   
						   $tax2rate=$myconfiguration[0]["tax2rate"];
						   
						   
						   
						   
						   
						   
						   
						  $productid=$productname[0]['id'];  
  $buyingprice=$productname[0]['buyingprice']; 
      $newsellingprice=trim($productname[0]['sellingprice']); 
	  	        $taxtype=trim($productname[0]['taxtype']); 

		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 


			$maincapital = $this->usermodel->populateallarray('purchaseorder','invoice',$invoice);

	    $currentamount=trim($maincapital[0]['amount']);
 $sellingprice=(float)$newsellingprice-(float)$discount;
  //$finaldiscount= ($discount*$qty);
	   $finaldiscount= ((float)$discount* (float)$qty);

	 	  $description = trim($productname[0]['description']); 


   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
	    $tax_vattype=trim($productname[0]['vattype']);

	
							  	 $finaltax = 0.00;
	
							   	 $finaltax2 = 0.00;
								$vattype = "";
								$taxable = 0.00;
							    if ($myvattype !="VATABLE"){
							   
								$finaltax = 0.00;
	
							   	 $finaltax2 = 0.00;
								$vattype = $myvattype;
								$taxable = 0.00;
							   
							   
						   }else{
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax = 0.00;
	
							   	 $finaltax2 = 0.00;
								$vattype = $myvattype;
								$taxable = 0.00;
							   
								 
							 }else{
								 
								 
								 
								 
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 $vatable=($sellingprice);	

								  $getvatable=($sellingprice*$mytax);	
								 $myfinaltax=(($getvatable-$sellingprice)*$qty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{

								 $mytax=1+($tax_included/100); 
								  $vatable=($sellingprice/$mytax);
								   $myfinaltax=(($sellingprice-$vatable)*$qty);

									}
								 
								 
								 
								 
								// $mytax=1+($tax_included/100); 
								// $vatable=($sellingprice/$mytax);
								// $myfinaltax=(($sellingprice-$vatable)*$qty);
								
								$finaltax= $this->formatMoney($myfinaltax, true);
								 
								$myinvoices =  $userid.time().$this->createRandomPasswordForsales();
												

				
							 
								$vattype = $tax_vattype;
								//$taxable = $vatable*$qty;
								//$taxable= $this->formatMoney(($vatable*$qty), true);

								$display2=$myconfiguration[0]["display2"]; 

	if($display2=="yes"){

	
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$qty)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$taxable= $this->formatMoney($ttoltaxable, true);

			
			
			

			
			

	}else{
	 $finaltax2=0;
		$taxable= $this->formatMoney(($vatable*$qty), true);


	}
							
							   
							 }
	}
			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
    							redirect('user/viewnewsalesorder?randomitemidentifier='.$invoice);	

		}
		 else
		{
			
						     $amount= (($qty)* ($sellingprice));
$finalamount=$currentamount+$amount;

								
			
			
					   					$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'vattype'=>$vattype,
									'tax2'=>$finaltax2,
									'taxable'=>$taxable,
				'sales'=>$qty,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branchid, 
		  				'type'=>'PO',

		     'invoice' => $invoice, 
 			 
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
						'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
							'description' => $description, 
'myinvoice'=>$myinvoices,
				'status' => "printed", 
			
								);
								
												
								
							$usr_result = $this->usermodel->add($data,'sales_order');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'purchaseorder','invoice',$invoice);

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product Added </div>');	
							
							redirect('user/viewnewsalesorder?randomitemidentifier='.$invoice);	
	
								

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
															//redirect('user/viewsales');	
							redirect('user/viewnewsalesorder?randomitemidentifier='.$invoice);	


																						redirect($myview);	

															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
	
	 public function addquotation()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	

		
		
	$codes = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($codes[0]));
$type = trim($this->input->post("type"));

$finaltax2=0;
		$taxable=0;
 
 //
 

$qty = trim($this->input->post("qty"));
	  $discount = trim($this->input->post("discount"));
	  $myview = trim($this->input->post("view"));  
	  $mode = trim($this->input->post("mode"));  
	  $salestype = trim($this->input->post("salestype"));  
	  //$unit = trim($this->input->post("unit"));  

  $description="";
		    
		      $invoice = trim($this->input->post("invoice")); 
							  
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);

							  //sawa
						  if ($productname ==false)
						   {
							   
							   
							   
							 		
							 $myserialname = $this->usermodel->geteproductlistbyserial($code,$branchid);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
							$qty=$myserialname[0]['qty'];
							
							  $description="";

							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$branchid);
							//$promoprice=$myserialname[0]['promoprice']; 
								
							 $buyingprice=trim($myserialname[0]['buyingprice']); 

								
								
						  $newsellingprice=trim($myserialname[0]['sellingprice']); 

	
						   }else{
												   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
	  						redirect($myview);	
	
								
						   return false;   
			
						   }  
							   
							   
							   
							   
		
						   }else{
							   
							   
	$buyingprice=$productname[0]['buyingprice']; 
	       $description=$productname[0]['description']; 
				if($salestype =="wholesale"){
      $newsellingprice=trim($productname[0]['wholesaleprice']); 

			}else{
      $newsellingprice=trim($productname[0]['sellingprice']); 


			}				
							   
						   }
						   
				
				
				
						   
						   
								if($type=="Lease"){
									
									
									
									  
   if($amount==0){
	   
	      $ttamount=(double)$qty*(double)$sellingprice;
   }else{
	   
	      $ttamount=(double)$qty*(double)$amount;
   }
   
   
   $availableqty=$productname[0]['qty'];
	 if ($availableqty<$qty) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
		<strong>Error!</strong>The available quantity ('.$availableqty.') is less than the damaged product ('.$qty.') hence the damaged product could not be saved. Try again a diffent code.</div>');
								
redirect($myview);
								 return false;
							}
						 
										  																															

									
									
									
									
									
							 
   $finalqty=((double)$availableqty-(double)$qty);
   
   	$damageddata=array(		
												'qty'=>$finalqty,
													
													);
															
									
									
									
								}
								
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						  $productid=$productname[0]['id'];  
  
		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 
	  	  		  $deliverymethod = trim($this->input->post("deliverymethod"));


			$maincapital = $this->usermodel->populateallarray('quotation','invoice',$invoice);

	    $currentamount=trim($maincapital[0]['amount']);
		
			if($mode=="PC"){
			
				$mydiscount=($newsellingprice* ($discount/100));	
				$discount= $this->formatMoney($mydiscount, true);
					
			
					
			}else  if(($mode=="TWOSTEPS")){
	
	if($discount!=0){
		$qty=(double)$qty* (double)$discount;
	
	}else{
		$qty=(double)$qty* 1;
	
	}
	$discount = 0;

}else{
			$discount=$discount;	
	
}
			
			
			
						 $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);	   
						   $tax2rate=$myconfiguration[0]["tax2rate"];

$display2=$myconfiguration[0]["display2"]; 
			
		
		
		
		
		
		
 $sellingprice=(double)$newsellingprice-(double)$discount;
 
  $finaldiscount= ((float)$discount* (float)$qty);
  //$finaldiscount= ($discount*$qty);
     $amount= ((float)$qty* (float)$sellingprice);

$finalamount=$currentamount+$amount;

					  	$taxtype=$productname[0]['taxtype']; 

   $available=trim($productname[0]['qty']); 
   $finalqty=((double)$available-(double)$qty); 
    $tax_included=(double)trim($productname[0]['tax_included']);
							 $finaltax=0;
							 
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								// $mytax=1+($tax_included/100); 
								// $vatable=($sellingprice/$mytax);
								 //$myfinaltax=(($sellingprice-$vatable)*$qty);
								
								//$finaltax= $this->formatMoney($myfinaltax, true);
								 
								 
								 
								 
									 //
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 $vatable=((double)$sellingprice  * (double)$qty);	

								  $getvatable=($sellingprice*$mytax);	
								 $finaltax=(((double)$getvatable-(double)$sellingprice)*$qty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{
	
								 $mytax=1+($tax_included/100); 
								  $vatable=(($sellingprice/$mytax) *(double)$qty );
								   $finaltax=(($sellingprice*$qty)-(double)$vatable);

									}
								 	 
								 if($display2=="yes"){

	
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$qty)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	 $taxable= $this->formatMoney($ttoltaxable, true);

			
			
			

			
			

	}else{
	 $finaltax2=0;
		$taxable= $this->formatMoney(($vatable), true);


	}
					
							 	$finaltax= $this->formatMoney($finaltax, true); 
						
							 }
							 
			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");
			
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
	  																														redirect($myview);	

		}
		 else
		{
			

					   					$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,
'taxable'=>$taxable,
'tax2'=>$finaltax2,
			'dateposted'=>$dateposted,
					 'branch'=>$branchid, 
		  								 'description'=>$description, 

	     'type' => $type,  
		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
						'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
							'unit' =>1, 

			
			
								);
											
								
							$usr_result = $this->usermodel->add($data,'purchaseorderlist');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								if($type=="Lease"){
									
						$this->usermodel->updatedatabytwo($damageddata,'productlist','code',$code,'branch',$branchid);
	$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'lease','invoice',$invoice);
									
								}else{
									
									
									 $ourtotal= $this->usermodel->geteallQUOTES_orderCounter($invoice,$deliverymethod);
	//
									$myfinalamount= round(($ourtotal[0]["amount"]));
			
									
										$amountdata=array(		
												'amount'=>$myfinalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'quotation','invoice',$invoice);
									
									
								}
								
								
								
								
								
								
								
								
								
								
								
								
								
					

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product Added </div>');	
							
	  																														redirect($myview);	
	
								

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
										
										//redirect('user/viewsales');	
	  																														redirect($myview);	



															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
 
   public function addquotation22()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	

		
		
	$codes = explode(':=',$this->input->post("code"));

 
  $code = htmlspecialchars(trim($codes[0]));
$type = trim($this->input->post("type"));


 
 //
 

$qty = trim($this->input->post("qty"));
	  $discount = trim($this->input->post("discount"));
	  $myview = trim($this->input->post("view"));  
	  $mode = trim($this->input->post("mode"));  
	  $salestype = trim($this->input->post("salestype"));  
	  //$unit = trim($this->input->post("unit"));  

  $description="";
		    
		      $invoice = trim($this->input->post("invoice")); 
							  
						 $productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branchid);

							  //sawa
						  if ($productname ==false)
						   {
							   
							   
							   
							 		
							 $myserialname = $this->usermodel->geteproductlistbyserial($code,$branchid);
  
							   
						  if ($myserialname !=false)
						   {
						  $serial=$myserialname[0]['serial']; 
						  $serialid=$myserialname[0]['id']; 
						  $code=$myserialname[0]['code']; 
							$qty=$myserialname[0]['qty'];
							
							  $description="";

							$productname = $this->usermodel->geteproductlistbyid($myserialname[0]['code'],$branchid);
							//$promoprice=$myserialname[0]['promoprice']; 
								
							 $buyingprice=trim($myserialname[0]['buyingprice']); 

								
								
						  $newsellingprice=trim($myserialname[0]['sellingprice']); 

	
						   }else{
												   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
	  						redirect($myview);	
	
								
						   return false;   
			
						   }  
							   
							   
							   
							   
		
						   }else{
							   
							   
	$buyingprice=$productname[0]['buyingprice']; 
	       $description=$productname[0]['description']; 
				if($salestype =="wholesale"){
      $newsellingprice=trim($productname[0]['wholesaleprice']); 

			}else{
      $newsellingprice=trim($productname[0]['sellingprice']); 


			}				
							   
						   }
						   
				
				
				
						   
						   
								if($type=="Lease"){
									
									
									
									  
   if($amount==0){
	   
	      $ttamount=$qty*$sellingprice;
   }else{
	   
	      $ttamount=$qty*$amount;
   }
   
   
   $availableqty=$productname[0]['qty'];
	 if ($availableqty<$qty) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
		<strong>Error!</strong>The available quantity ('.$availableqty.') is less than the damaged product ('.$qty.') hence the damaged product could not be saved. Try again a diffent code.</div>');
								
redirect($myview);
								 return false;
							}
						 
										  																															

									
									
									
									
									
							 
   $finalqty=($availableqty-$qty);
   
   	$damageddata=array(		
												'qty'=>$finalqty,
													
													);
															
									
									
									
								}
								
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						  $productid=$productname[0]['id'];  
  
		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 
	  	  		  $deliverymethod = trim($this->input->post("deliverymethod"));


			$maincapital = $this->usermodel->populateallarray('quotation','invoice',$invoice);

	    $currentamount=trim($maincapital[0]['amount']);
		
			if($mode=="PC"){
			
				$mydiscount=($newsellingprice* ($discount/100));	
				$discount= $this->formatMoney($mydiscount, true);
					
			
					
			}else  if(($mode=="TWOSTEPS")){
	
	if($discount!=0){
		$qty=$qty* $discount;
	
	}else{
		$qty=$qty* 1;
	
	}
	$discount = 0;

}else{
			$discount=$discount;	
	
}
			
			
			
			
			
		
		
		
		
		
		
		
 $sellingprice=$newsellingprice-$discount;
 
  $finaldiscount= ((float)$discount* (float)$qty);
  //$finaldiscount= ($discount*$qty);
     $amount= ((float)$qty* (float)$sellingprice);

$finalamount=$currentamount+$amount;

					  	$taxtype=$productname[0]['taxtype']; 

   $available=trim($productname[0]['qty']); 
   $finalqty=($available-$qty); 
    $tax_included=trim($productname[0]['tax_included']);
							 $finaltax=0;
							 
							 if(($tax_included=="")|| ($tax_included==0)){
								$finaltax=0; 
								 
							 }else{
								 
								// $mytax=1+($tax_included/100); 
								// $vatable=($sellingprice/$mytax);
								 //$myfinaltax=(($sellingprice-$vatable)*$qty);
								
								//$finaltax= $this->formatMoney($myfinaltax, true);
								 
								 
								 
								 
									 //
								 		if($taxtype=="Exclusive"){
								$mytax=1+($tax_included/100); 
								 $vatable=($sellingprice  * $qty);	

								  $getvatable=($sellingprice*$mytax);	
								 $finaltax=(($getvatable-$sellingprice)*$qty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{
	
								 $mytax=1+($tax_included/100); 
								  $vatable=(($sellingprice/$mytax) *$qty );
								   $finaltax=(($sellingprice*$qty)-$vatable);

									}
								 	 
								 
								 
								 
								 
								 
								 
							 }
							 
			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");
			
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
	  																														redirect($myview);	

		}
		 else
		{
			

			
					   					$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
		  	'discount'=>$finaldiscount,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branchid, 
		  								 'description'=>$description, 

	     'type' => $type,  
		     'invoice' => $invoice,  
		    'sprice' => $sellingprice, 
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
						'tax' => $finaltax,
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 
							'unit' =>1, 

			
			
								);
											
								
							$usr_result = $this->usermodel->add($data,'purchaseorderlist');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								if($type=="Lease"){
									
						$this->usermodel->updatedatabytwo($damageddata,'productlist','code',$code,'branch',$branchid);
	$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'lease','invoice',$invoice);
									
								}else{
									
									
									 $ourtotal= $this->usermodel->geteallQUOTES_orderCounter($invoice,$deliverymethod);
	//
									$myfinalamount= round(($ourtotal[0]["amount"]));
			
									
										$amountdata=array(		
												'amount'=>$myfinalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'quotation','invoice',$invoice);
									
									
								}
								
								
								
								
								
								
								
								
								
								
								
								
								
					

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product Added </div>');	
							
	  																														redirect($myview);	
	
								

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
										
										//redirect('user/viewsales');	
	  																														redirect($myview);	



															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
 
  public function addexpenses()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];


 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  	

		
 $code = htmlspecialchars(trim($this->input->post("code")));
$qty = trim($this->input->post("qty"));
	  $discount = trim($this->input->post("discount"));
	  $myview = trim($this->input->post("view"));  
	  $description = trim($this->input->post("description"));  

		  $customer = trim($this->input->post("customer"));  

  
		    
		      $invoice = trim($this->input->post("invoice")); 
						      $productname=$this->usermodel->populateallarray('products','code',$code);

						  if ($productname ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');
							
						  		
																						redirect($myview);	
	
								
							//redirect('user/viewsales');						   
						   return false;
						   }
						  $productid=$productname[0]['id'];  
  $buyingprice=$productname[0]['buyingprice']; 
      $newsellingprice=trim($productname[0]['sellingprice']); 
	  
		
	        $categoryid=trim($productname[0]['category']); 
			$maincategory = $this->usermodel->populateallarray('purchaseorderlist','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 


			$maincapital = $this->usermodel->populateallarray('quotation','invoice',$invoice);

	   
     $amount= (($qty)* ($buyingprice));
	 
	 
	 	 $productlist = $this->usermodel->populateallarray('expenses','invoice', $invoice);


			
				
		$availabletotal=$productlist[0]['amount'];
		

		//$availableqty=$productlist[0]['qty'];
		
		
		 $finalamount=$availabletotal+$amount;

			
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
																						redirect($myview);	

		}
		 else
		{
			

			
					   					$data=array(		
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$qty,
		  	
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branchid, 
		  				'type'=>'EXP',

		     'invoice' => $invoice,  
		  
			      'amount' => $amount, 
			   			      'bprice' => $buyingprice, 
					
				'maincategory' => $maincategoryid, 
							'category' => $categoryid, 

										'description' => $description, 
										'customer' => $customer, 

			
								);
								
												
								
							$usr_result = $this->usermodel->add($data,'purchaseorderlist');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'expenses','invoice',$invoice);

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New item/product Added </div>');	
							
																						redirect($myview);	
	
								

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Product/item  was not added.. Try again</div>');
										
										
										//redirect('user/viewsales');	
																						redirect($myview);	



															//redirect('user/viewsales');	
	
								
							}
					 
					 
	    }
    }
 
  public function addreceivings()
    {
		
			$session_data = $this->session->userdata('logged_in');

  
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	 		
			 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
			
			
			
			
			
			
			
			
			  $codes = explode(':=',$this->input->post("code"));

 
  $searchterm = htmlspecialchars(trim($codes[0]));
			
			
			

 $code =  $searchterm;

 $compare = trim($this->input->post("compare"));
 $sprice = trim($this->input->post("sprice"));

$qty = trim($this->input->post("qty"));
	  $invoice_number = trim($this->input->post("salesid"));
     $to = trim($this->input->post("to"));
	      $tax = $this->input->post("tax");
				      $discount = $this->input->post("discount");

$tocurrencyamount = $this->input->post("tocurrencyamount");
	  $tocurrency = $this->input->post("tocurrency");
		  $newcurrency = $this->input->post("newcurrency");  
		  $currency = $this->input->post("currency");  
		  $directprice = $this->input->post("bprice");  
		  $mode = $this->input->post("mode");  


	
		
















     $description = "receivings";
 $from = "supplier";
		    $mysupplier = $this->usermodel->getesupplierbyid($invoice_number);
		   
			if($to=="Main"){
$productname = $this->usermodel->populateallarray('products','code', $code);
 //$productname = $this->usermodel->getallproductbyid($code);

			}else{
				

				
//$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $to);
 $productname = $this->usermodel->geteproductlistbyid($code,$to);

			}
		$code=$productname[0]['code'];
			$supplier=$mysupplier[0]['supplier']; 
   	 $sellingprice=$productname[0]['sellingprice'];

						if($tax=="all"){
								$tax=$productname[0]['vattype'];
						}							
								
								
						
								
								
			
				        //$productname = $this->usermodel->geteproductbyid($code);
								$data['salesid'] = $invoice_number;
	 
	$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
						
						  if ($productname ==false)
						   {
							  
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That product code does not exist. Try again.</div>');

						  
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   return false;
						   }
						   			





  if ($qty < 0) {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not receive negative(-) stock. Try again.</div>');

						  
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   return false;
						   }






//

									 
				$name=$productname[0]['name']; 
				$category=$productname[0]['category']; 
		  	$description=$productname[0]['description']; 
					  	$shortname=$productname[0]['shortname']; 

								  	$uom=$productname[0]['uom']; 

			$item_id=$productname[0]['id'];
			
							$realqty=$productname[0]['qty']; 

if((trim($directprice) !="0")){

	if(($tocurrencyamount > 0) &&  ($newcurrency !="")){
			$buyingprice=$tocurrencyamount;

			
					}else{
	//$buyingprice=$productname[0]['buyingprice'];
					$buyingprice=$directprice;


					}
			
	
	
	
	
	
}else{
	
	$buyingprice=$productname[0]['buyingprice'];

	
}

			
					



//

			if($mode=="PC"){
			
				$mydiscount=($buyingprice* ($discount/100));	
				$discount= $this->formatMoney($mydiscount, true);
					
				
			}else{
			$discount=$discount;	
				
			}









			
			
		$buyingprice=$buyingprice - $discount;
			
			$sellingprice=$productname[0]['sellingprice']; 
				$wholesaleprice=$productname[0]['wholesaleprice']; 
				$promoprice=$productname[0]['promoprice']; 
						$retailmargin=$productname[0]['allow_alt_description']; 

			
							$status=$productname[0]['status']; 

			$tax_included=$productname[0]['tax_included']; 
			$store=$productname[0]['store']; 
		$imgid=$productname[0]['imgid']; 
			$reorderevel=$productname[0]['reorderevel']; 
			$expdate=$productname[0]['expdate']; 
						$orderamount=$productname[0]['orderamount']; 
  		   						//$sellingprice=$productname[0]['sellingprice']; 

					  	$vattype=$productname[0]['vattype']; 
$vatrate=$productname[0]['tax_included'];
		
		if($vattype=="VATABLE"){
								  $mytax=1+($vatrate/100); 
								  if($tax=="Exclusive"){
									$buyingprice= $buyingprice*$mytax;
								  }
							  
								 $vatable=($buyingprice/$mytax);
								 $myfinaltax=(($buyingprice-$vatable));
								
								 $finaltax= $this->formatMoney(($myfinaltax*$qty), true);
								$vatable= $this->formatMoney(($vatable*$qty), true);


							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
							  $vat=$finaltax;
						      $taxable=$vatable;
							  
							
							  
							  
												
			
			
			






	
if($sprice !="No") {
	
	$finalspriceraw = trim($this->input->post("finalspriceraw"));
$finalsprice=0;
	if($sprice=="Direct"){
	
	
	if (($finalspriceraw >0) && ($finalspriceraw > $buyingprice)){
		
		

 $finalsprice=(($finalspriceraw)) ;
 
	}else{
		
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not change selling price manually since the selling price is zero(0) or if the s.price is less than b.price. Kindly adjust selling price then again.</div>');

						  
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   return false;
		
		
	}
		
	}else if($sprice =="Yes") {
	
	
	

		//$retailmargin=$productname[0]['allow_alt_description']; 
	
	  if (($retailmargin < 1)) {
							   
					///$retailmargin=1;
				   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You can not change selling price automatically before you adjust the profit margin. Try adjust profit margin then again.</div>');

						  
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   return false;
						   }
	
	
	
$finalsprice1=(($buyingprice* ($retailmargin/100))+ $buyingprice);
  $finalsprice=(round($finalsprice1)) ;

	
	}else{
		 $finalsprice=(($productname[0]['sellingprice'])) ;

	}
	
	



	$sellingpricepriceDATA=array(		
						
										'sellingprice'=>$finalsprice,
									
										);
$this->usermodel->updatedata($sellingpricepriceDATA,'products','code',$code);
$this->usermodel->updatedata($sellingpricepriceDATA,'productlist','code',$code);
//

		
	
	
	
	
	
	
	
}






				if($to=="Main"){
	$myfinalqty=($realqty+$qty);
				$myproductdata=array(		
												'qty'=>$myfinalqty,
													);
					 
			$productdata=array(		
			'userid'=>$userid,
							'tax'=>$tax,
								'vat'=>$finaltax,
				'taxable'=>$vatable,
	'uomqty'=>$qty,
				'item_id'=>$code,
			'total'=>$qty,
		  	'invoice_number'=>$invoice_number,
					  	'vatrate'=>$tax_included,

					  	'invoice'=>$invoice_number,
						'name'=>$name,

						'companyid'=>$companyid,
'description'=>$description,
'type'=>$to,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  		    'sellingprice' => $sellingprice, 

		    'buyingprice' => $buyingprice, 
			     
  'stockfrom' => $from,		  
		  		    'uom' => $uom, 

		    'stockto' => $to, 
				
				'balance'=>$myfinalqty,
								'item_id1'=>$realqty,

			
			
								);
								
								
										$myproductusr_result=$this->usermodel->updateproduct($myproductdata,$code); 

				
		

			
							
							//check if username and password is correct
							if ($myproductusr_result ==TRUE) //active user record is present
							{
									$this->usermodel->add($productdata,'newstock');


if($compare !="No") {
	 							$mybuyingprice=$productname[0]['buyingprice'];

						if($compare=="Yes") {
						$availableqty=$productname[0]['qty']; 
						$latest=$qty;
	
					$myfinalybuyingprice=($mybuyingprice+$buyingprice)/2;
					
					
				$firtst=($mybuyingprice*$availableqty);

$second=($buyingprice*$latest);
					$averageprice=($firtst+$second)/($availableqty+$latest);	
					
					
					
					
					
					
					$finalybuyingprice= $this->MyformatMoney($averageprice, true);

						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
						
					


					
						
			if($buyingprice!=$mybuyingprice){
				
		
			$buyingpriceDATA=array(		
						
										'buyingprice'=>$finalybuyingprice,
									
										);
$this->usermodel->updatedata($buyingpriceDATA,'products','code',$code);
	
	
	$confirmuomproducts = $this->usermodel->populatealldataarray('uomproducts','uom', $code,'companyid', $companyid);


if($confirmuomproducts !=false){
	
	$uomfinalprice=($finalybuyingprice * $confirmuomproducts[0]['qty']);

	$buyingpriceDATAUOM=array(		
						
										'brice'=>$uomfinalprice,
									
										);


		$this->usermodel->updatedatabytwo($buyingpriceDATAUOM,'uomproducts','uom',$code,'companyid',$companyid);

}
	
			if($to=="Main"){
		 $this->usermodel->updatedatabytwo($buyingpriceDATA,'productlist','code',$code,'branch',$branchid);
			}else{
				 $this->usermodel->updatedatabytwo($buyingpriceDATA,'productlist','code',$code,'branch',$to);

			}

							// $this->usermodel->updateproductlist($buyingpriceDATA,$mycode,$branch); 

	
		}				
						
			



	






			
	
	
	}

	
	











						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Receiving Added </div>');	
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Receiving  was not added.. Try again</div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							}

				}





						 $productlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $to);

						     if ($productlist ==false)
						   {
							   
							   								$newproductlist=array(		
	'userid'=>$userid,
			'code'=>$code,
				'name'=>$name,
				'category'=>$category,
		  	'description'=>$description,
					  	'shortname'=>$shortname,

			'status'=>$status,
			
			'dateposted'=>$dateposted,
				
			 'companyid'=>$companyid,
			'supplier'=>$supplier,
			'buyingprice'=>$buyingprice,
			'sellingprice'=>$sellingprice,
				'wholesaleprice'=>$wholesaleprice,
				'promoprice'=>$promoprice,
								'branch'=>$to,
		  		    'uom' => $uom, 

			'qty'=>$qty,
			
				    'buyingprice' => $buyingprice, 

			'tax_included'=>$tax_included,
			'store'=>$store,
		'imgid'=>$imgid,
			'reorderevel'=>$reorderevel,
			'expdate'=>$expdate,
						'orderamount'=>$orderamount,

								);
							   
							   
							   
							   
							   
							   
							   
							   
			$myusr_result = $this->usermodel->add($newproductlist,'productlist');

							   if ($myusr_result ==TRUE) //active user record is present
							{
								
		$mydata=array(		
			'userid'=>$userid,
										'tax'=>$tax,
					  	'vatrate'=>$tax_included,

				'item_id'=>$code,
			'total'=>$qty,
		  	'invoice_number'=>$invoice_number,
			'stockfrom' => $from,	
						'companyid'=>$companyid,
'description'=>$description,
'type'=>$to,
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  
		    'buyingprice' => $buyingprice, 
				  
		  'name'=>$name,
		    'stockto' => $to, 
			'sellingprice'=>$sellingprice,

						  		    'uom' => $uom, 

				'balance'=>$myfinalqty,
								'item_id1'=>$realqty,
	'vat'=>$finaltax,
				'taxable'=>$vatable,
			
			
								);
								$usr_result = $this->usermodel->add($mydata,'newstock');
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Receiving Added </div>');	
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);	
						return false;							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Receiving  was not added.. Try again</div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);	
							return false;							
							}
							   
							
						  
						
						   }
						   
						   
				
						 $realproductlist = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $to);

  
						   		  $available=$realproductlist[0]['qty']; 
						$finalqty=($available+$qty); 
						   
						   
			
				
			  		  $this->form_validation->set_rules("code", "Product code", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewreceiving ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
	
					   //validation succeeds
					 	if ($this->input->post('btn_addsale') == "sale")
					   {
				
						   
						   
												$data=array(		
			'userid'=>$userid,
													'tax'=>$tax,
					  	'vatrate'=>$tax_included,

				'item_id'=>$code,
			'total'=>$qty,
				'uomqty'=>$qty,
		  	'invoice_number'=>$invoice_number,
				     'stockfrom' => $from,
						'companyid'=>$companyid,
'description'=>$to,
'type'=>$to,
    'stockto' => $to, 
			'date'=>$dateposted,
			'supplier' => $supplier,		  
		  		
 'name'=>$name,
		    'buyingprice' => $buyingprice, 
			     
			'sellingprice'=>$sellingprice,

					'balance'=>$finalqty,
								'item_id1'=>$realqty,

					  		    'uom' => $uom, 
	'vat'=>$finaltax,
				'taxable'=>$vatable,
			
			
								);
								
								
												$productdata=array(		
												'qty'=>$finalqty,
													);
								
								
						
				
				
		
							$usr_result = $this->usermodel->add($data,'newstock');

			
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
if($compare !="No") {
	 							$mybuyingprice=$productname[0]['buyingprice'];

						if($compare=="Yes") {
						$availableqty=$productname[0]['qty']; 
						$latest=$qty;
	
					$myfinalybuyingprice=($mybuyingprice+$buyingprice)/2;
					

					
					
					
										
				$firtst=($mybuyingprice*$availableqty);

$second=($buyingprice*$latest);
					$averageprice=($firtst+$second)/($availableqty+$latest);	
					
					
					
					
					
					$finalybuyingprice= $this->MyformatMoney($averageprice, true);

						}else{
							$finalybuyingprice=$buyingprice;
							//$finalybuyingprice= $this->formatMoney($myfinalybuyingprice, true);

						}
						
						
						
			if($buyingprice!=$mybuyingprice){
			$buyingpriceDATA=array(		
						
										'buyingprice'=>$finalybuyingprice,
									
										);
$this->usermodel->updatedata($buyingpriceDATA,'products','code',$code);
	
	
	
		$confirmuomproducts = $this->usermodel->populatealldataarray('uomproducts','uom', $code,'companyid', $companyid);
if($confirmuomproducts !=false){
	
	$uomfinalprice=($finalybuyingprice*$confirmuomproducts[0]['qty']);

	$buyingpriceDATAUOM=array(		
						
										'brice'=>$uomfinalprice,
									
										);


		$this->usermodel->updatedatabytwo($buyingpriceDATAUOM,'uomproducts','uom',$code,'companyid',$companyid);

}

	
	
	
	
	
	
	
	
			if($to=="Main"){
		 $this->usermodel->updatedatabytwo($buyingpriceDATA,'productlist','code',$code,'branch',$branchid);
			}else{
				 $this->usermodel->updatedatabytwo($buyingpriceDATA,'productlist','code',$code,'branch',$to);

			}

							// $this->usermodel->updateproductlist($buyingpriceDATA,$mycode,$branch); 

	
		}				
						
						
	
	
	}

								
								
									  $confirmmotherchild = $this->usermodel->populatealldatanoarraythree('uomproducts','branch', $branchid,'code',$code,'status','child');



if(is_array($confirmmotherchild)){

   foreach($confirmmotherchild as $confirmmotherchildrow)
   {
    $chidqty=$confirmmotherchildrow->qty; 
 $childfinalprices=($finalybuyingprice / $chidqty);


$childfinalprice= $this->MyformatMoney($childfinalprices, true);


						$buyingpriceDATACHILDBRANCH=array(		
						
										'buyingprice'=>$childfinalprice,
									
										);

						$buyingpriceDATACHILD=array(		
						
										'brice'=>$childfinalprice,
									
										);
$this->usermodel->updatedata($buyingpriceDATACHILD,'uomproducts','id',$confirmmotherchildrow->id);
	
	
	if($to=="Main"){
		 $this->usermodel->updatedatabytwo($buyingpriceDATACHILDBRANCH,'products','code',$confirmmotherchildrow->uom);
			}else{
				 $this->usermodel->updatedatabytwo($buyingpriceDATACHILDBRANCH,'productlist','code',$confirmmotherchildrow->uom,'branch',$confirmmotherchildrow->branch);

			}




   }
}



		  $confirmmotherchild2 = $this->usermodel->populatealldatanoarraythree('uomproducts','branch', $branchid,'code',$code,'status','active');



if(is_array($confirmmotherchild2)){

   foreach($confirmmotherchild2 as $confirmmotherchildrow2)
   {
    $chidqty2=$confirmmotherchildrow2->qty; 
 $childfinalprices2=($finalybuyingprice * $chidqty2);


$childfinalprice2= $this->MyformatMoney($childfinalprices2, true);


						$buyingpriceDATACHILDBRANCH2=array(		
						
										'buyingprice'=>$childfinalprice2,
									
										);

						$buyingpriceDATACHILD2=array(		
						
										'brice'=>$childfinalprice2,
									
										);
$this->usermodel->updatedata($buyingpriceDATACHILD2,'uomproducts','id',$confirmmotherchildrow2->id);
	
	
	if($to=="Main"){
		 $this->usermodel->updatedatabytwo($buyingpriceDATACHILDBRANCH2,'products','code',$confirmmotherchildrow2->uom);
			}else{
				 $this->usermodel->updatedatabytwo($buyingpriceDATACHILDBRANCH2,'productlist','code',$confirmmotherchildrow2->uom,'branch',$confirmmotherchildrow2->branch);

			}




   }
}












					
								
								
							 $this->usermodel->updateproductlist($productdata,$code,$to); 

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	Receiving Added </div>');	
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Receiving  was not added.. Try again</div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 function OURformatMoney($number, $fractional=false) {
						if ($fractional) {
							$number = sprintf('%.2f', $number);
						}
						while (true) {
							$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
							if ($replaced != $number) {
								$number = $replaced;
							} else {
								break;
							}
						}
						
						return $number;
					}
 
 
 
 
 
  public static function generateIntrlData($tin, $rcptPbctDt)
    {
        return self::generateUniqueString($tin . $rcptPbctDt . "PIN", 26);
    }

    public static function generateRcptSign($tin, $rcptPbctDt)
    {
        return self::generateUniqueString($tin . $rcptPbctDt . "RCPDATE", 16);
    }

    private static function generateUniqueString($input, $length)
    {
        $hash = hash("sha256", $input, true);
        $base64Encoded = rtrim(strtr(base64_encode($hash), '+/', '-_'), '=');

        if (strlen($base64Encoded) > $length) {
            return substr($base64Encoded, 0, $length);
        } else {
            return str_pad($base64Encoded, $length, '0');
        }
    }



 
 public function savesales()
    {
		//
			$session_data = $this->session->userdata('logged_in');
//
//dateposted(
//
    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		 $currenttime = date('H:i:s');
 		$dateposted2 =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		//
		
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 	  	  $mydateposted = $this->input->post("dateposted");	
			    $myfrotime = $this->input->post("frotime");	
			  	   $dateposted=$mydateposted." ".$myfrotime;
			    $receiptno = $this->input->post("receiptno");	
			    $mymemberid = $this->input->post("memberid");
if(	$mymemberid !=""){
$userid = $mymemberid;
}	
	$myinvoices =  $userid.time().$this->createRandomPasswordForsales();

	 	  	  $etimsdata = $this->input->post("etims");		
			 

	 	  	  $change = $this->input->post("change");		  
			  	 	  	  $mydiscountedtotal = $this->input->post("discountedtotal");		  



//$this->saveItemComposition("AC2BAAV0000026","2","KE1BCAV0000027");



  $backdateddateposted = date("Y-m-d", strtotime($mydateposted));

		


//


	 	  	  $myreceipt ="";		  
$this->load->dbutil();
	$this->db->cache_on(); 
	    $accountlimit=$this->usermodel->populatuserpermissionsdataarray('sales','accountlimit',$userid);
		
		$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		  		  	      $backdatesales=$this->usermodel->populatuserpermissionsdataarray('sales','backdatesales',$userid);
 		  		  	      $negativesales=$this->usermodel->populatuserpermissionsdataarray('sales','negativesales',$userid);
 $kitchen=$smsconfig[0]['kitchen'];	
 //
  //$kitchenid=$smsconfig[0]['kitchenid'];	
		 	  $receiptview=$smsconfig[0]['receipt'];	

						  $myreceipt=$smsconfig[0]['receipt'];	
 $activatebank=$smsconfig[0]['bankcode'];
 			$etims=$smsconfig[0]["hscode"];
			 			$etimsonline=$smsconfig[0]["etimsonline"];

		

 $customerpin ="";
  $customername ="";

 $customerpinphone="";
		
		 if($accountlimit==true){
		$mylimitamount=0;
		 	$limitamount = $this->usermodel->populateallarray('people','id', $userid);
	if($limitamount!=FALSE){
	$mylimitamount=$limitamount[0]['code'];
	}else{
	$mylimitamount=0;

	}
		 
				
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];

		  	

		




		 
		 

		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
								 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
		 }



		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
	


	 $branchname = $data['branchid'];
	 $maincategory="all";

		$totalsales = $this->usermodel->displayallsalesbyamountlimit('sales','userid',$userid,$finalstartdate, $finalendate,$branchname,$maincategory,$companyid);










if( $totalsales >  $mylimitamount){
		 		  $myview = $this->input->post("myview");



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You have reached your sales limit of ('.$this->OURformatMoney($mylimitamount, true).'). Kindly Request administrator to increase your daily sales limit to continue. Try again</div>');
								
		redirect($myview);
			return false;
			
			
				 }
		 
				}		 
			
	
	
			
	 	$finalamount	=0;
								$mpesaresult	=""	;					
		 $coins =count((array)$this->input->post("coins"));
		 $sendmysms = trim($this->input->post("sendsms"));
	 if($sendmysms==""){
			 $sendmysms=0;
			 
		 }else{
			 
			  $sendmysms=$sendmysms;
		 }
		 	
		
		

			//
			
			
			
			
			
		 $next = $this->input->post("next");
		 			 $nextcounter =count((array)$next);
				
$creditnote=$this->input->post("creditnote");
			  	 	  	 $salesperson = $this->input->post("salesperson");	
						 //$salesperson = $this->input->post("customer");	
//uruani
			  	 	  	  $delivery = $this->input->post("delivery");	
			  	 	  	  //$currency = $this->input->post("currency");	

			  	 	  	  $tocurrencyamount = $this->input->post("tocurrencyamount");	
			  	 	  	  $tocurrency = $this->input->post("tocurrency");
						  $currency=$tocurrency ;
						$basecurrency = $this->input->post("basecurrency");			


				  $ourcompany = $this->input->post("ourcompany");
				  $saving = $this->input->post("saving");

		  $redeem = $this->input->post("redeem");

		  $salestype = $this->input->post("salestype");
		  		  $name = $this->input->post("name");

 	 		 $accountno = $this->input->post("accountno");
//
 	 		 $due = $this->input->post("due");

 	 		 $advance = $this->input->post("advance");

//$mycustomer = $this->input->post("customer");


 $customerraw = explode(':=',$this->input->post("customer"));

 
  $mycustomer = htmlspecialchars(trim($customerraw[0]));




$memberid = $this->input->post("memberid");
  $type = $this->input->post("type");
   $deliverytype = $this->input->post("type");
   $cardnumber = $this->input->post("cardnumber");
      $idno = $this->input->post("idno");
//
	$phone = $this->input->post("phone"); 
	$customerid="";
		 $myview = $this->input->post("myview");

	  			  		  $this->form_validation->set_rules("phone", "Phone", "trim");


 $feedback=$smsconfig[0]['feedback'];

		 		  	 $sendfeedback=$smsconfig[0]['sendfeedback'];
			$pointsdisplay=$smsconfig[0]['display'];


$nextfinalbalance=0;



if($mycustomer!=""){
	
	$customerid=$mycustomer;	
}
//

	  $cash = $this->input->post("cash");
	  $total = $this->input->post("total");		  
	  $discountedtotal = $this->input->post("discountedtotal");	
		    	  $maindiscount = $this->input->post("maindiscount");	

		      $invoice = trim($this->input->post("invoice")); 
			  		      $description = $this->input->post("description"); 
			  		     $mytable = $this->input->post("mytable"); 
							$description1 = $this->input->post("mydescription1");
			  		     $mytable2 = $this->input->post("mytable2"); 
if($mytable ==""){
	
	$mytable=$mytable2;
	
}
						
			  		      $station = $this->input->post("station"); 
			  		      $destination = $this->input->post("destination"); 
//
									  $mpesa = $this->input->post("mpesa");		  
	  	        $cheque = $this->input->post("cheque");		  
	            $card = $this->input->post("card");	
		    	$voucher = $this->input->post("voucher");	

		      $credit = $this->input->post("credit"); 
			  		      $points = $this->input->post("points"); 
						  			  		      $rooms = $this->input->post("rooms"); 

						  
						  

						  			  		      $mycash = $this->input->post("cash"); 
//$mysoldqty = $this->input->post("soldqty"); 

			 
						$savedcoins=0;
						$savedpoints=0;
					
							$totalpoints=0;
$totalcoins=0;
						
				


	

 if(trim($backdateddateposted) > trim($postedtime)){
		 		  $myview = $this->input->post("myview");



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> You can not back date sales to future date ('.$backdateddateposted.').. You can only select current / previous date ! Try again</div>');
								
		redirect($myview);
			return false;
			
			
				 }

if($negativesales!=true){
if(($total<= 0)||($total=="")){
		 		 



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You have not sold item.Kindly sell atleast one product to proceed. Try again</div>');
								
		redirect($myview);
			return false;
			
		 }
}


	
										$invoicename = $this->usermodel->getinvoice('sales','invoice', $invoice);
										//




if ($this->input->post('btn_savesales') == "hold")
					   {
						   
						   
						   
						
				  if ($invoicename !=false)
						   {
							  						   
				 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You could not hold the sales because it had completed before. Try again</div>');
								
		redirect($myview);
			return false;
									

	   
						   }   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
	
	   
						   
						   
						   
						   
						   
						   
						   
						   
						
						
						
												$dataHOLD=array(
			
			'userid'=>$userid,
						///'cardnumber'=>$customerpin,
		 'savedcoins'=>$savedcoins,
								'savedpoints'=>$savedpoints,
				
			//'ordersales'=>"hold",
		  	'cash'=>$cash,
					  	'salestype'=>$salestype,
			   			   'cashier' => $accountno, 
'branch'=>$branchid,
			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
			'total' => $total,		  
		  'type' => $type,    
		     'invoice' => $invoice,  
			 	   'customer' => $name, 
			 
		     //'balance' => $finalbalance, 
			 		    // 'balance' => -($discountedtotal), 

			   'due_date' => $due, 
					   'maindiscount' => $maindiscount,   
							'name' => $name,  					   
		     'discountedtotal' => $discountedtotal, 

					 // 'ordersales' =>"hold" , 
			  'description' => $description,    
		  'mytable' => $mytable,
//		  balance
					   'paymentstatus' => "No",   

			  'mpesa' => $mpesa,    
		     'cheque' => $cheque, 
			 		     'creditnote' => $creditnote,  
			 			     'salesperson' => $salesperson, 
				 			     'currency' => $basecurrency, 
								 'othercurrency' => $currency,
								 'othercurrencyamount' => $tocurrencyamount,
	
		     'card' => $card, 
			   'voucher' => $voucher, 
			   'credit' => $credit, 
					   'points' => $points,   
						 'receiptno' => $receiptno,   
	
								);

						
						
							   
							   
							$usr_resultHOLD = $this->usermodel->add($dataHOLD,'sales_holding');

						   
						   
							if ($usr_resultHOLD ==TRUE) //active user record is present
							{
							
							
						
							
						   
						   
						
				
			$sales_orderkitchen = array();
	$solditems= $this->usermodel->geteallsales_order($invoice);
			//$solditems= $this->usermodel->geteallsales_orderoriginal($invoice);

			$ttbrice=0;
$totTaxblAmt=0;
$totTaxAmt=0;
$ttitemqty=0;
		$taxblAmtA=0;
            $taxblAmtB=0;
            $taxblAmtC=0;
            $taxblAmtD=0;
            $taxblAmtE=0;
			
			$taxAmtA =0;
			$taxAmtB=0;
            $taxAmtC=0;
            $taxAmtD=0;
            $taxAmtE =0;

			//$mydebitcred= $this->usermodel->searchaaccountingsalesrow($invoice,$companyid);
					$sales_orderkitchen = array();

		$costofgoodsold="";		
	if(is_array($solditems)){
	$insertdata = array();
	$insertinventorydata = array();

			   	$enabled="";

	$updateArray = array();	
	$salesaccount="";
								$sales_orderdata = array();


	$inventoryaccount="";
	   foreach($solditems as $row)
	   {
		   
		   $mystatus=$row->status;
		   if($mystatus !="returned"){
	   $transactionid=$row->id; $itemid=$row->code;$totalqty=$row->qty;$mybranch=$row->branch;$mytotal=$row->amount;
		  $producttype=$row->producttype;
		

			 $mybprice=$row->bprice;
			  $correctqty=$row->qty;
			  $finalbprice=($mybprice*$correctqty);
			 
		$salesaccount=$row->salesaccount;
		  $costofgoodsold=$row->expenseaccount;
		   $inventoryaccount=$row->assetaccount;
	 if($salesaccount!=""){ $salesaccount=$row->salesaccount;}else{ $salesaccount=4000; }
	  if($costofgoodsold!=""){ $costofgoodsold=$row->expenseaccount;}else{ $costofgoodsold=5500; }
	 if($inventoryaccount!=""){ $inventoryaccount=$row->assetaccount;}else{ $inventoryaccount=1110; }

	 if($type=="Creditnote"){
		 
		 $Creditnotetotal=0;
	if($mytotal<0){
			$Creditnotetotal=(-1*$mytotal);

	}else{
			$Creditnotetotal=$mytotal;

	}
				 $insertdata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$salesaccount,'debit'=>$Creditnotetotal,'description'=>"Good returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid,'type'=> 'creditnote' ,'supplier'=> $customerid);
		
				}else{
					 $insertdata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$mytotal,'description'=>"Good sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid,'type'=> 'sales' ,'supplier'=> $customerid);
	
				}
		if(($producttype!="Service") && ($mybprice!="")){
			
			$ttbrice=$ttbrice+ $finalbprice;
				if($type=="Creditnote"){
					
					
						 $Creditnotetotal=0;
	if($finalbprice<0){
			$Creditnotetotal=(-1*$finalbprice);

	}else{
			$Creditnotetotal=$finalbprice;

	}
					 $insertinventorydata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$Creditnotetotal,'description'=>"Inventory returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'creditnote' ,'supplier'=> $customerid);

				}else{
								 $insertinventorydata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$finalbprice,'description'=>"Inventory sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'sales' ,'supplier'=> $customerid);
	
				}
			

		}

		
	   }
	   
	   

	   
	      $myid=trim($row->id);
				
				
				
						$assetaccount=$row->assetaccount;
		$salesaccount=$row->salesaccount;
		$expenseaccount=$row->expenseaccount;
				$taxcode=$row->taxcode;

			$producttype=$row->producttype;	
			$mode=$row->mode;	
			$mytaxcode=$row->taxcode;	

				if($mytaxcode=="A"){
						$taxblAmtA=$taxblAmtA+$row->amount;
						$taxAmtA=$taxAmtA+$row->tax;
					}
						
					if($mytaxcode=="B"){
					$taxblAmtB=$taxblAmtB+$row->taxable;
					$taxAmtB=$taxAmtB+$row->tax;
					}	
					if($mytaxcode=="C"){
					$taxblAmtC=$taxblAmtC+$row->amount;
					$taxAmtC=$taxAmtC+$row->tax;					
					}	
					if($mytaxcode=="D"){
					$taxblAmtD=$taxblAmtD+$row->amount;
					$taxAmtD=$taxAmtD+$row->tax;
					}	
					if($mytaxcode=="E"){
					$taxblAmtE=$taxblAmtE+$row->taxable;
					$taxAmtE=$taxAmtE+$row->tax;					
					}
			
				
				
				
		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$mytype=$row->type;
	 $myqty=$row->qty;

	//$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;
		/*	
$productname = $this->usermodel->populatealldataarray('productlist','code', $row->code,'branch', $row->branch);

     $myid=$productname[0]['id']; 

   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$myqty);
   									
							

 $producttype=$productname[0]['orderamount']; 
if($producttype !="Service"){
	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$finalqty,
);	

//$this->usermodel->deletedata($row->myinvoice,"invoice","newstock");
	// $this->usermodel->updatedata($productdata,'advance','id',$advanceid);

}
			
	*/		
			
			


	$sales_orderdata[]=array(
		
				'code'=>$code,
				'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
			'mode'=>$mode,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
			 'taxcode' => $taxcode,
			'userid'=>$userid,
				//
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						//'companyid'=>$companyid,
		//	$dateposted=$row->dateposted,
'customer'=>$row->customer,
		'dateposted'=>$row->dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => "Hold", 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
								
	   
	   //
		}

		$usr_result =$this->db->insert_batch('sales_orderholding', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
			//$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');

		
			$this->usermodel->deletedata($invoice,"invoice","sales_orderraw");
	
			
		}	
				
				
		
			    $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!  </strong>Sales data has been held Successfully </div>');
										
								
	if($nextcounter==0){
									redirect("user/viewsales");

								  return false;
		
		}else{
		  redirect("user/printholdreceipt?invoice=". $invoice."");	

								  return false;			
		}
			
				
				
				
				
				
				
				
				


	
					
		
		///
		
		
	}
	}else{


 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You could not hold the sales. Try again</div>');
								
		redirect($myview);
			return false;


	}		
		
		
		
		
		
		
		
		
		
		
		
						  
						   
						   
					   }











				
	  if ($etims=="EnableEtims"){
	$myconfiguration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
	
	
$mykra_pin=trim($myconfiguration[0]["tin"]);	   
$mybranch_id=trim($myconfiguration[0]["bhfid"]);
$mysign_key=trim($myconfiguration[0]["cmcKey"]);
$mymrcNo=trim($myconfiguration[0]["mrcNo"]);
$myetimsurl=trim($myconfiguration[0]["url"]);
$myonlineoffline=trim($myconfiguration[0]["onlineoffline"]);
			  }





if( $change < 0 ){
		 		 



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
 <strong>Warning!</strong> SALES NOT COMPLETED!! Your balance/change ('.$change .') can not be less than expected amount. Try again</div>');
								
		redirect($myview);
			return false;
			
		 }

if( $negativesales !=true){
if( $mydiscountedtotal <= 0){
		 		 



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> SALES NOT COMPLETED!! You can not sale items with less than zero selling price. Try again</div>');
								
		redirect($myview);
			return false;
			
		 }

}


	  if($cardnumber !=""){
		


	 $allmebers = $this->usermodel->populatealldataarray('people','address_1', $cardnumber,'companyid', $companyid);

	  $customerpin=$allmebers[0]["idnumber"];
				  $customerpinphone=$allmebers[0]["phone"];
				  $customername="";
				  
				  if($allmebers[0]["company"] !=""){
					  				  $customername=$allmebers[0]["company"];

					  
				  }else{
					  				  $customername=$allmebers[0]["firstname"];

					  
				  }

							 $customerid=$allmebers[0]['id'];
								$customer=$allmebers[0]['id'];
								$mycustomer=$allmebers[0]['id'];

	  }



	  if(($mycustomer!="")  && ($cardnumber =="")){
		  
	
		  

	 $allmebers = $this->usermodel->populatealldataarray('people','id', $mycustomer,'companyid', $companyid);

	  $customerpin=$allmebers[0]["idnumber"];
				  $customerpinphone=$allmebers[0]["phone"];
				  $customername="";
				  
				  if($allmebers[0]["company"] !=""){
					  				  $customername=$allmebers[0]["company"];

					  
				  }else{
					  				  $customername=$allmebers[0]["firstname"];

					  
				  }

							$customerid=$allmebers[0]['id'];
							
							

	  } else if(($phone!="") &&  ($name!="")){
	 
	 $allmebers = $this->usermodel->populatealldataarray('people','phone', $phone,'companyid', $companyid);
	
	
				  $customerpin=$allmebers[0]["idnumber"];
				  $customerpinphone=$allmebers[0]["phone"];
				  $customername="";
				  
				  if($allmebers[0]["company"] !=""){
					  				  $customername=$allmebers[0]["company"];

					  
				  }else{
					  				  $customername=$allmebers[0]["firstname"];

					  
				  }




	
	
	

	
		
			  if ($allmebers!=false)
						   {
						$customerid=$allmebers[0]['id'];
				
						   }else{

							  				$peopledata=array(		
			'userid'=>$userid,
			
				'firstname'=>$name,
							'company'=>$ourcompany,

								  'companyid' => $companyid, 
								  'idnumber' => $idno, 

			
			'createdate'=>$dateposted,
			'phone' => $phone,		  
		  'address_1' => $cardnumber,    
		 
				  'category' => "member", 
							  'entrydate' => $dateposted, 

			
			
								);
						//	$myusr_result = $this->usermodel->add($peopledata,'people');
				  if ($this->usermodel->add($peopledata,'people'))
						   {
								 $myallmebers = $this->usermodel->populatealldataarray('people','phone', $phone,'companyid', $companyid);
							$customerid=$myallmebers[0]['id'];
						   }

						   } 
			
	 

	 }else{
	
		 
								$customerid=$mycustomer;
 
	 }
 
	 

 if($deliverytype=="Delivery"){
	 $type="Credit";
 }

	
	
	
	
	
	 



if((trim($credit) >0) && (trim($type)!="Invoice") ) {
		 		  



 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
	 <strong>Warning!</strong> SALES NOT COMPLETED!! You must select Credit/ Invoice so long as there is some amount on credit field..... Try again</div>');
			//oukooo				
	redirect($myview);
		return false;
			
		
		 
				}		
	
	
	
	
	
	
	if($customerpinphone==""){
		
	$customerpinphone=$phone;	
	}
	
	
	

		 $ourtotal= $this->usermodel->geteallsales_orderCounter($invoice);
//

if($total<>sprintf("%.0f",($ourtotal[0]["amount"]))){
		   
			 
		 $totalkatestnow= round($ourtotal[0]["amount"], 0);
		
			
			if($totalkatestnow!=$total){
			  $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
				<strong>Error!..Try  printing again.You did not finish posting all the itmes before printing..!</strong> </div>');
				
				 redirect($myview);
				false;
				
			}else{
			$total= $totalkatestnow;
			}
}
	///manyalaaa
			

	 			if((trim($customerpin)=="") &&(trim($idno)!=""))  {
									$customerpin=$idno;	
		
											}

	


	 $finalsmstocustomer="Dear ".$name.", " .$feedback." Details are: Code: ".$accountno." Amount:Ksh. ".$total." Destination:".$destination;


if($mycustomer=="directly"){
$mycustomer="";
}

if($mycustomer!=""){
$customer=$mycustomer;
} else if($memberid!=""){
$customer=$memberid;
}else if($customerid!=""){
$customer=$customerid;
}else{
$customer=$mycustomer.$memberid.$customerid;
	
}

												  
																  
			 if(($deliverytype=="Delivery") && ($customer !="") &&  ($phone!="")  && ($sendfeedback=="yes")){	
			
										 $this->addallpushedsms($finalsmstocustomer,$phone,$myview);

			 }

		 
		 
		 
		 
		 
		 
												  
								 if($backdatesales==true){
			  if(trim($backdateddateposted)!=trim($postedtime)){

			 				$checksales  = $this->usermodel->populatealldatanoarray('sales_orderraw','invoice', $invoice,'companyid', $companyid);

//$checksales=false;
if(is_array($checksales)){

   foreach($checksales as $row)
   {
   $transactionid=$row->id; 
$updateArray[] =array(	
	'id'=>$transactionid,													
'dateposted'=>$dateposted,
'date'=>$dateposted,

);	

			
	}
$RESULT =	$this->db->update_batch('sales_orderraw',$updateArray, 'id');
							
		

	
}

			  }
	}						  
																  
																  
																  

						   if($deliverytype=="Delivery"){

						 //  if(($name=="")||($phone=="")||($name=="")||($station=="")||($destination=="") ||($accountno=="") ){

						   if($destination ==""){  
						   $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not Completed.Kindly make sure you fill all the delivery details first then try again</div>');
								
								 redirect($myview);
								 return false;
								 
									}
						}

						  
						 
						 
						 if($phone!=""){$myphone=" </BR>" .$phone;}else{
							$myphone=$phone; 
								}
						 if($station!=""){$mystation=" </BR>" .$station;}else{
							$mystation=$station; 
								}
								if($destination!=""){$mydestination=" </BR>" .$destination;}else{
							$mydestination=$destination; 
								}
								if($description!=""){$ourdescription=" </BR>" .$description;}else{
							$ourdescription=$description; 
								}
						 
						 
						 if($description1!=""){$mydescription1=" </BR>" .$description1;}else{
							$mydescription1=$description1; 
								}
						  
					 $mydescription = $name.  " " .$myphone. " " .$mystation. " " .$mydestination . " " .$ourdescription. " " .$mydescription1; 

						 
						 


			  
			   $updatedby="";
			
						   $updatedat="";
			  	   $finaluserid="";
				   
			  

$paymentstatus="";
$mpesaid="";
$mpesastatus="";
$customerbalances="";

			    $maincategory="";
				
				$houseno="";
				$plotno="";
		
		
	
			$finallimit=0;
			
			
			
				if((trim($customerid) !="")&&(trim($type)=="Cash")){
				
					 //$this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						// <strong>Error!</strong> You have not selected invoice mode since there is customer selected. Please select invoice first then try again.</div>');
							//uruani	
							// redirect($myview);
						// return false;	
			}
		
			
			//if (($type=="Mpesa")|| ($type=="Card")||($type=="Bank")){
			
			if ( ($type=="Card")||($type=="Bank")||($type=="Mpesa")){




		
			if($accountno==""){
				
					 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have not Entered  Transaction code to finish the sale. Please Enter the Transaction code then try again.</div>');
								
								 redirect($myview);
								 return false;	
			}

			
			}
			
			
			
			
		
			
	
			
		if(($type=="Credit")|| ($type=="Invoice") || ($type=="Delivery") || ($type=="Creditnote")||($type=="Advance")){
			
			
		
			if($customer==""){
				
					 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have not selected the customer. Please select the customer first then try again.</div>');
								
								 redirect($myview);
								 return false;	
			}
			
			
			
			
		
			
			$ourpeople = $this->usermodel->populateallarray('people','id',$customerid);
				 $customerlimit=$ourpeople[0]["customerlimit"];
			 $limitamount=$ourpeople[0]["limitamount"];
		
			
					  $customerbalances=$ourpeople[0]["balance"];
					
					 //					


	
									if($customerlimit=="yes"){
										
			
				
			
				 $finallimit=$customerbalances+$credit ;
				
				
			
								if($finallimit>$limitamount){
								
									 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have reached your credit limit of ('.$limitamount.' ). Pay first to buy more more then try again</div>');
								
								 redirect($myview);
								 return false;	
										
										}
									}
							
									
								}
		
	
		
		
		
		
		
		
		
	
		
		
		
		
		
		
				
				
		
				
			 		$mycategory = $this->usermodel->populatesalescategoryraw($invoice);

			  		 $maincategory=$mycategory[0]['maincategory'];
				
					$paidamount=0;
			
					if($accountno==""){
						$paymentstatus="No";
						$mpesastatus="1";
					}else{
						
						
						
						
										$mpesaresult = $this->usermodel->populateallarray('sms_in','code', $accountno);
	if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
					$paidamount=$mpesaresult[0]['amount'];

					$paymentstatus="Cleared";
						$mpesastatus="1";

					
		}else{
			$paymentstatus="Cleared";
			
			$mpesastatus="0";
													$paidamount=0;

		}
		
				
//
				
					}
	
		/*		
  if($cash >= $total){
	  $cash= $total;
  }else{
  $cash= $cash;
  
  }
*/	

			
			  
  if($cash >= $total){
	  $cash= $total;
	  
	  
	  
	   if($mpesa > 0){
		    $cash= $total-$mpesa;
	   }else{
		 $cash= $total;   
	   }
	   
	   
  }else{
	  
	     if($mpesa > 0){
		    $cash= $total-$mpesa;
	   }else{
		  $cash= $cash;
	   }
  //echo "    no";		  
  }	
			
		//$card+$creditnote+$maindiscount;
	if($negativesales !=true){
if(($mpesa > $total )||( $voucher > $total )||( $cheque > $total )||( $points > $total )||( $card > $total )||( $creditnote > $total ) ||( $advance > $total )){
$this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
 <strong>Warning!</strong> SALES NOT COMPLETED!! The money you have entered can not be more than the expected total ('.$total .') .Try again</div>');
								
		redirect($myview);
			return false;
			
		 }
	}		
				
		  
			  
			  
			$finalbalance=0;
						$mytotal=$mycash+$mpesa+$voucher+$cheque+$points+$card+$creditnote+$advance;
						$mytotal2=$cash+$mpesa+$voucher+$cheque+$points+$card+$creditnote+$credit+$advance;

			//$mytotal=$cash+$mpesa+$voucher+$cheque+$points+$card+$creditnote;
			  $finalbalance= (($mytotal-$total-$saving));
			   $currentfinalbalance= (($mytotal2-$total-$saving));
			  //
			  $finalbalances=0;
			  
		  $finalbalances= (($total-$mytotal));
   
		if( $currentfinalbalance < 0 ){
		 		 

//kengaaaaaaexit;

 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
 <strong>Warning!</strong> SALES NOT COMPLETED!! Your balance/change ('.$finalbalance .') can not be less than expected amount. Try again</div>');
								
	redirect($myview);
			return false;
			
		 }	 
			
			
	if( $negativesales !=true){
//if( $finalbalances > 0 ){
		 		 //if(($finalbalances < 0 )&& ($type =! "Invoice")){
		 		 if((trim($finalbalance) < 0 )&&(trim($type)!="Invoice")){


//kengaaaaaaexit;

 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
 <strong>Warning!</strong> SALES NOT COMPLETED!! Your balance/change ('.$finalbalance .') can not be less than expected amount. Try again</div>');
								
	redirect($myview);
	return false;
			
		 }
	}

			



 //echo $finalbalance;
//exit;
//

			  		  $this->form_validation->set_rules("cash", "Amount Paid ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewsales', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
			
			
			
				 	if($advance>0){
									
									
							$updatedbalance=(-1*$customerbalances);	
	
		//
			if(($customerid=="") ||($updatedbalance<$advance)){		
				
					 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have not selected the customer or the balance('.$updatedbalance.') is less than the amount .('.$advance.'). Please select the customer first then try again.</div>');
								
								 redirect($myview);
								 return false;	
			}



 if(trim($advance)>0){
	/*
	   $myadvance = $this->usermodel->populateallarray('advance','tenantid', $customerid);

	 $mybalance=$myadvance[0]['balance'];
	 $customer=$myadvance[0]['tenantid'];
	 $advanceid=$myadvance[0]['id'];

	
	
		 $myamount=$myadvance[0]['amount'];
		  $mypaid=$myadvance[0]['paid'];

		 			   $balances = $mybalance-$advance;
							$finalpaid = $mypaid+$advance;
							
							

    $productdata=array(		
						'balance'=>$balances,
						'paid'=>$finalpaid,
												'status'=>$status,

						
						);
						  */
 
						   
if( $balances==0){
$status="closed";
}else{
$status="active";	
}
			
		 $ttbalance=(double)$customerbalances+(double)$advance;
 $ttbalance= (-1* ($ttbalance));

		 
$ttpeoplebalance=(double)$customerbalances+(double)$advance;				 
						  							$data=array(		
			'userid'=>$userid,
			
			'description'=>"payment deducted",

		  	'balance'=>$ttbalance,
			
			'companyid' => $companyid,
				'amount' => (-$advance),
			'createdat'=>$dateposted,
				'advanceid'=>$customerid,

			
								); 
						   
						   
					$usr_resultss = $this->usermodel->add($data,'advancepayment');
							
							//check if username and password is correct
							if ($usr_resultss ==TRUE) //active user record is present
							{
							 //$this->usermodel->updatedata($productdata,'advance','id',$advanceid);
								 
							}
					







		

			 }





















									
									
				
		
		//
		
				
					$balancedata=array(		
											
												'balance'=>$ttpeoplebalance,
												
													);
								
								
										$this->usermodel->updatedata($balancedata,'people','id',$customerid);
					}
						
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
									///	$invoicename = $this->usermodel->getinvoice('sales','invoice', $invoice);

				  if ($invoicename !=false)
						   {
							  						   

											 	// $this->usermodel->deletedata($invoice,"code","debitcredit");
												 
				//$this->usermodel->deletedata($invoice,"code","debitcredit");
				$this->usermodel->deletedatatwo("debitcredit","code",$invoice,"type <>","payment");

	   
						   }
						   
						   
				
				if( $rooms !=""){
			
		$roomdata = explode('-', $rooms);
	
	
		$houseno=$roomdata[0] ;
		$plotno=$roomdata[1];
		
		 $myoccupancyNew = $this->usermodel->populatethreenoarray('dailycharges','houseno', $houseno,'plotno', $plotno,'ordersales', "active");
		//$myoccupancyNew[0]['transactioncode'];

		//$myoccupancy = $this->usermodel->populatethreenoarray('bookroom','houseno', $houseno,'plotno', $plotno,'status', "active");

	$myoccupancy= $this->usermodel->populateallarray('bookroom','transactioncode',$myoccupancyNew[0]['transactioncode']);






		 $customerid=$myoccupancy[0]['tenantid'];
				 $roomid=$myoccupancy[0]['id'];
$transactioncodes=$myoccupancy[0]['transactioncode'];
	
		
		
		$myroomdata=array(	
		
		
'houseno'=>$houseno,

				'plotno'=>$plotno,

								'transactioncode'=>$transactioncodes,
							
			'userid'=>$userid,
			
							'customerid'=>$customerid,

'branch'=>$branchid,
			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
			'total' => $total,		  
		     'invoice' => $invoice,  
		    
					     'description' => $roomid,  

							 	
			'updatedby'=>$updatedby,
			'updatedat'=>$updatedat,
								);


if ($invoicename !=false)
			{
			$confirmsales = $this->usermodel->populatealldataarray('roomsales','houseno', $houseno,'invoice', $invoice);
			if($confirmsales !=false){
				 $roomsalesid=$confirmsales[0]['id'];
			$this->usermodel->updatedata($myroomdata,'roomsales','id',$roomsalesid);
	$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		);
		$this->usermodel->updatedata($updaterefund,'bookroom','id',$roomid);
						

			}else{
		$this->usermodel->add($myroomdata,'roomsales');
	
				
			}
			}else{
			$this->usermodel->add($myroomdata,'roomsales');
   	$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		);
		$this->usermodel->updatedata($updaterefund,'bookroom','id',$roomid);
						

			}





			 //$this->usermodel->add($myroomdata,'roomsales');


		
  
				}
						   
						   
						   
						   
						   
						   
				   
						   
				if(($cardnumber !="") ||($customer !="")) {
					


				
					if($customer !="") {
						$confirmcard = $this->usermodel->Getcardnumberholder(trim($customer),$companyid);
					}else{
						$confirmcard = $this->usermodel->Getcardnumber($cardnumber,$companyid);
	
						
					}
								
							
								
								
						
				
						
								
								
					
								
	if($confirmcard!=FALSE){
		
	
					$cardnumber=trim($confirmcard[0]['address_1']);
			
					
					if($cardnumber !=""){
					
			$oldpoints=$confirmcard[0]['savedpoints'];
					$oldcoins=$confirmcard[0]['savedcoins'];
$customerid=$confirmcard[0]['id'];
		
									$TTpoints=0;
										$TTcoins=0;
	$totalpoints=0;
				$totalcoins=0;
								
		
								
						 if($redeem =="Yes"){
				 
			
				 	if($voucher>0){
										 if($voucher>$oldcoins){
							 	  
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have less coins/saving('.$oldcoins.' )... Try again</div>');
								
								 redirect('user/viewloyality');
								 return false;
						 
								}else{
								$TTcoins="-".$voucher;
	
								}
								}
		
			
								if($points>0){
										 if($points>$oldpoints){
						  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have less points('.$oldpoints.' )... Try again</div>');
								
								 redirect($myview);
								}else{
									$TTpoints="-".$points;
								}
					 
								}
				 	if($voucher > 0){
							 $totalcoins=$oldcoins-$voucher;
		
				
		
				 		$redeemdata=array(		
			'userid'=>$userid,
			'value'=>0,
				'cardnumber'=>$cardnumber,
			
		 	'description'=>"Coins Redeemed ",
			
			'type'=>"Coins",
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
								  'amount'=>$TTcoins,
								'originalamount'=>0,
								  'invoice'=>"Redeemed",
								);
						 
								
				$this->usermodel->add($redeemdata,'loyalitycards');
				
					$updatecoinsdata=array(		
											
												'savedcoins'=>$totalcoins,
												
													);
								
								
										$this->usermodel->updatedata($updatecoinsdata,'people','id',$customerid);
					}
								
								
				 
				 
				 	$totalpoints=$oldpoints-$points;
					
				 	if($points>0){
			
				 		$redeemdata=array(		
			'userid'=>$userid,
			'value'=>$TTpoints,
				'cardnumber'=>$cardnumber,
			
		 	'description'=>"Points Redeemed ",
			
			'type'=>"Points",
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
					  	  'amount'=>0,
							
								'originalamount'=>0,
								  'invoice'=>"Redeemed",
								);
						 
								
				$this->usermodel->add($redeemdata,'loyalitycards');
				
				
				
					$updatpointsdata=array(		
											
												'savedpoints'=>$totalpoints,
												
													);
								
								
										$this->usermodel->updatedata($updatpointsdata,'people','id',$customerid);
					}
						
				 
				 
				 
				 
				 
				 
			 }else{
				 
				 
		
		
		
		
			

							$savedpoints=  $total/$pointsdisplay;
							$totalpoints=$oldpoints+$savedpoints;
							
							
							
										 
												$coinsdata=array(		
			'userid'=>$userid,
			'value'=>$savedpoints,
				'cardnumber'=>$cardnumber,
			
		  	'description'=>"Loyality points awarded ",
			'type'=>"Points",
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
								  'amount'=>0,
								'originalamount'=>$total,
								  'invoice'=>$invoice,
								);
							$this->usermodel->add($coinsdata,'loyalitycards');

					
						
							
							
						
							
								if($coins==1){
							
							$savedcoins=$saving;
							
							
											 
												$coinsdata=array(		
			'userid'=>$userid,
			'value'=>0,
				'cardnumber'=>$cardnumber,
			
		  	'description'=>"Coins saved",
			'type'=>"Coins",
			
			'dateposted'=>$dateposted,
					 'companyid'=>$companyid,
					  'branchid'=>$branchid,
								  'amount'=>$saving,
								  		'originalamount'=>$total,
								  'invoice'=>$invoice,

								);
							$this->usermodel->add($coinsdata,'loyalitycards');
													$totalcoins=$oldcoins+$savedcoins;

						}else{
							
								$savedcoins=0;
									$totalcoins=$oldcoins;
						}
						
						
											$updatecoinsdata=array(		
											
												'savedcoins'=>$totalcoins,
												'savedpoints'=>$totalpoints,
												
													);
								
								
										$this->usermodel->updatedata($updatecoinsdata,'people','id',$customerid);
							
								
							
							
							
							
							
							
	}
	}	
							}
							
						
							
							
				
							
							
							
							
							
							
						}else{
							
								$savedpoints=0;
						}
						
					
				
				
				
				
				
				
										//$paymentmode = $this->usermodel->populateallarray('smsconfig','mode', 'After Bill');
												$accountname=0;
												
										if(($type=="Credit")|| ($type=="Invoice")|| ($type=="Creditnote")){
												
												$accountname=1100;
											}else if(($type=="Advance")){
												
												$accountname=2060;
											}else{
											$accountname=1000;	
											}
											
									//if($paymentmode!=FALSE){
									
											//$accountname=1000;
											
										//}else{
											
										//}
								
			
			
			
	// $type;

			
			  if ($invoicename ==false)
						   {
						   
							   
							   $userid=$userid;
							   $name=$name;
							   $customer=$customer;
							   $description=$description;
								$mytable=$mytable;

						   $updatedby="";
			
						   $updatedat="";
						   $dateposted= $dateposted;
						   	$oldcreditamount=0;

						   }else{
							   
							   //$view=
							   
							    $updatedby=$userid;
			
						   $updatedat=$dateposted;
							  $dateposted= $invoicename[0]['dateposted'];	 
							    $userid=$invoicename[0]['userid'];
								$mytable=$invoicename[0]['mytable'];;
						$oldcreditamount=$invoicename[0]['credit'];
								$name=$invoicename[0]['name'];
								
								if($customer !=""){
								 $customer=$customer;

								}else{
								 $customer=$invoicename[0]['customer'];

								}
							   //$customer=$invoicename[0]['customer'];
							   
							   
							   
							   $description=$invoicename[0]['description'];								
						   }
			
			
			
		
			
						   
												$MPESASALEAdata=array(		
			'userid'=>$userid,
			
				'code'=>$accountno,
			
		  	'branch'=>$branchid,
				 'companyid'=>$companyid,
				'type'=>1,
				 	'amount'=>$paidamount,
			'dateposted'=>$dateposted,
				'paymentstatus'=>$mpesastatus,
						//	'paymentstatus'=>$paymentstatus,

								);
							
			
			
			
			
		
			
			
			
			
			
			
			
			
						   							$paymentdata=array(		
			'id'=>$mpesaid,
			
				'used'=>$mpesastatus,
		
						   
					  	);		   //validation succeeds
										
										
					
					 	if ($this->input->post('btn_savesales'))
					   {
						   
						   
		
				
						 
						   $ordersales="";
						   	    	if ($this->input->post('btn_savesales') == "sales")
					   {
						   //
						 		  if (($receiptview=="One With Automatic Logout")||($receiptview=="One Without Automatic Logout")){
															$paymentstatus="Cleared";
   $ordersales="printed";

						  }else{
							  //$paymentstatus="Cleared";
							 // $paymentstatus=$paymentstatus;
  $paymentstatus="No";
  						
   $ordersales="new";
						  }
				   
						
															//echo$paymentstatus="No";
															//exit;
		   
						   
						}else  	if ($this->input->post('btn_savesales') == "noreceipt")
					   {
						
						
						      $ordersales="printed";

						   // $ordersales="new";
							$paymentstatus="No";
		  if (($receiptview=="One With Automatic Logout")||($receiptview=="One Without Automatic Logout")){
							$paymentstatus="Cleared";
							  //$paymentstatus=$paymentstatus;

						  }else{
							  ///$paymentstatus=$paymentstatus;
					$paymentstatus="Cleared";
						  }
				   
						
						   
						}else  	if ($this->input->post('btn_savesales') == "order")
					   {
						
   $ordersales="new";
											//$paymentstatus="No";

						   
						}else {
						
															$paymentstatus="Cleared";

						   $ordersales="printed";

						}
							
						  	   
						if($description =="" ){
														$description=$mydescription;

						}else{
														$description=$description;


							
						}
					   
				   

						   $mybalance=0;
														
								if(($type=="Credit")|| ($type=="Invoice")|| ($finalbalance !=0)){
								$mybalance=$finalbalance;
								}else{
									$mybalance=$change;	
									}									
						   
						   
												$data=array(
'houseno'=>$houseno,
			
				'plotno'=>$plotno,												
			'userid'=>$userid,
						'cardnumber'=>$customerpin,
		 'savedcoins'=>$savedcoins,
								'savedpoints'=>$savedpoints,
				
			'customer'=>$customer,
		  	'cash'=>$cash,
					  	'salestype'=>$salestype,
			   			   'cashier' => $accountno, 
'branch'=>$branchid,
			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
						'advance'=>$advance,

			'total' => $total,		  
		  'type' => $type,    
		     'invoice' => $invoice,  
			 	   //'balance' => $change, 
			 
		     //'balance' => $finalbalance, 
			 'balance' => $mybalance,
			 		    // 'balance' => -($discountedtotal), 

			   'due_date' => $due, 
					   'maindiscount' => $maindiscount,   
							'name' => $name,  					   
		     'discountedtotal' => $discountedtotal, 
								  'maincategory' => $maincategory,  

					  'ordersales' =>$ordersales , 
			  'description' => $description,    
		  'mytable' => $mytable,
//		  balance
					   'paymentstatus' => $paymentstatus,   

			  'mpesa' => $mpesa,    
		     'cheque' => $cheque, 
			 		     'creditnote' => $creditnote,  
			 			     'salesperson' => $salesperson, 
				 			     'currency' => $basecurrency, 
								 'othercurrency' => $currency,
								 'othercurrencyamount' => $tocurrencyamount,
	
		     'card' => $card, 
			   'voucher' => $voucher, 
			   'credit' => $credit, 
					   'points' => $points,   
						 'receiptno' => $receiptno,   
	
			'updatedby'=>$updatedby,
			'updatedat'=>$updatedat,
								);

						
						  if ($invoicename ==false)
						   {
							   
							   
							   
							   
							   
							   
							   
							   
							   
							$usr_result = $this->usermodel->add($data,'sales');
      						//$this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

				
						   }else{
						$usr_result = $this->usermodel->updatedata($data,'sales','invoice',$invoice);
    						//$this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

						   }
						   	
	
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 if ($invoicename != false)
						   {
							
								 $this->usermodel->deletedata($invoice,"code","debitcredit");
		
						   }
			
								
								
								
	  $linksalesorders=$this->usermodel->populatuserpermissionsdataarray('openclose','linksalesorders',$userid);
							
if($linksalesorders==true){
   if($name!=""){
	 		    $mysoldqty = $this->input->post("soldqty"); 
			 

		$getpetrol = $this->usermodel->populateallarray('openorders','id', $name);

		 	  $orderid=$getpetrol[0]['id'];
			   
			    $nextfuel=$getpetrol[0]['nextfuel'];
				 $fuellimit=$getpetrol[0]['fuellimit'];
			  
			  
			  $fuel=$fuellimit-$mysoldqty;
			  
			  			  $adjusted=$mysoldqty-$nextfuel;


	   
												$Petrol=array(		
			'exactfuel'=>$mysoldqty,
			
				'fuel'=>$fuel,
			
		  	'adjusted'=>$adjusted,
				

								);
			   				$this->usermodel->updatedata($Petrol,'openorders','id',$orderid);

   }


}






								
			if($mpesaresult!=FALSE){				
			$usr_result = $this->usermodel->add($MPESASALEAdata,'mpesasales');
		
		
			
			   						$this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

				
			}

			 $myArray = explode(',', $accountno);
		
			if(is_array($myArray)){
foreach($myArray as $allaccountno){

	 $this->usermodel->deletedata($allaccountno,"code","mergedmpesa");

}
}



//$creditdata=array( 'userid'=>$userid,'account'=>4000,'credit'=>$total,'description'=>"Good sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'balance'=> $nextfinalbalance);

			if($activatebank=="yes"){
				
					if($type!="Cash"){
				//
										
				$closedata[]=array(	'invoice'=>$invoice,	
									'status'=>'printed',
									'type'=>$type,
											);
					}else{
							
									$closedata[]=array(	
									'invoice'=>$invoice,		
									'status'=>'printed',
										
											);	
						
					}
				
				
				
				
				
				
				
$confirmaccounts = $this->usermodel->populatealldatanoarray('paymentmethodes','branchid', $branchid,'companyid', $companyid);



if(is_array($confirmaccounts)){
		$insertdebitdata= array();
	   foreach($confirmaccounts as $row)
	   {
		
				$mybankname=$row->name;
		      $myaccountno=$row->type;
	
 
  
  	   if(($mybankname=="advance") && ($advance != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$advance,'description'=>"Payment through Advance",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
 
		   }
  
		   if(($mybankname=="cash") && ($cash != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cash,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
 
		   }
		     if(($mybankname=="mpesa") && ($mpesa != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$mpesa,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
  
				}
		       if(($mybankname=="bank") && ($cheque != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cheque,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
  
				}
				 if(($mybankname=="card") && ($card != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$card,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
					}

			if(($mybankname=="voucher") && ($voucher != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$voucher,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
					}
					
					//
			if(($mybankname=="credit") && ($credit != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$credit,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
					}
			
			 if(($mybankname=="points") && ($points != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$points,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
			
					}
			
			
			if(($mybankname=="creditnote") && ($creditnote != 0)){
				$Creditnotetotal=0;
	if($creditnote <0){
			$Creditnotetotal=(-1*$creditnote);

	}else{
			$Creditnotetotal=$creditnote;

	}

				 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$Creditnotetotal,'description'=>"Goods returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'creditnote','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);
				 //$insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$credit,'description'=>"Payment of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'payment','transactioncode'=>$accountno ,'supplier'=> $customerid,'mode'=>$myinvoices);

					}

	   }
	 
	   	if(!empty($insertdebitdata)){
		$this->db->insert_batch('debitcredit', $insertdebitdata);

							}	
							
	   
}








				
				
			}else{
	
			
			if($type!="Cash"){
				//
										
											$closedata[]=array(		
											//'dateposted'=>$dateposted,	

												'invoice'=>$invoice,	
									'status'=>'printed',
										'type'=>$type,
											);
										
if($type=="Creditnote"){
	$Creditnotetotal=0;
	if($total<0){
			$Creditnotetotal=(-1*$total);

	}else{
			$Creditnotetotal=$total;

	}
	//
	//
								$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'credit'=>$Creditnotetotal,'description'=>"Good returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'creditnote','transactioncode'=>$accountno ,'supplier'=> $customerid ,'mode'=>$myinvoices);
			
				}else  if($type=="Advance"){
				
				
					$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$total,'description'=>"Paid through Advance",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Paid with advance','transactioncode'=>$accountno ,'supplier'=> $customerid ,'mode'=>$myinvoices);

				
				
				
				}else{
						$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$total,'description'=>"Good sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','transactioncode'=>$accountno ,'supplier'=> $customerid);

				}										



									}else{
										
									$closedata[]=array(		
											//'dateposted'=>$dateposted,	

												'invoice'=>$invoice,		
									'status'=>'printed',
										
											);
										$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$total,'description'=>"Good sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$accountno ,'supplier'=> $customerid);
	//
										
									}
								//$this->usermodel->updatedatabytwo($closedata,'sales_order','invoice',$invoice,'status<>','returned');

								
			}					
									
			
	$ttbrice=0;




			  
	  if($mydebitcred= $this->usermodel->geteallsales_order($invoice)){
		  				$this->db->where('status <>','returned');
	$this->db->update_batch('sales_orderraw',$closedata, 'invoice');
		
	  }else{
		  	 
	$mydebitcred= $this->usermodel->geteallsales_orderoriginal($invoice);
	$this->db->where('status <>','returned');
	$this->db->update_batch('sales_order',$closedata, 'invoice');
								
		  
		  }
	  


				
			$sales_orderkitchen = array();
								$sales_orderdata = array();
	//$solditems= $this->usermodel->geteallsales_order($invoice);
			//$solditems= $this->usermodel->geteallsales_orderoriginal($invoice);

			
$totTaxblAmt=0;
$totTaxAmt=0;
$ttitemqty=0;
		$taxblAmtA=0;
            $taxblAmtB=0;
            $taxblAmtC=0;
            $taxblAmtD=0;
            $taxblAmtE=0;
			
			$taxAmtA =0;
			$taxAmtB=0;
            $taxAmtC=0;
            $taxAmtD=0;
            $taxAmtE =0;

				//$mydebitcred= $this->usermodel->searchaaccountingsalesrow($invoice,$companyid);
		$costofgoodsold="";		
	if(is_array($mydebitcred)){
	$insertdata = array();
	$insertinventorydata = array();

			   	$enabled="";


	$salesaccount="";


	$inventoryaccount="";
	   foreach($mydebitcred as $row)
	   {
		   
		   $mystatus=$row->status;
		   if($mystatus !="returned"){
	   $transactionid=$row->id; $itemid=$row->code;$totalqty=$row->qty;$mybranch=$row->branch;$mytotal=$row->amount;
		  $producttype=$row->producttype;
		

			 $mybprice=$row->bprice;
			  $correctqty=$row->qty;
			  $finalbprice=((double)$mybprice*(double)$correctqty);
			 
		$salesaccount=$row->salesaccount;
		  $costofgoodsold=$row->expenseaccount;
		   $inventoryaccount=$row->assetaccount;
	 if($salesaccount!=""){ $salesaccount=$row->salesaccount;}else{ $salesaccount=4000; }
	  if($costofgoodsold!=""){ $costofgoodsold=$row->expenseaccount;}else{ $costofgoodsold=5500; }
	 if($inventoryaccount!=""){ $inventoryaccount=$row->assetaccount;}else{ $inventoryaccount=1110; }

	 if($type=="Creditnote"){
		 
		 $Creditnotetotal=0;
	if($mytotal<0){
			$Creditnotetotal=(-1*$mytotal);

	}else{
			$Creditnotetotal=$mytotal;

	}
				 $insertdata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$salesaccount,'debit'=>$Creditnotetotal,'description'=>"Good returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid,'type'=> 'creditnote' ,'supplier'=> $customerid);
		
				}else{
					 $insertdata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$salesaccount,'credit'=>$mytotal,'description'=>"Good sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid,'type'=> 'sales' ,'supplier'=> $customerid);
	
				}
		if(($producttype!="Service") && ($mybprice!="")){
			
			$ttbrice=$ttbrice+ $finalbprice;
				if($type=="Creditnote"){
					
					
						 $Creditnotetotal=0;
	if($finalbprice<0){
			$Creditnotetotal=(-1*$finalbprice);

	}else{
			$Creditnotetotal=$finalbprice;

	}
					 $insertinventorydata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$Creditnotetotal,'description'=>"Inventory returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'creditnote' ,'supplier'=> $customerid);

				}else{
								 $insertinventorydata[]=array('refno'=>$itemid, 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$finalbprice,'description'=>"Inventory sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'sales' ,'supplier'=> $customerid);
	
				}
			

		}

		
	   }
	   
	   

	   
	      $myid=trim($row->id);
				
				
				
						$assetaccount=$row->assetaccount;
		$salesaccount=$row->salesaccount;
		$expenseaccount=$row->expenseaccount;
				$taxcode=$row->taxcode;

			$producttype=$row->producttype;	
			$mode=$row->mode;	
			$mytaxcode=$row->taxcode;	

				if($mytaxcode=="A"){
						$taxblAmtA=$taxblAmtA+$row->amount;
						$taxAmtA=$taxAmtA+$row->tax;
					}
						
					if($mytaxcode=="B"){
					$taxblAmtB=$taxblAmtB+$row->taxable;
					$taxAmtB=$taxAmtB+$row->tax;
					}	
					if($mytaxcode=="C"){
					$taxblAmtC=$taxblAmtC+$row->amount;
					$taxAmtC=$taxAmtC+$row->tax;					
					}	
					if($mytaxcode=="D"){
					$taxblAmtD=$taxblAmtD+$row->amount;
					$taxAmtD=$taxAmtD+$row->tax;
					}	
					if($mytaxcode=="E"){
					$taxblAmtE=$taxblAmtE+$row->taxable;
					$taxAmtE=$taxAmtE+$row->tax;					
					}
			
				
				
				
		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$mytype=$row->type;
	 $myqty=$row->qty;

	//$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;






//echo "===xxxxxxxx=======".round($bprice,2);

///exit;


	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;

		
		
		if($kitchen=="yes"){
		
			
		  $confirmprinters = $this->usermodel->populatealldatanoarraythree('printers','branchid', $branchid,'status', 'active','categoryno',$row->maincategory);




if(is_array($confirmprinters)){

   foreach($confirmprinters as $confirmprintersrow)
   {
    $kitchenid=$confirmprintersrow->categoryno; 





	
	
			
			if($row->maincategory == $kitchenid){
			if($ordersales !="printed"){

			$enabled="yes";
				$sales_orderkitchen[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 
		'customer'=>$row->customer,
		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
				
			}
			}
			
		}
		}
	
	
}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'start'=>$enabled,
			'mode'=>$mode,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
			 'taxcode' => $taxcode,
			'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 
						'customer'=>$row->customer,
				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
								
								   if (($etims=="EnableEtims") && ($this->input->post('btn_savesales') != "order") ){
									   
										 ///////OKATCH
			
							//		   
									   
				//$productname = $this->usermodel->populateallarray('productlis','code', $code);
				$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);
				 
				$name=$productname[0]['name']; 
				$itemclassification=$productname[0]['itemclassification']; 
		  	$hscode=$productname[0]['hscode']; 
					  	$packagingunit =$productname[0]['packagingunit']; 
					  	$salesunit=$productname[0]['salesunit']; 
	   					  	$itemtax=$productname[0]['itemtax']; 
			  $inventorytype=trim($productname[0]['producttype']); 

//

if($etimsonline !="yes"){
$this->SendStStockMaster($code,$productname[0]['qty']);
}

//
 $stockmasterdata = [
		  	'tin' => $mykra_pin,
            'bhfId' => $mybranch_id,
            "itemCd" => $hscode,
            "rsdQty" => $myqty,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
			
        ];
		     $stockmasterdata1['tin'] =  $mykra_pin;
            $stockmasterdata1['bhfId'] = $mybranch_id;
            $stockmasterdata1['itemCd'] =  $hscode;
            $stockmasterdata1['rsdQty'] = $this->formatMoney($myqty,true);
            $stockmasterdata1['regrId'] = "Admin";
            $stockmasterdata1['regrNm'] = "Admin";
            $stockmasterdata1['modrNm'] = "Admin";
            $stockmasterdata1['modrId'] = "Admin";
		$finalstockmasterdata[] = $stockmasterdata1;

	   $ttitemqty=$ttitemqty+1;


	   //$ttitemqty=$ttitemqty+$myqty;

$totTaxblAmt=$totTaxblAmt+$taxable;
 //$totTaxAmt=$totTaxAmt+$tax;

//$totTaxAmt=$totTaxAmt+$taxAmtA+$taxAmtB+$taxAmtC+$taxAmtD+$taxAmtE;
			//ouma
//$this->formatMoney($myfinaltax, true);
			
			$data1['itemSeq'] = round($ttitemqty,2);
            $data1['itemCd'] =  $hscode;
            $data1['itemClsCd'] = $itemclassification;
            $data1['itemNm'] =  $name;
            $data1['bcd'] = $code;
            $data1['pkgUnitCd'] = $packagingunit;
            $data1['pkg'] =  $this->formatMoney($myqty,true);
            $data1['qtyUnitCd'] = $salesunit;
            $data1['qty'] = $this->formatMoney($myqty,true);
              $data1['prc'] = $this->formatMoney($sprice,true);
            $data1['splyAmt'] = $this->formatMoney($bprice,true);
            $data1['dcRt'] = 0;
            $data1['dcAmt'] = $discount;
            $data1['isr ccCd'] = null;
            $data1['isrccNm'] = null;
            $data1['isrcRt'] = null;
            $data1['isrcAmt'] = null;
            $data1['taxTyCd'] = $itemtax;
            $data1['taxblAmt'] = $taxable;
            $data1['taxAmt'] = ($tax);
            $data1['totAmt'] = $amount;
            $saledetails[] = $data1;
								
			
	if($inventorytype !="Service"){
               $data2['itemSeq'] = $ttitemqty;
                $data2['itemCd'] = $hscode;
                $data2['itemClsCd'] = $itemclassification;
                $data2['itemNm'] = $name;
                $data2['bcd'] = $code;
                $data2['pkgUnitCd'] = $packagingunit;
                $data2['pkg'] = 1;
                $data2['qtyUnitCd'] = $salesunit;
                $data2['qty'] = $this->formatMoney($myqty,true);
                $data2['itemExprDt'] = '';
				$data2['prc'] =  $this->formatMoney($sprice,true);
                $data2['splyAmt'] =  $this->formatMoney($bprice,true);
                $data2['totDcAmt'] = $discount;
                $data2['taxblAmt'] = $taxable;
                $data2['taxTyCd'] = $itemtax;
                $data2['taxAmt'] = $tax;
                $data2['totAmt'] = $amount;
				
				$itempurchased[] = $data2;
				 $productname[0]['qty'];
				

	}



					
						
								
								
								   }
	   
	   //
		}
		$totTaxAmt=$taxAmtA+$taxAmtB+$taxAmtC+$taxAmtD+$taxAmtE;

		$usr_result =$this->db->insert_batch('sales_order', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
							 	 $this->usermodel->deletedata($invoice,"invoice","sales_orderraw");
	
			
		}	
				//$itempurchased2[] = $stockmasterdata;




	
								
							   if ($etims =="EnableEtims"){
							  		  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
							   
		
							 $currentDateTime =date('YmdHis');
		  
			 $currentDate =date('Ymd');

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

if($onlineoffline=="OSCU"){
$apiUrl = ''.$etimsurl.'/etims-api/saveTrnsSalesOsdc';			
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/trnsSales/saveSales';

			 }
			    



 $dataviewreceipt = $this->usermodel->populateinvoiceAll($invoice);




			  $stockmasterdatajson = json_encode($finalstockmasterdata);










        // Data to send in the JSON format
       $receipt = [
				
            "custTin" => $customerpin,
            "custMblNo" => $customerpinphone,
            "rptNo" =>  $dataviewreceipt[0]['id'],
            "rcptPbctDt" => $currentDate,
            "trdeNm" => "",
            "adrs" => "",
            "topMsg" => "Shopwithus",
            "btmMsg" => "Welcome",
            "prchrAcptcYn" => "Y",
        ];
		

	   
	     
	   
	     $data2 = [
		    "tin" => $kra_pin,
            "bhfId" => $branch_id,	
            "sarNo" => $dataviewreceipt[0]['id'],
            "orgSarNo" => $dataviewreceipt[0]['id'],
            "regTyCd" => "M",
            "custTin" => $customerpin,
            "custNm" => $customername,
            "custBhfId" => $branch_id,
            "sarTyCd" => "02",
            "ocrnDt" => $currentDate,
            "totItemCnt" => (int) $ttitemqty,
            "totTaxblAmt" => $this->formatMoney($totTaxblAmt,true),
            "totTaxAmt" =>$this->formatMoney($totTaxAmt,true),
            "totAmt" => $total,
            "regrId" => "Admin",
            "regrNm" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin",
            "itemList" => $itempurchased,

        ];
  
  $salestype="";
   $originalinvoice="";
if($type=="Creditnote"){
	$previousinvoice=$accountno;
	$dataviewreceiptss = $this->usermodel->populateallarray('sales','id',$previousinvoice);

	$salestype="R";
	   $originalinvoice=$dataviewreceiptss[0]['currcptno'];
	  
}else{
		$salestype="S";
   $originalinvoice=0;

}

	   
$data1 = [
			"tin" => $kra_pin,
              "bhfId" => $branch_id,
            "invcNo" => $dataviewreceipt[0]['id'],
            "orgInvcNo" =>$originalinvoice,
            "custTin" => $customerpin,
            "custNm" => $customername,
            "salesTyCd" => "N",
			//"rcptTyCd" => "R",
			"rcptTyCd" => $salestype,
            "pmtTyCd" => "01",
            "salesSttsCd" => "02",
            "cfmDt" => $currentDateTime,
            "salesDt" => $currentDate,
            "stockRlsDt" => $currentDateTime,
            "cnclReqDt" => null,
            "cnclDt" => null,
            "rfdDt" => null,
            "rfdRsnCd" => null,
            "totItemCnt" => (int) $ttitemqty,
            "taxblAmtA" =>$this->formatMoney($taxblAmtA,true),
            "taxblAmtB" =>$this->formatMoney($taxblAmtB,true),
            "taxblAmtC" =>$this->formatMoney($taxblAmtC,true),
            "taxblAmtD" =>$this->formatMoney($taxblAmtD,true),
            "taxblAmtE" =>$this->formatMoney($taxblAmtE,true),
            "taxRtA" => 0,
            "taxRtB" => 16,
            "taxRtC" => 0,
            "taxRtD" => 0,
            "taxRtE" => 0,
            "taxAmtA" =>$this->formatMoney($taxAmtA,true),
            "taxAmtB" =>$this->formatMoney($taxAmtB, true),
            "taxAmtC" => $this->formatMoney($taxAmtC,true),
            "taxAmtD" => $this->formatMoney($taxAmtD,true),
            "taxAmtE" => $this->formatMoney($taxAmtE,true),
            "totTaxblAmt" =>$this->formatMoney($totTaxblAmt,true),
            "totTaxAmt" =>$this->formatMoney($totTaxAmt,true),
            "totAmt" =>$this->formatMoney($total,true),
            "prchrAcptcYn" => "Y",
            "remark" => null,
            "regrId" => "11999",
            "regrNm" => "TestVSCU",
            "modrId" => "45678",
            "modrNm" => "TestVSCU",
            "receipt" => $receipt,
            "itemList" => $saledetails,

        ];
        // Convert the data to JSON format
      	
						   
	  }				    
						   
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	
	if($ttbrice!=0){
		
	
		
$this->db->insert_batch('debitcredit', $insertinventorydata);
//thisss
}

	}	
			
	if($ttbrice!=0){
		
		if($type=="Creditnote"){
			
								 $Creditnotetotal=0;
	if($ttbrice<0){
			$Creditnotetotal=(-1*$ttbrice);

	}else{
			$Creditnotetotal=$ttbrice;

	}
	//
		$insertcostofgoodsolddata=array( 'userid'=>$userid,'account'=>$costofgoodsold,'credit'=>$Creditnotetotal,'description'=>"Cost of goods returned",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'creditnote' ,'supplier'=> $customerid);
				
				}else{
	$insertcostofgoodsolddata=array( 'userid'=>$userid,'account'=>$costofgoodsold,'debit'=>$ttbrice,'description'=>"Cost of goods sold",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $customerid);

				}
	$this->usermodel->add($insertcostofgoodsolddata,'debitcredit');
//thisss



	}				
								
								if($activatebank=="yes"){
								}else{
							$this->usermodel->add($debitdata,'debitcredit');
	
								}
							
					//thisss
	if(!empty($insertdata)){
									$this->db->insert_batch('debitcredit', $insertdata); 
//thisss
								
	}					

	
								
								if(($type=="Credit")|| ($type=="Invoice")){
									if(($credit>0) && ($customer!="")){
										//$ = $this->usermodel->populateallarray('people','id',$customer);
									$customerbalance=$ourpeople[0]["balance"];
									$peopleid=$ourpeople[0]["id"];
									$myfinaltotalamount=$customerbalance+$credit;
									 if ($invoicename !=false)
												{
												$myfinaltotalamount=$myfinaltotalamount-$oldcreditamount;	
												}
									
										$peopledata=array(		
												'balance'=>$myfinaltotalamount,
										'lastbalancedate'=>$dateposted,
												
												
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$peopleid);
										
									}
									
								}
								
		
			
								
								
							
		
								
								  if(( $sendmysms=="1") && ($customerid !="")){
		  
		  
	
		
		  
		  
		 $people = $this->usermodel->populateallarray('people','id',$customerid);
									$myphone=$people[0]["phone"];
							//		
								
										
	
										
					if(($type=="Credit") || ($type=="Invoice")){
						
						
						
						
						$myyview="user/printinvoice?invoice=". $invoice."";
												$invoicelink= base_url()."printinvoice?refnumber=".$invoice;

						$digitalmessage="Hello, this is to inform you that your invoice worth Ksh ".$total." with  REF No ".$salesid." due on ".$due."  has been generated. Thank you for shopping with us. Click this link to print your Digital invoice: ".$invoicelink."";
	
					}else{
					$receiptlink= base_url()."pintreceipt?refnumber=".$invoice;
	$myyview="user/printreceipts?invoice=". $invoice."";
						$digitalmessage="Hello, this is to inform you that your Receipt worth Ksh ".$total." with   REF No ".$invoice." has been generated.Thank you for shopping with us. Click this link to print your Digital Receipt: ".$receiptlink."";

					}
					
	
								
		if($myphone!=""){
			
				//
		  	  	 $this->pushroomsms($digitalmessage,$myphone,$myyview);

							//  $this->pushedsmswithview($digitalmessage,$myphone,$myyview);	

														 //$sendmysms."iko".$myphone;
		
										
										
										
										
										
		}
	  }
								
  							if(!empty($sales_orderkitchen)){
		$this->db->insert_batch('sales_orderkitchen', $sales_orderkitchen);

							}									
		
							
											   if ($etims =="EnableEtims"){
  
  
  
  
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewsales');
						   

						   
						   return false;
						   }											
							
						  $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewsales');
						   return false;
	}
		
  //
  
  
  
  
 
				$currcptno =$dataviewreceipt[0]['id'];
                $totrcptno = $dataviewreceipt[0]['id'];
                $intrldata = "";
                $rcptsign = "";
				
					  
	

	  


$intrlData = strtoupper($this->generateIntrlData($kra_pin, $currentDateTime));


$rcptSign = strtoupper($this->generateRcptSign($kra_pin, $currentDateTime));
  
  $myreceipt = [
	   "tin" => $kra_pin,
    "bhfId" => $branch_id,
    "invcNo"=>  $dataviewreceipt[0]['id'],
    "orgInvcNo"=>  0,
//	"rcptTyCd" => $salestype,
     "orgInvcNo" =>$originalinvoice,
    "curRcptNo"=>  $currcptno,
    "totRcptNo"=>  $totrcptno,
    "custTin"=>  $customerpin,
    "custMblNo"=>  "",
    "rptNo"=>  $currcptno,
    "rcptPbctDt"=> $currentDateTime,
    "intrlData"=>  $intrlData,
    "rcptSign"=>  $rcptSign,
    "jrnl"=>  "",
    "trdeNm"=>  "",
    "adrs"=>  "N/A",
    "topMsg"=>  "Welcome again",
    "btmMsg"=>  "THANK YOU",
    "prchrAcptcYn"=>  "N",
    "regrId"=>  "Admin",
    "regrNm"=>  "Admin",
    "modrId"=>  "Admin",
    "modrNm"=>  "Admin"

        ];
  


  $salesdump="";
  $receiptdump="";

  
  $salesdump = json_encode($data1);
  $receiptdump = json_encode($myreceipt);

							$Tempupdateinvoicedata=array(		
										'currcptno'=>$currcptno,
										'totrcptno'=>$totrcptno,
										'intrldata'=>$intrlData,
										'rcptsign'=>$rcptSign,
										'etimsstatus'=>3,
										//'sdcdatetime'=>$sdcdatetime,
										

'itemsstockmaster'=>$stockmasterdatajson,												
'mrcNo'=>trim($configuration[0]["mrcNo"]),
'sdcId'=>trim($configuration[0]["sdcId"]),
'salesdump'=>$salesdump,
'receiptdump'=>$receiptdump,
'sdcdatetime'=>$currentDateTime,					
					
			'taxblAmtA'=>$this->formatMoney($taxblAmtA,true),								
			'taxblAmtA'=>$this->formatMoney($taxblAmtA,true),
            'taxblAmtB'=>$this->formatMoney($taxblAmtB,true),
            'taxblAmtC'=>$this->formatMoney($taxblAmtC,true),
            'taxblAmtD'=>$this->formatMoney($taxblAmtD,true),
            'taxblAmtE'=>$this->formatMoney($taxblAmtE,true),
			 'tax1'=>$this->formatMoney($totTaxAmt,true),

			'taxAmtA'=>$this->formatMoney($taxAmtA,true),
			'taxAmtB'=>$this->formatMoney($taxAmtB,true),
            'taxAmtC'=>$this->formatMoney($taxAmtC,true),
            'taxAmtD'=>$this->formatMoney($taxAmtD,true),
            'taxAmtE'=>$this->formatMoney($taxAmtE,true),
												
												
													);
 if($etimsonline=="yes"){						
								//cccccc
	$this->usermodel->updatedata($Tempupdateinvoicedata,'sales','invoice',$invoice);   
						   
	  
	  
	  
	  
  }
  
  

  if($etimsonline !="yes"){
	    $jsonData = json_encode($data1);

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
					
					//   echo "<br>";
					   
		$all= $response;
	
		//echo "<BR>";
		//Not selling
		
        // Check for cURL errors
		    // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS sales :'.curl_error($ch).',Details:'.var_dump($response).'. Try again </div>');
								
						  redirect('user/viewsales');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);

//VAR_DUMP($responseArray );

///EXIT;
			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			 $resultMsg = $responseArray['resultMsg'];




            if ($resultCd == '000') {
				

				
                $currcptno = $responseArray['data']['curRcptNo'];
                $totrcptno = $responseArray['data']['totRcptNo'];
                $intrldata = $responseArray['data']['intrlData'];
                $rcptsign = $responseArray['data']['rcptSign'];
                $sdcdatetime = $responseArray['data']['sdcDateTime'];	   
					 $mrcNos = $responseArray['data']['mrcNo'];
						$sdcIds = $responseArray['data']['sdcId'];	   
							$updateinvoicedata=array(		
												'currcptno'=>$currcptno,
										'totrcptno'=>$totrcptno,
												'intrldata'=>$intrldata,
										'rcptsign'=>$rcptsign,
												'sdcdatetime'=>$sdcdatetime,
													'mrcNo'=>$mrcNos,
												'sdcId'=>$sdcIds,
													'etimsstatus'=>1,
												
											
											
'itemsstockmaster'=>$stockmasterdatajson,												
'mrcNo'=>trim($configuration[0]["mrcNo"]),
'sdcId'=>trim($configuration[0]["sdcId"]),
'salesdump'=>$salesdump,
'receiptdump'=>$receiptdump,
//'sdcdatetime'=>$currentDateTime,										
											
											
											
											
											
											
												
			'taxblAmtA'=>$this->formatMoney($taxblAmtA,true),
            'taxblAmtB'=>$this->formatMoney($taxblAmtB,true),
            'taxblAmtC'=>$this->formatMoney($taxblAmtC,true),
            'taxblAmtD'=>$this->formatMoney($taxblAmtD,true),
            'taxblAmtE'=>$this->formatMoney($taxblAmtE,true),
			 'tax1'=>$this->formatMoney($totTaxAmt,true),

			'taxAmtA'=>$this->formatMoney($taxAmtA,true),
			'taxAmtB'=>$this->formatMoney($taxAmtB,true),
            'taxAmtC'=>$this->formatMoney($taxAmtC,true),
            'taxAmtD'=>$this->formatMoney($taxAmtD,true),
            'taxAmtE'=>$this->formatMoney($taxAmtE,true),
												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','invoice',$invoice);   
						   
				
			
	
						   
						//   
				    
	if($onlineoffline=="OSCU"){
$apiUrl2 = ''.$etimsurl.'/etims-api/insertStockIO';
			

			 }else{
			
$apiUrl2 = ''.$etimsurl.'/stock/saveStockItems';

			 }
			   			
					
					
					

	   $jsonData2 = json_encode($data2);
	   
        // Initialize cURL session
        $ch2 = curl_init();
		

        // Set cURL options
        curl_setopt($ch2, CURLOPT_URL, $apiUrl2);
        curl_setopt($ch2, CURLOPT_POST, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $jsonData2);
        curl_setopt($ch2, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response2 = curl_exec($ch2);		   
		
				   
						   
			}else{
			    $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!  </strong>Sales data saved Successfully,  however Error occurred during submitting  ETIMS Items :'.curl_error($ch2).',Error message :'.($resultMsg).' . Try again </div>');
								
							redirect("user/viewsales");
						   	
				
			}
		
		
		}
  }		
		
											
							
											   }
							
							
									
						if ($this->input->post('btn_savesales') == "noreceipt")
					   {
						  
						  	if($myview=="user/viewwholesales"){
								
										redirect("user/viewwholesales");
							}else{
							redirect("user/viewsales");
	
							}
						  
						  
						}else  	if ($this->input->post('btn_savesales') == "sales")
					   {
						   
						   
				
						   
						  //var_dump($sales_orderkitchen);
					
							
						if($delivery==1){
						redirect("user/printdelivery?invoice=". $invoice."");
							}
						
						
						
							if(($type=="Credit")|| ($type=="Invoice")|| ($type=="Creditnote") ){
				
	if($nextcounter==1){
  redirect("user/viewbalance?invoice=". $invoice."");	
								  return false;
		
		}else{
		
  redirect("user/printinvoice?invoice=". $invoice."");	
								  return false;			
		}
				
				
								
								
								}else{
									
								redirect("user/printreceipts?invoice=". $invoice."");

								
									
									}
						
						
					
							
							
						
						}else  	if ($this->input->post('btn_savesales') == "order")
					   {

				if($kitchen=="yes"){

	if($receiptview=="One Without Automatic Logout"){


redirect('user/viewsales');
 
}else if($receiptview=="One With Automatic Logout"){


redirect('login');

	

}else if($receiptview=="Two Without Automatic Logout"){


redirect('user/viewsales');
 
}else if($receiptview=="Two With Automatic Logout"){


redirect('login');

	

	}else if($receiptview=="Three Without Automatic Logout"){

redirect('user/viewsales');

 
}else if($receiptview=="Three With Automatic Logout"){


redirect('login');
  
}else{
	

	if($nextcounter==1){
	redirect('user/viewmysales?invoice=$invoiceid&myview=$myview');

		
		}else{
		
redirect('user/viewsales');
			
		}
	
}

					
				}else{
										 redirect("user/printmyorder?invoice=". $invoice."&nextcounter=".$nextcounter."&myview=".$myview);
	
					
				}
				
//
						   
						
						
						 //redirect("user/printreceipts?invoice=". $invoice."");

						
						}
									
									
									
									
									
									
	
								
							
												


					  
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('salestmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales  was not Completed.. Try again</div>');
								
								 redirect($myview);
							}
		
					   }else{
							 redirect("login");   
						   
					   }
	    }
    }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function getpayment() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
	
if($restricttill=="yes"){
	  $data['payment'] = $this->usermodel->populatependingpaymentbybranch($phone,$branchid);

}else{
	  $data['payment'] = $this->usermodel->populatependingpayment($phone);


}
   








//
 if($data['payment']!=false){
	 $myphone = $data['payment']['0']['sender_number'];
	 $transactioncode = $data['payment']['0']['code'];
	  $lastname = $data['payment']['0']['lastname'];
	   $firstname = $data['payment']['0']['firstname'];
	      $message = $data['payment']['0']['sms_text'];
		  $mpesaamount = $data['payment']['0']['amount'];
		   $exactime = $data['payment']['0']['exactime'];
	  $data['transactioncode']=$transactioncode ;
	  $data['mpesaamount']=$mpesaamount ;
	   $data['phone']=$myphone;

  $data['salesid']=$salesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code is:' .$transactioncode.'; Amount: '.$mpesaamount.'; Name: '.$firstname." ".$lastname.'; Phone: '.$myphone.';Payment Date:' .$exactime.'  </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'?transactioncode='.$transactioncode.'&mpesaamount='.$mpesaamount);	

	 
 }else{
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') does not exist or belong to different branch..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
  
  

	}
 
 
 
 
 
 
  public function getpaymentDebtors() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
	
if($restricttill=="yes"){
	  $data['payment'] = $this->usermodel->populatependingpaymentbybranch($phone,$branchid);

}else{
	  $data['payment'] = $this->usermodel->populatependingpayment($phone);

}
   








//
 if($data['payment']!=false){
	 $myphone = $data['payment']['0']['sender_number'];
	 $transactioncode = $data['payment']['0']['code'];
	  $lastname = $data['payment']['0']['lastname'];
	   $firstname = $data['payment']['0']['firstname'];
	      $message = $data['payment']['0']['sms_text'];
		  $mpesaamount = $data['payment']['0']['amount'];
		   $exactime = $data['payment']['0']['exactime'];
	  $data['transactioncode']=$transactioncode ;
	  $data['mpesaamount']=$mpesaamount ;
	   $data['phone']=$myphone;

  $data['salesid']=$salesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code is:' .$transactioncode.'; Amount: '.$mpesaamount.'; Name: '.$firstname." ".$lastname.'; Phone: '.$myphone.';Payment Date:' .$exactime.'  </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'&transactioncode='.$transactioncode.'&mpesaamount='.$mpesaamount);	

	 
 }else{
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') does not exist or belong to different branch..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
  
  

	}
 
 
 
 
 
 
 
 
 
  public function saveinsurance() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   			  		  $dateposted = date('Y-m-d H:i:s');

	$code = trim($this->input->post("code"));

    $name = $this->input->post("name");
	  	 $rate = $this->input->post("rate");
			 	  	 $description = $this->input->post("description");

			 

			 	  		  		  $this->form_validation->set_rules("code", "Code", "trim|required|xss_clean");

			 
			 
			 
   	if ($this->input->post('btn_Insurance') == "Insurance")
					   {
						  



$configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
						   }											
							
						  
						  
						  
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
			  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


 


if($onlineoffline=="OSCU"){
        $apiUrl = ''.$etimsurl.'/etims-api/saveBhfInsurance';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/branches/saveBrancheInsurances';

			 }
			

						  
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $apiUrl);
        curl_setopt($curl, CURLOPT_HTTPHEADER,
            array('Content-Type:application/json')); //setting custom header


 $data = [
			'tin' => $kra_pin,
            'bhfId' => $branch_id,
            "isrccCd" => $code,
            "isrccNm" => $name,
            "isrcRt" => $rate,
            "useYn" => "Y",
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
			
        ];
       

      // Convert the data to JSON format
        $jsonData = json_encode($data);
        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Execute the cURL request
        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($curl)) {

            
			
			  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS code list:'.curl_error($curl).'. Try again </div>');
								
						   redirect('user/viewetiminitialize');
						   

						   
						   return false;
		


        } else {
            // Process the API response as needed
            //return $response;
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];



            if ($resultCd == '000') {
                $data = $responseArray['data']['info'];
				
                //$signkey = $responseArray['data']['info']['cmcKey'];
                $pin = $responseArray['data']['info']['tin'];
                $branchOpenDate = $responseArray['data']['info']['bhfOpenDt'];
                $sdc_id = $responseArray['data']['info']['sdcId'];
                $mrc_no = $responseArray['data']['info']['mrcNo'];
                $cmc_key = $responseArray['data']['info']['cmcKey'];
				
			
				
				       $data = array(
	   	   	'code'=>$code,
	   	'name'=>$name,

	   	'rate'=>$rate,
		
			'description'=>$description,
				
							'createdate'=>$dateposted,
							'branchid'=>$branchid,



             );
				
				
				
				
				
				
				
				
					$usr_result = $this->usermodel->add($data,'insurance');
							
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the data ..</div>');	
							redirect('user/viewetimsinsurance');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Process failed.. Try again</div>');
								
							redirect('user/viewetimsinsurance');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetiminitialize');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetiminitialize');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetiminitialize');	
					   }
				
				   
						   
		}   
				



				}
					   else
					   {
							redirect('login/admin');
					   }
					   
					   
					
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 public function initializeetims() {
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	    	$data['id'] = $session_data['id'];
         $userid = $data['id'];
	   
	   
	$tin = ($this->input->post("tin"));
	  		  		  //$this->form_validation->set_rules("tin", "KRA PIN", "trim|required|xss_clean");

    $bhfId = $this->input->post("bhfid");
	  	     $dvcsrlNo = $this->input->post("dvcsrlNo");
			 	  	     //$url = trim($this->input->post("url"));
			 	  	     $etimsurl =($this->input->post("url"));

			 	  	     $name = $this->input->post("name");
	$invoice = $userid.time()+ 1;
			 
			  		  $dateposted = date('Y-m-d H:i:s');
$bhfId = sprintf('%02d', $bhfId);
			  //$bhfId= (string)$bhfId;
			    $tin= (string)$tin;
				  $dvcsrlNo= (string)$dvcsrlNo;
			   $url= (string)$url;
			   
			   
			   
     

	 
   	if ($this->input->post('btn_Initialize') == "Initialize")
					   {
						   
						   
						   
				
						   $onlineoffline = trim($this->input->post("onlineoffline"));
						   if($onlineoffline=="OSCU"){
							   
							   $url = $etimsurl.'/etims-api/selectInitOsdcInfo';

						   }else{
							   
							$url = ''.$etimsurl.'/initializer/selectInitInfo';
					

					//$url = "http://localhost:8088/initializer/selectInitInfo";    
						   }
						   		   
					//echo $url."<br>";
						   
						   
						   
						   

        $curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER,
            array('Content-Type:application/json')); //setting custom header

        $curl_post_data = array(
            'tin' => $tin,
            'bhfId' => $bhfId,
            'dvcSrlNo' => $dvcsrlNo,
        );

        $data_string = json_encode($curl_post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

        //$results = curl_exec($curl);

        //$response = json_decode($results, true);
        // return $response;
        // Execute the cURL request
        $response = curl_exec($curl);
	


        // Check for cURL errors
        if (curl_errno($curl)) {




			
			  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during ETIMS initialization:'.curl_error($curl).'. Try again </div>');
								
						   redirect('user/viewetiminitialize');
						   

						   
						   return false;
		


        } else {
            // Process the API response as needed
            //return $response;
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];



            if ($resultCd == '000') {
                $data = $responseArray['data']['info'];
				
                //$signkey = $responseArray['data']['info']['cmcKey'];
                $pin = $responseArray['data']['info']['tin'];
                $branchOpenDate = $responseArray['data']['info']['bhfOpenDt'];
                $sdc_id = $responseArray['data']['info']['sdcId'];
                $mrc_no = $responseArray['data']['info']['mrcNo'];
                $cmc_key = $responseArray['data']['info']['cmcKey'];
				
				  $configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$businesskey=$configuration[0]["businesskey"];	
				
				       $data = array(
	   	   	'tin'=>$pin,
	   	'bhfid'=>$bhfId,

	   	'bhfOpenDt'=>$branchOpenDate,
			   	'url'=>$etimsurl,
	'userid'=>$userid,
			'sdcId'=>$sdc_id,
											'onlineoffline'=>$onlineoffline,

					'name'=>$name,
					'businesskey'=>$businesskey,
				'bhfSttsCd'=>$invoice,
					'mrcNo'=>$mrc_no,
			'cmcKey'=>$cmc_key,
							'createdate'=>$dateposted,

'companyid'=>1,
	'branchid'=>$branchid,

             );
				
				
				
				
				
				
				
				
					$usr_result = $this->usermodel->add($data,'etiminitialization');
							
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully initialized the serial ..</div>');	
							redirect('user/viewetiminitialize');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Process failed.. Try again</div>');
								
							redirect('user/viewetiminitialize');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetiminitialize');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetiminitialize');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetiminitialize');	
					   }
				
				   
						   
		}   
				



				}
					   else
					   {
							redirect('login/admin');
					   }
					   
					   
					
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
  }
 
 
 
 
 
 
 
 
 
 
  public function initializeetims_old() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	    	$data['id'] = $session_data['id'];
         $userid = $data['id'];
	   
	   
	$tin = trim($this->input->post("tin"));
	  		  		  $this->form_validation->set_rules("tin", "KRA PIN", "trim|required|xss_clean");

    $bhfId = $this->input->post("bhfid");
	  	     $dvcsrlNo = $this->input->post("dvcsrlNo");
			 	  	     //$url = trim($this->input->post("url"));
			 	  	     $etimsurl = trim($this->input->post("url"));

			 	  	     $name = $this->input->post("name");
	$invoice = $userid.time()+ 1;
			 
			  		  $dateposted = date('Y-m-d H:i:s');

			 
			 
			 
   	if ($this->input->post('btn_Initialize') == "Initialize")
					   {
						   
						   
						   
				
						   $onlineoffline = trim($this->input->post("onlineoffline"));
						   if($onlineoffline=="OSCU"){
							   
							   $url = $etimsurl.'/etims-api/selectInitOsdcInfo';

						   }else{
							   
							$url = ''.$etimsurl.'/initializer/selectInitInfo';
					

					//$url = "http://localhost:8088/initializer/selectInitInfo";    
						   }
						   		   
					//echo $url."<br>";
						   
						   
						   
						   

        $curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER,
            array('Content-Type:application/json')); //setting custom header

        $curl_post_data = array(
            'tin' => $tin,
            'bhfId' => $bhfId,
            'dvcSrlNo' => $dvcsrlNo,
        );

        $data_string = json_encode($curl_post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

        //$results = curl_exec($curl);

        //$response = json_decode($results, true);
        // return $response;
        // Execute the cURL request
        $response = curl_exec($curl);
	


        // Check for cURL errors
        if (curl_errno($curl)) {




			
			  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during ETIMS initialization:'.curl_error($curl).'. Try again </div>');
								
						   redirect('user/viewetiminitialize');
						   

						   
						   return false;
		


        } else {
            // Process the API response as needed
            //return $response;
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];



            if ($resultCd == '000') {
                $data = $responseArray['data']['info'];
				
                //$signkey = $responseArray['data']['info']['cmcKey'];
                $pin = $responseArray['data']['info']['tin'];
                $branchOpenDate = $responseArray['data']['info']['bhfOpenDt'];
                $sdc_id = $responseArray['data']['info']['sdcId'];
                $mrc_no = $responseArray['data']['info']['mrcNo'];
                $cmc_key = $responseArray['data']['info']['cmcKey'];
				
				  $configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$businesskey=$configuration[0]["businesskey"];	
				
				       $data = array(
	   	   	'tin'=>$pin,
	   	'bhfid'=>$bhfId,

	   	'bhfOpenDt'=>$branchOpenDate,
			   	'url'=>$etimsurl,
	'userid'=>$userid,
			'sdcId'=>$sdc_id,
											'onlineoffline'=>$onlineoffline,

					'name'=>$name,
					'businesskey'=>$businesskey,
				'bhfSttsCd'=>$invoice,
					'mrcNo'=>$mrc_no,
			'cmcKey'=>$cmc_key,
							'createdate'=>$dateposted,

'companyid'=>1,
	'branchid'=>$branchid,

             );
				
				
				
				
				
				
				
				
					$usr_result = $this->usermodel->add($data,'etiminitialization');
							
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully initialized the serial ..</div>');	
							redirect('user/viewetiminitialize');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Process failed.. Try again</div>');
								
							redirect('user/viewetiminitialize');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetiminitialize');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetiminitialize');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetiminitialize');	
					   }
				
				   
						   
		}   
				



				}
					   else
					   {
							redirect('login/admin');
					   }
					   
					   
					
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function requestetimscodelist() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$mydate = trim($this->input->post("mydate"));
	  		  		  $this->form_validation->set_rules("mydate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			 $currentDate =date('YmdHis');
			 
			 
			 
			 
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_ETIMSCODELIST') == "ETIMSCODELIST")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
						   }											
							
						  
						  
				$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
				  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

			if($onlineoffline=="OSCU"){
			$apiUrl = ''.$etimsurl.'/etims-api/selectCodeList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/code/selectCodes';

			 }
						   		
 
	
	
	// API endpoint URL
//
            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
				// "lastReqDt" => $currentDate
				"lastReqDt" => "20180722212803"


            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS code list:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
				
				
				
            } else {
                // Process the API response as needed
                //return $response;
                $responseArray = json_decode($response, true);

                $resultCd = $responseArray['resultCd'];
                $resultMsg = $responseArray['resultMsg'];
                $resultDt = $responseArray['resultDt'];
				

				
				if ($resultCd == '000') {

                   // //\Log::debug('eTims Codes fetech and  Response.', $responseArray);

                    $itemClsList = $responseArray['data']['clsList'];
                    // $itemlistcount =count((array)$responseArray['data']['clsList']);
                    if (isset($responseArray['data']['clsList']) && is_array($responseArray['data']['clsList'])) {
                        $itemlistcount =count((array)$responseArray['data']['clsList']);
                    } else {
                        // Handle the case where the data is not an array or doesn't exist
                        $itemlistcount = 0; // You can set a default count or handle the error in another way.
                    }
                    ////\Log::debug('eTims Codes fetch count  and  Response.', ['count' => $itemlistcount]);
					

					

					
					
					
					
				
					
                    foreach ($itemClsList as $detail) {
	

                        //Store Taxes
                        if ($detail['cdCls'] === '04') {
													$this->usermodel->truncatemydata("taxcodes");		

                            //\Log::debug('eTims Found taxes');
                            $taxList = $detail['dtlList'];
							
                            foreach ($taxList as $taxdetail) {
                               // $exists = Tax::where('tax_code', $taxdetail['cd'])->exists();
                             
									
								       $taxcodesdata = array(
										'company_id' => 1,
                                        'name' => $taxdetail['cdNm'],
                                        'tax_code' => $taxdetail['cd'],
                                        'sort_order' => $taxdetail['srtOrd'],
                                        'rate' => $taxdetail['userDfnCd1'],
                                        'rate_code2' => $taxdetail['userDfnCd2'],
                                        'description' => $taxdetail['cdDesc']

										);
				
				
					$usr_result = $this->usermodel->add($taxcodesdata,'taxcodes');	
									
									
									
									
									
									
									
									
									
                                
								

                            }

                        }

                    	
                        if ($detail['cdCls'] === '05') {
						$this->usermodel->truncatemydata("nation");		

                            //\Log::debug('eTims Store Countries');
                            $countryList = $detail['dtlList'];
							
                            foreach ($countryList as $countrydetail) {
                              
										$countrycodes = array(
                                        'name' => $countrydetail['cdNm'],
                                        'code' => $countrydetail['cd'],
                                        'description' => $countrydetail['cdDesc'],
                                        'status' => $countrydetail['useYn']
                               		);
										

				
							$usr_result = $this->usermodel->add($countrycodes,'nation');	
									
									

                            }

                        }


                        //Payment Types
                        if ($detail['cdCls'] === '07') {
													$this->usermodel->truncatemydata("paymentcodes");		

                            //\Log::debug('eTims Store Payments Fetched');
                            $paymentList = $detail['dtlList'];
							//var_dump($detail);
							////echo "000000007";
						//exit;
                            foreach ($paymentList as $paymentdetail) {
                              	$paymentcodes = array(
                                        'name' => $paymentdetail['cdNm'],
                                        'code' => $paymentdetail['cd'],
                                        'sort_order' => $paymentdetail['srtOrd'],
                                        'description' => $paymentdetail['cdDesc'],
                                        'status' => $paymentdetail['useYn']
										    		);
										

				
							$usr_result = $this->usermodel->add($paymentcodes,'paymentcodes');	
								
                             
                            }
                        }

                        //Quantity Units
                        if ($detail['cdCls'] === '10') {
																	$this->usermodel->truncatemydata("quantitycodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $quantityList = $detail['dtlList'];
                            foreach ($quantityList as $quantitydetail) {
                              $quantitycodes = array(
                                        'company_id' => 1,
                                        'name' => $quantitydetail['cdNm'],
                                        'code' => $quantitydetail['cd'],
                                        'sort_order' => $quantitydetail['srtOrd'],
                                        'description' => $quantitydetail['cdDesc'],
                                        'status' => $quantitydetail['useYn']
										);

							$usr_result = $this->usermodel->add($quantitycodes,'quantitycodes');	
								
							}
                            

                            

                        }

                        //Sale Status
                        if ($detail['cdCls'] === '11') {
														$this->usermodel->truncatemydata("salestatuscodes");		

                            //\Log::debug('eTims Sale Status Fetched');
                            $saleStatusList = $detail['dtlList'];
                            foreach ($saleStatusList as $saleStatusdetail) {
                            $saleStatuscodes = array(
                                        'name' => $saleStatusdetail['cdNm'],
                                        'code' => $saleStatusdetail['cd'],
                                        'sort_order' => $saleStatusdetail['srtOrd'],
                                        'description' => $saleStatusdetail['cdDesc'],
                                        'status' => $saleStatusdetail['useYn']
                              				);
											

							$usr_result = $this->usermodel->add($saleStatuscodes,'salestatuscodes');	
								
							}
                            

                            

                        }

                        //Stock I/O types
                        if ($detail['cdCls'] === '12') {
															$this->usermodel->truncatemydata("stocktypecodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $stockTypeList = $detail['dtlList'];
                            foreach ($stockTypeList as $stockTypedetail) {
                                 $stockTypecodes = array(
                                        'name' => $stockTypedetail['cdNm'],
                                        'code' => $stockTypedetail['cd'],
                                        'sort_order' => $stockTypedetail['srtOrd'],
                                        'description' => $stockTypedetail['cdDesc'],
                                        'status' => $stockTypedetail['useYn']
                                   				);

							$usr_result = $this->usermodel->add($stockTypecodes,'stocktypecodes');	
								
							}
                            

                        }

                        //Transaction Type

                        if ($detail['cdCls'] === '14') {
																$this->usermodel->truncatemydata("transtypecodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $transTypeList = $detail['dtlList'];
                            foreach ($transTypeList as $transTypdetail) {
                                     $transTypecodes = array(

                                        'name' => $transTypdetail['cdNm'],
                                        'code' => $transTypdetail['cd'],
                                        'sort_order' => $transTypdetail['srtOrd'],
                                        'description' => $transTypdetail['cdDesc'],
                                        'status' => $transTypdetail['useYn']
                                       				);
													

							$usr_result = $this->usermodel->add($transTypecodes,'transtypecodes');	
								
							}
                            

                            

                        }

                        //Packing Unit (itemPackaging)
                        if ($detail['cdCls'] === '17') {
							
															$this->usermodel->truncatemydata("packagingcodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $packagingList = $detail['dtlList'];
                            foreach ($packagingList as $packagingdetail) {
                              
									 $packagingcodes = array(

                                        'name' => $packagingdetail['cdNm'],
                                        'code' => $packagingdetail['cd'],
                                        'sort_order' => $packagingdetail['srtOrd'],
                                        'description' => $packagingdetail['cdDesc'],
                                        'status' => $packagingdetail['useYn']
                                             				);
															
															
						
							$usr_result = $this->usermodel->add($packagingcodes,'packagingcodes');	
								
							}
                            

                            

                        }

                        //Refund Reasons
                        if ($detail['cdCls'] === '32') {
																						$this->usermodel->truncatemydata("refundreasoncodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $refundreasonList = $detail['dtlList'];
                            foreach ($refundreasonList as $refundreasondetail) {
                                	 $refundreasoncodes = array(

                                        'name' => $refundreasondetail['cdNm'],
                                        'code' => $refundreasondetail['cd'],
                                        'sort_order' => $refundreasondetail['srtOrd'],
                                        'description' => $refundreasondetail['cdDesc'],
                                        'status' => $refundreasondetail['useYn']
                                                 				);
																
																
																
									
							$usr_result = $this->usermodel->add($refundreasoncodes,'refundreasoncodes');	
								
							}
                            

                        }
                        //Currency
                        if ($detail['cdCls'] === '33') {
							
														$this->usermodel->truncatemydata("currencycodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $currencyList = $detail['dtlList'];
                            foreach ($currencyList as $currencydetail) {
                               $currencycodes = array(
                                        'name' => $currencydetail['cdNm'],
                                        'code' => $currencydetail['cd'],
                                        'symbol' => $currencydetail['cd'],
                                        'sort_order' => $currencydetail['srtOrd'],
                                        'description' => $currencydetail['cdDesc'],
                                        'status' => $currencydetail['useYn']
                                               				);
															

							$usr_result = $this->usermodel->add($currencycodes,'currencycodes');	
								
                            }

                        }

                        //Purchase Status
                        if ($detail['cdCls'] === '34') {
								$this->usermodel->truncatemydata("purchasecodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $purchaseList = $detail['dtlList'];
                            foreach ($purchaseList as $purchasedetail) {
                                 $purchasecodes = array(
                                        'name' => $purchasedetail['cdNm'],
                                        'code' => $purchasedetail['cd'],
                                        'sort_order' => $purchasedetail['srtOrd'],
                                        'description' => $purchasedetail['cdDesc'],
                                        'status' => $purchasedetail['useYn']
                                               				);
															

							$usr_result = $this->usermodel->add($purchasecodes,'purchasecodes');	
								
                            }
                        }

                        //Reason of Inventory Adjustment
                        if ($detail['cdCls'] === '35') {
							
															$this->usermodel->truncatemydata("adjustmentcodes");		

                            //\Log::debug('eTims Quantity Units Fetched');
                            $adjustmentList = $detail['dtlList'];
                            foreach ($adjustmentList as $adjustmentdetail) {
                                    $adjustmentcodes = array(
                                        'name' => $adjustmentdetail['cdNm'],
                                        'code' => $adjustmentdetail['cd'],
                                        'sort_order' => $adjustmentdetail['srtOrd'],
                                        'description' => $adjustmentdetail['cdDesc'],
                                        'status' => $adjustmentdetail['useYn']
                                   				);
												

							$usr_result = $this->usermodel->add($adjustmentcodes,'adjustmentcodes');	
								
                            }

                        }

                        //Banks
                        if ($detail['cdCls'] === '36') {
							
															$this->usermodel->truncatemydata("bankcodes");		

                            //\Log::debug('eTims Bank Accounts Fetched');
                            $bankList = $detail['dtlList'];
                            foreach ($bankList as $bankdetail) {
                                    $bankcodes = array(

                                        'name' => $bankdetail['cdNm'],
                                        'code' => $bankdetail['cd'],
                                        'sort_order' => $bankdetail['srtOrd'],
                                        'description' => $bankdetail['cdDesc'],
                                        'status' => $bankdetail['useYn']
                           		);

							$usr_result = $this->usermodel->add($bankcodes,'bankcodes');	
								

                        }


                    }
                  
					

                } 
				
						  $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					  <strong>Error!  </strong>Code list retrieved Successfully </div>');
								
						 redirect('user/viewetimscodelist');
						   

						   
						  return false;
				
				
		}else {
			echo "error ocured";
                   // return $this->sendResponse(null, $resultMsg);

                }
				
				
				
				
				
				
				
				
				
			}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

						}
					   else
					   {
							redirect('login/admin');
					   }
					   
					   
					
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
  }
 
 
 
 
 
 
 
 
 
  public function downloadetimspurchase() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
	   
	$fromdate = trim($this->input->post("fromdate"));
	  		  		  $this->form_validation->set_rules("fromdate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			// $currentDate =date('YmdHis');
			 
			 	 $currentDate = date("YmdHis", strtotime($fromdate));

			
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_downloadetimpurchases') == "downloadetimpurchases")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
						   }											
							
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
			  
						  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

if($onlineoffline=="OSCU"){
       $apiUrl = ''.$etimsurl.'/etims-api/selectTrnsPurchaseSalesList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/trnsPurchase/selectTrnsPurchaseSales';

			 }
			   
				

 
	        // API endpoint URL
       // $apiUrl = env('ETIMS_URL', ''.$etimsurl.'/etims-api/') . 'selectTrnsPurchaseSalesList';


        // Data to send in the JSON format
        $data = [
		   "tin" => $kra_pin,
                "bhfId" => $branch_id,
				
            "lastReqDt" =>$currentDate
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);


        // Initialize cURL session
        $ch = curl_init();


            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);

			
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS purchases:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewpurchases');
						   

						   
						   return false;
				
				
				
            } else {
                // Process the API response as needed
                //return $response;
                $responseArray = json_decode($response, true);

                $resultCd = $responseArray['resultCd'];
                $resultMsg = $responseArray['resultMsg'];
                $resultDt = $responseArray['resultDt'];
				

				
			       if ($resultCd == '000') {

               // \Log::debug('Get Purchases From Etims successful');

                $psaleList = $responseArray['data']['saleList'];
				
		//var_dump($psaleList);
		//exit;
                foreach ($psaleList as $detail) {
   
   
   

						  $exists= $this->usermodel->populateallarray('purchaseorder','invoice',$detail['spplrInvcNo']);
			
                     if ($exists==false) {

                   // if ($exists) {

                    
						  $supplier= $this->usermodel->populateallarray('people','idnumber',$detail['spplrTin']);

                        if ($supplier ==false) {
                        
						
						       $savesupplier = array(
                                'companyid' => $companyid,
                                'branchid' => $branchid,
                                'company' => $detail['spplrNm'],
                                'idnumber' => $detail['spplrTin'],
                                'box' => $detail['spplrMrcNo'],
                                'town' => $detail['spplrSdcId'],
                                'city' => $detail['spplrBhfId'],
								'category' => "supplier",
								'firstname' =>  $detail['spplrNm'],
                            );
                       $this->usermodel->add($savesupplier,'people');

                        }
						  $getsupplier= $this->usermodel->populateallarray('people','idnumber',$detail['spplrTin']);
						$supplier_id=$getsupplier[0]["id"];	   
                       
						    $savepurchase = array(
                            'companyid' => $companyid,
                            'userid' => $userid,
                            'branchid' => $branchid,
                            'supplier' => $supplier_id,
                           // 'purchase_no' => $purchase_no,
                           // 'refNo' => $uniqueRef,
                            'invoice' => $detail['spplrInvcNo'],
                            'createdate' => $detail['cfmDt'],
                            'fromdate' => $detail['cfmDt'],
							 'paiddate' => $detail['cfmDt'],

							// 'createdate' => $detail['stockRlsDt'],

                            'qty' => $detail['totItemCnt'],
                            'description' => 'etims-purchase',
                            'remarks' => $detail['rcptTyCd'],
                            'deliverymethod' => $detail['pmtTyCd'],
                            'EXEMPTED' => $detail['taxblAmtA'],
                            'taxblAmtB' => $detail['taxblAmtB'],
                            'ZERORATED' => $detail['taxblAmtC'],
                            'taxblAmtD' => $detail['taxblAmtD'],
                            'taxblAmtE' => $detail['taxblAmtE'],
                            'taxRtA' => $detail['taxRtA'],
                            'vatrate' => $detail['taxRtB'],
                            'taxRtC' => $detail['taxRtC'],
                            'taxRtD' => $detail['taxRtD'],
                            'taxRtE' => $detail['taxRtE'],
							
							"taxAmtA" => $detail['taxAmtA'],
							"taxAmtB" =>$detail['taxAmtB'],
							"taxAmtC" => $detail['taxAmtC'],
							"taxAmtD" => $detail['taxAmtD'],
							"taxAmtE" => $detail['taxAmtE'],
							

                            'taxable' => $detail['totTaxblAmt'],
                            'vat' => $detail['totTaxAmt'],
                            'amount' => $detail['totAmt'],
                            'remarks' => $detail['remark'],
                            'transactionstatus' => 'open',
                            'status' => 'purchases',
							 'approvalstatus' => 'new',

                            'paiddate' => $fromdate,

                          );
                       $this->usermodel->add($savepurchase,'purchaseorder');


                        $sitemlist = $detail['itemList'];
                        foreach ($sitemlist as $itemdetail) {

						    $savepurchaseitems = array(
								'invoice' => $detail['spplrInvcNo'],
								'invoice_number' => $detail['spplrInvcNo'],
                                'date' => $detail['cfmDt'],
								'item_id1' => $itemdetail['itemCd'],
                                'name' => $itemdetail['itemNm'],
                                'item_id' => $itemdetail['itemCd'],
								 'itemClsCd' => $itemdetail['itemClsCd'],
								  'uom' => $itemdetail['qtyUnitCd'],
								  'itemSeq' => $itemdetail['itemSeq'],

								 'description' =>$itemdetail['itemClsCd']." ".$itemdetail['pkg']." ".$itemdetail['qtyUnitCd'] ,

                                'total' => $itemdetail['qty'],
                                'discount' => 0,
								'itemstatus' => "etims",

                                'buyingprice' => $itemdetail['prc'],
                                'pkgUnitCd' => $itemdetail['pkgUnitCd'],
								'taxTyCd' => $itemdetail['taxTyCd'],
                                //'tax' => $itemdetail['taxTyCd'],

                                'taxable' => $itemdetail['taxblAmt'],
                                'vat' => $itemdetail['taxAmt'],
                              );
                       $this->usermodel->add($savepurchaseitems,'newstock');

                        }
                    }

                }

	  $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					  <strong>Error!  </strong> Etims purchase has been received Successfully </div>');
								
						 redirect('user/viewpurchases');
						   

						   
						  return false;
            }else{
				
				  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					  <strong>Error!  </strong> Etims purchase was not received .. Try again or there is no new purchase </div>');
								
						 redirect('user/viewpurchases');
						   

						   
						  return false;	
				
			}

        }

        // Close the cURL session
        curl_close($ch);
				
			
 
 
	  }
					   
					   
  }
 
 
 
 
 
  public function downloadetimspurchaseimports() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
	   
	$fromdate = trim($this->input->post("fromdate"));
	  		  		  $this->form_validation->set_rules("fromdate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			// $currentDate =date('YmdHis');
			 
			 	 $currentDate = date("YmdHis", strtotime($fromdate));

			
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_downloadetimpurchasesimports') == "downloadetimpurchasesimports")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
						   }											
							
						  
						  $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


if($onlineoffline=="OSCU"){
         $apiUrl = ''.$etimsurl.'/etims-api/selectImportItemList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/imports/selectImportItems';

			 }
			   


        // Data to send in the JSON format
        $data = [
		   "tin" => $kra_pin,
                "bhfId" => $branch_id,
            "lastReqDt" =>$currentDate
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);


        // Initialize cURL session
        $ch = curl_init();


            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS purchases:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewpurchases');
						   

						   
						   return false;
				
				
				
            } else {
                // Process the API response as needed
                //return $response;
                $responseArray = json_decode($response, true);

                $resultCd = $responseArray['resultCd'];
                $resultMsg = $responseArray['resultMsg'];
                $resultDt = $responseArray['resultDt'];
				

				
			
			       if ($resultCd == '000') {

                $importedIitemList = $responseArray['data']['itemList'];

                if (isset($responseArray['data']['itemList']) && is_array($responseArray['data']['itemList'])) {
                    $itemlistcount =count((array)$responseArray['data']['itemList']);
                } else {
                    // Handle the case where the data is not an array or doesn't exist
                    $itemlistcount = 0; // You can set a default count or handle the error in another way.
                }

                foreach ($importedIitemList as $detail) {
   
						  $exists= $this->usermodel->populateallarray('purchaseorder','invoice',$detail['taskCd']);
						  
        $date = DateTime::createFromFormat('dmY', $detail['dclDe']);
      $importdate = $date->format('Y-m-d H:i:s');
       // Output: 01-02-2024
    
						  
						  
					  
						  
						  
						  
						  
					
				
                    if ($exists ==false) {

                    
						  $supplier= $this->usermodel->populateallarray('people','company',$detail['spplrNm']);

                        if ($supplier ==false) {
                        
						
						       $savesupplier = array(
                                'companyid' => $companyid,
                                'branchid' => $branchid,
                                'company' => $detail['spplrNm'],
                               // 'idnumber' => $detail['spplrTin'],
                               // 'box' => $detail['spplrMrcNo'],
                               // 'town' => $detail['spplrSdcId'],
                               // 'city' => $detail['spplrBhfId'],
								'category' => "supplier",
								'firstname' =>  $detail['spplrNm'],
                            );
                       $this->usermodel->add($savesupplier,'people');

                        }
						  $getsupplier= $this->usermodel->populateallarray('people','company',$detail['spplrNm']);
						$supplier_id=$getsupplier[0]["id"];	   
                                               $purchaseprice = ($detail['invcFcurAmt'] / $detail['qty']) * $detail['invcFcurExcrt'];

						    $savepurchase = array(
                            'companyid' => $companyid,
                            'userid' => $userid,
                            'branchid' => $branchid,
                            'supplier' => $supplier_id,
                            'remarks' => $detail['itemNm'],
                            'ordernumber' => $detail['dclNo'],
                            'invoice' => $detail['taskCd'],
                            'createdate' => $importdate,
                            'fromdate' => $importdate,
                            'fob' => $detail['agntNm'],

                            'qty' => $detail['qty'],
                            'description' => 'etims-imports',
                            'deliverymethod' => $detail['exptNatCd'],
                         
                            'amount' => $detail['invcFcurAmt'],
                            'transactionstatus' => 'open',
                            'status' => 'purchases',
							 'approvalstatus' => 'new',

                            'paiddate' => $fromdate,

                          );
                       $this->usermodel->add($savepurchase,'purchaseorder');


                       


						    $savepurchaseitems = array(
								'invoice' => $detail['taskCd'],
								'invoice_number' => $detail['taskCd'],
								'taskCd' => $detail['taskCd'],
								'itemSeq' => $detail['itemSeq'],
                                'name' => $detail['itemNm'],
                                //'item_id' => $detail['hsCd'],
								'imptItemsttsCd' => $detail['imptItemsttsCd'],
								'item_id1' => $detail['hsCd'],
								 'description' =>$detail['imptItemsttsCd']." ".$detail['pkg']." ".$detail['qtyUnitCd']." ".$detail['totWt'] ." ".$detail['netWt'] ." ".$detail['invcFcurAmt'] ." ".$detail['invcFcurCd']." ".$detail['qtyUnitCd'] ,


                                'total' => $detail['qty'],
                                'discount' => 0,
								'itemstatus' => "etims",
                                'date' => $importdate,
								'buyingprice' => round($purchaseprice, 2),

                                'uom' => $detail['pkgUnitCd'],
                                //'tax' => $detail['taxTyCd'],
                                //'taxable' => $detail['taxblAmt'],
                               // 'vat' => $detail['taxAmt'],
                              );
                       $this->usermodel->add($savepurchaseitems,'newstock');

                        
                    }

                }

	  $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					  <strong>Error!  </strong> Etims purchase has been received Successfully </div>');
								
						 redirect('user/viewpurchases');
						   

						   
						  return false;
            }else{
				
				  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					  <strong>Error!  </strong> Etims purchase was not received .. Try again or there is no new purchase </div>');
								
						 redirect('user/viewpurchases');
						   

						   
						  return false;	
				
			}

        }

        // Close the cURL session
        curl_close($ch);
				
			
 
 
	  }
					   
					   
  }
 
 
 
 
	
 
 
 
 
 
 
 
 
  
  public function requestItemclassification() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$mydate = trim($this->input->post("mydate"));
	  		  		  $this->form_validation->set_rules("mydate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			 $currentDate =date('YmdHis');
			 
			 
			 
			 
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_ETIMSCLASSIFICATION') == "ETIMSITEMCLASSIFICATION")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimsitemclassification');
						   

						   
						   return false;
						   }											
							
						  
						  
						  
					$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
			  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


 if($onlineoffline=="OSCU"){
            $apiUrl = ''.$etimsurl.'/etims-api/selectItemClsList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/itemClass/selectItemsClass';

			 }
				
	
	
	// API endpoint URL

            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
			 // "lastReqDt" => $currentDate
                "lastReqDt" => "20150722212803"

            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS Items classifications:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewetimsitemclassification');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
				$itemClsList = $responseArray['data']['itemClsList'];
					$this->usermodel->truncatemydata("itemclassification");		

			foreach ($itemClsList as $detail) {
				
                        
						
				       $itemclassificationdata = array(
                                'name' => $detail['itemClsNm'],
                                'itm_class_code' => $detail['itemClsCd'],
                                'itm_class_level' => $detail['itemClsLvl'],
                                'tax_type_code' => $detail['taxTyCd'],
                                'status' => $detail['useYn'],
                                 );
                        
				
			
				
				
					$usr_result = $this->usermodel->add($itemclassificationdata,'itemclassification');
					}
							
							
					
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully retrived the imes classifications ..</div>');	
							redirect('user/viewetimsitemclassification');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Process failed.. Try again</div>');
								
							redirect('user/viewetimsitemclassification');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetimsitemclassification');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetimsitemclassification');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetimsitemclassification');	
					   }
				
				   
				
				
				
				
				
			}
	
	
	
	

						}
					   else
					   {
							redirect('login/admin');
					   }
					   
	 
  }
 
 
 
 
 
 	
		public function viewetiminitializemain()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");

	

			$this->load->view('userdata/viewetiminitializemain',$data);
		$this->load->view("template/footerpage");
	}
 
 
 
 
 
 
 
 
 
  public function requestetimsbranches() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$mydate = trim($this->input->post("mydate"));
	  		  		  $this->form_validation->set_rules("mydate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			 $currentDate =date('YmdHis');
			 
			 
			 
			 
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_ETIMSBRANCHES') == "ETIMSBRANCHES")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimsitemclassification');
						   

						   
						   return false;
						   }	

$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
						  
							  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);



	

	// API endpoint URL

if($onlineoffline=="OSCU"){
			$apiUrl = ''.$etimsurl.'/etims-api/selectBhfList';
			

			 }else{
		
			$apiUrl = $etimsurl.'/branches/selectBranches';
 

			 }
				





            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
                "lastReqDt" => "20150722212803"
				
            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);

		//var_dump($response);
	//	exit;
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS Items classifications:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewetimsitemclassification');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
				$branchlistData = $responseArray['data']['bhfList'];
					$this->usermodel->truncatemydata("branchlist");		

			foreach ($branchlistData as $detail) {
				
                        
						
				       $branchlist = array(
                                'tin' => $detail['tin'],
                                'bhfId' => $detail['bhfId'],
                                'bhfNm' => $detail['bhfNm'],
                                'bhfSttsCd' => $detail['bhfSttsCd'],
                                'prvncNm' => $detail['prvncNm'],
								  'dstrtNm' => $detail['dstrtNm'],
								  
								     'sctrNm' => $detail['sctrNm'],
                                'locDesc' => $detail['locDesc'],
                                'mgrNm' => $detail['mgrNm'],
                                'mgrTelNo' => $detail['mgrTelNo'],
                                'mgrEmail' => $detail['mgrEmail'],
								  'hqYn' => $detail['hqYn'],



                                 );
                        
				
			
				
				
					$usr_result = $this->usermodel->add($branchlist,'branchlist');
					}
							
							
					
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully retrived the etims branches ..</div>');	
							redirect('user/viewetimsbranches');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Process failed.. Try again</div>');
								
							redirect('user/viewetimsbranches');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetimsbranches');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetimsbranches');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetimsbranches');	
					   }
				
				   
				
				
				
				
				
			}
	
	
	
	

						}
					   else
					   {
							redirect('login/admin');
					   }
					   
	 
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function requestetimsnotices() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$mydate = trim($this->input->post("mydate"));
	  		  		  $this->form_validation->set_rules("mydate", "Current date", "trim|required|xss_clean");

			 
			  		  $dateposted = date('Y-m-d H:i:s');

			 $currentDate =date('YmdHis');
			 
			 
			 
			 
			 
			 
			
			 
			 
			 
			 
			 
   	if ($this->input->post('btn_ETIMSNOTICES') == "ETIMSNOTICES")
					   {
						   
						   
						   
						   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewetimsitemclassification');
						   

						   
						   return false;
						   }											
							
						$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		  
						  
						  
						  
						  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


 
	
	
	// API endpoint URL


if($onlineoffline=="OSCU"){
	        $apiUrl = ''.$etimsurl.'/etims-api/selectNoticeList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/notices/selectNotices';

			 }
				






            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
			 // "lastReqDt" => $currentDate
                "lastReqDt" => "20150722212803"

            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS Items notices:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewetimsnotices');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			



            if ($resultCd == '000') {
				$noticeList = $responseArray['data']['noticeList'];
					$this->usermodel->truncatemydata("noticelist");		

			foreach ($noticeList as $detail) {
				
                        
						
				       $noticelist = array(
                                'noticeNo' => $detail['noticeNo'],
                                'title' => $detail['title'],
                                'cont' => $detail['cont'],
                                'dtlUrl' => $detail['dtlUrl'],
                                'regrNm' => $detail['regrNm'],
								  'regDt' => $detail['regDt'],



                                 );
                        
				
			
				
				
					$usr_result = $this->usermodel->add($noticelist,'noticelist');
					}
							
							
					
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully retrived the Etims notices ..</div>');	
							redirect('user/viewetimsnotices');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Notices  failed.. Try again</div>');
								
							redirect('user/viewetimsnotices');	
							}
					  

					  
					  
					  
					  }else if ($resultCd == '901') { 
					  		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
												  <strong>Error!</strong> Not avalid device. Check details.. Try again..</div>');


								
							redirect('user/viewetimsnotices');	
					  
					  }else if ($resultCd == '902') { 
					   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						<strong>Error!</strong> Device already Initialized.. Try again</div>');
								
							redirect('user/viewetimsnotices');	
					  
					 
					  
					  }
					   else
					   {
							
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The initilaization process failed . Try again</div>');
								
							redirect('user/viewetimsnotices');	
					   }
				
				   
				
				
				
				
				
			}
	
	
	
	

						}
					   else
					   {
							redirect('login/admin');
					   }
					   
	 
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function getpaymentsdkpush1() {
	  
	  
	  	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $finalsalesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");
	  	     $amount = $this->input->post("finaltotals");

	  $configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];



   if (isset($_GET['invoice_number'])){
	  
      $invoice_number= $_GET['invoice_number'];
	        $myview= $_GET['myview'];

	  $data['payment'] = $this->usermodel->populatependingpaymentFromEcitizenDirect($invoice_number);
	  
	  
	  
	  
	   if($data['payment']!=false){
	 $myphone = $data['payment']['0']['sender_number'];
	 $transactioncode = $data['payment']['0']['code'];
	  $lastname = $data['payment']['0']['lastname'];
	   $firstname = $data['payment']['0']['firstname'];
	      $message = $data['payment']['0']['sms_text'];
		  $mpesaamount = $data['payment']['0']['amount'];
		   $exactime = $data['payment']['0']['exactime'];
	  $data['transactioncode']=$transactioncode ;
	  $data['mpesaamount']=$mpesaamount ;
	   $data['phone']=$myphone;

  $data['salesid']=$finalsalesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code is:' .$transactioncode.'; Amount: '.$mpesaamount.'; Name: '.$firstname." ".$lastname.'; Phone: '.$myphone.';Payment Date:' .$exactime.'  </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'?transactioncode='.$transactioncode.'&mpesaamount='.$mpesaamount);	

	 
 }else{
	 
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Invoice No('.$invoice_number.') does not exist or has tas not been paid /Received.. Try again  </div>');
	redirect($myview,$data);	
 }
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  


   }else{




	
if($restricttill=="yes"){
	  $data['payment'] = $this->usermodel->populatependingpaymentbybranchEcitizen($phone,$branchid,$finalsalesid);

}else{
	  $data['payment'] = $this->usermodel->populatependingpaymentEcitizen($phone,$finalsalesid);

}
   
   }
 

//
 if($data['payment']!=false){
	 $myphone = $data['payment']['0']['sender_number'];
	 $transactioncode = $data['payment']['0']['code'];
	  $lastname = $data['payment']['0']['lastname'];
	   $firstname = $data['payment']['0']['firstname'];
	      $message = $data['payment']['0']['sms_text'];
		  $mpesaamount = $data['payment']['0']['amount'];
		   $exactime = $data['payment']['0']['exactime'];
	  $data['transactioncode']=$transactioncode ;
	  $data['mpesaamount']=$mpesaamount ;
	   $data['phone']=$myphone;

  $data['salesid']=$finalsalesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code is:' .$transactioncode.'; Amount: '.$mpesaamount.'; Name: '.$firstname." ".$lastname.'; Phone: '.$myphone.';Payment Date:' .$exactime.'  </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'?transactioncode='.$transactioncode.'&mpesaamount='.$mpesaamount);	

	 
 }else{
	 /*
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') does not exist or belong to different branch..try again  </div>');
	redirect($myview,$data);	
		 
   
	  
	  */
	  





	$apiClientID = "244";
$amount = $amount;
$ServiceID = "194494";
$clientIDNumber = "20242023";
$currency = "KES";
$billRefNumber = $finalsalesid;
$billDesc = "FOOD";
$clientName = "STUDENT";
$secret = "1FaPNFnB6IN5TU/2zhofLtgJH1OYVias";  // Note that the secret is directly used here
$key ="Bsn5RB7qBLEhZFXR";




	/*
// Your input data
$apiClientID = "162";
$amount = $amount;
$ServiceID = "6525886";
$clientIDNumber = "20242023";
$currency = "KES";
$billRefNumber = $finalsalesid;
$billDesc = "FOOD";
$clientName = "STUDENT";
$secret = "9MsfesrK1Ay7Uk8GY1klrn36lphZdBIm";  // Note that the secret is directly used here
$key ="gESTMy65UKolLaIq";
*/
// Construct your data string
$data_string = $apiClientID.$amount.$ServiceID.$clientIDNumber.$currency.$billRefNumber.$billDesc.$clientName.$secret;

  
	 // echo $finalsalesid;
	//  exit;

						//$callbaseurl ="https://mainerp.robisearch.com/user/viewsales?transactioncode=SAK7JAGLGP&mpesaamount=1.00";

						$callbaseurl = base_url()."user/viewsales?sdkphone=1";






$url = "https://payments.ecitizen.go.ke/PaymentAPI/iframev2.1.php";

//$url = "https://test.pesaflow.com/PaymentAPI/iframev2.1.php";

$secure_hash = base64_encode(hash_hmac('sha256', $data_string, $key));

   // "notificationURL" =>"https://mainerp.robisearch.com/user/getpaymentsdkpush?invoice_number=201705724489",
   					$notificationURL = "https://mainerp.robisearch.com/getecitizenpayment";
					   						//$notificationURL = base_url()."getecitizenpayment";



  $data = array(  
	
	"apiClientID"=>$apiClientID,
    "secureHash"=>$secure_hash,
    "ServiceID"=>$ServiceID,
    "billDesc"=>$billDesc,
    "billRefNumber"=>$billRefNumber,
    "currency"=>"KES",
    "clientMSISDN"=>$phone,
    "clientName"=>$clientName,
    "clientIDNumber"=>$clientIDNumber,
    "clientEmail"=>"kise@gmail.com",
    "callBackURLOnSuccess" =>$callbaseurl,
    "notificationURL" =>$notificationURL,
    "amountExpected" =>$amount,
    "format"=>"json",
    "sendSTK"=>"true"
	
  );
  $payload = json_encode($data);


	
	
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
  $curl_response = curl_exec($curl);
  


    $result = json_decode(($curl_response));
	
	
	

 

    $result = json_decode(json_encode(json_decode($curl_response)), true);

//var_dump($result["invoice_number"]);
//var_dump($result["invoice_link"]);

						$callbaseurl = base_url()."user/viewsales?sdkphone=".$phone;

	
	
	
	  $data['salesid']=$salesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code/ Acc No is:' .$result["invoice_number"].' Try refresh or press eneter to confirm payment </div>');
	//redirect('user/viewsales',$data);	
		redirect($myview.'?sdkphone='.$phone.'&invoice_number='.$result["invoice_number"]);	
	
	
	
	
	
	
	//redirect(($result["invoice_link"]));	
	//redirect(($result["invoice_link"]));	


//exit;





 }

	  
  }
 
 
 
 
 
 
 
  
  public function getpaymentsdkpush_MAIN() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	$amount = trim($this->input->post("total"));

	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
$myconsumer_key=$configuration[0]["consumer_key"];
$myconsumer_secret=$configuration[0]["consumer_secret"];
$shortcode=$configuration[0]["shortcode"];
$confirmationurl=$configuration[0]["confirmationurl"];
$passkey=$configuration[0]["responseType"];

$errors  = array();
$errmsg  = '';



	  #Callback url
	 // define('LNMO_CALLBACK_URL', 'https://abansacco.co.ke/include/callback_url.php?orderid=');

	  # access token
	 $consumerKey =$myconsumer_key; //Fill with your app Consumer Key
	 $consumerSecret = $myconsumer_secret; // Fill with your app Secret

	  # provide the following details, this part is found on your test credentials on the developer account
	  $BusinessShortCode = $shortcode; //business short code
	  $Passkey = $passkey; //live passkey
	  $phone = preg_replace('/^0/', '254', str_replace("+", "", $phone));
	  $PartyA = $phone; // This is your phone number,
	  $PartyB = $shortcode;
	  $TransactionDesc = 'Pay Order'; //Insert your own description
	  # Get the timestamp, format YYYYmmddhms -> 20181004151020
	  $Timestamp = date('YmdHis');    
	  # Get the base64 encoded string -> $password. The passkey is the M-PESA Public Key
	  $Password = base64_encode($shortcode.$passkey.$Timestamp);
	  # header for access token
	  $headers = ['Content-Type:application/json; charset=utf8'];
 





	  # M-PESA endpoint urls
	  $access_token_url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
	  $initiate_url = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest';  

	  $curl = curl_init($access_token_url);
	  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	  curl_setopt($curl, CURLOPT_HEADER, FALSE);
	  curl_setopt($curl, CURLOPT_USERPWD, $consumerKey.':'.$consumerSecret);
	  $result = curl_exec($curl);
	  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	  $result = json_decode($result);
	 // $access_token = $result->access_token;  
    $access_token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";




	  curl_close($curl);

	  # header for stk push
	  $stkheader = ['Content-Type:application/json','Authorization:Bearer '.$access_token];
	  # initiating the transaction

	  $curl = curl_init();
	  curl_setopt($curl, CURLOPT_URL, $initiate_url);
	  curl_setopt($curl, CURLOPT_HTTPHEADER, $stkheader); //setting custom header
	  
	  $curl_post_data = array(

		//Fill in the request parameters with valid values
		'BusinessShortCode' => $shortcode,
		'Password' => $Password,
		'Timestamp' => $Timestamp,
		'TransactionType' => 'CustomerBuyGoodsOnline', // 
		'Amount' => $amount,
		'PartyA' => $phone,
		'PartyB' => $shortcode,
		'PhoneNumber' => $phone,
		'CallBackURL' => $confirmationurl,
		'AccountReference' => "".$_POST['invoice']."",
		'TransactionDesc' => "pos payments"
	  );

	  $data_string = json_encode($curl_post_data);
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	  curl_setopt($curl, CURLOPT_POST, true);
	  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
	  $curl_response = curl_exec($curl);


		$result = json_decode(json_encode(json_decode($curl_response)), true);

	  $ResponseCode = $result['ResponseCode'];
	  return $ResponseCode;




    //if($result['ResponseCode'] === "0"){









	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') could be wrong or there is configuration error..try again  </div>');
	redirect($myview,$data);	

  }
 
 
 
	public function viewmaincategoryofdocuments()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	
		$data['viewproductcategory']= $this->usermodel->populatealldatawhere('documentcategory','id','ASC','companyid',$companyid);

				$this->load->view('userdata/viewmaincategoryofdocuments',$data);
		$this->load->view("template/footerpage");
	}
	
	
		
  public function adddocumentcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");

		   	  $description = $this->input->post("description");
			  
		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmaincategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adddocumentcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'documentcategory');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new Document Category..</div>');	
							redirect('user/viewmaincategoryofdocuments');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Document  Category was not added.. Try again</div>');
								
								 redirect('user/viewmaincategoryofdocuments');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	
	
  public function updatdocumentcategory()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
		         $exactime = date('Y-m-d H:i:s');

 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $name = $this->input->post("name");
		 		 $mycategoryid = $this->input->post("mycategoryid");

		   	  $description = $this->input->post("description");
			  		   	  $status = $this->input->post("status");

		    
		
				
			  		  $this->form_validation->set_rules("name", "Product name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewmaincategory', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatedocumentcategory') == "category")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
			 	'companyid'=>$companyid,
						'status'=>$status,

			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->updatedata($data,'documentcategory','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								$mycustomer=$this->usermodel->populateallarray('people','id', $userid);


			$myname=$mycustomer[0]['firstname'];

		 $actiondone=$myname ." Updated item with id ". $mycategoryid." from  documentcategory table at ".$exactime;
								   $mydata = array(
									
									  'userid' => $userid,
									  		'ip' => $this->input->ip_address(),		
																		  	  'companyid' => $companyid,

									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
								 			  	 $this->usermodel->add($mydata,'activityloggs');
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the  document category..</div>');	
							redirect('user/viewmaincategoryofdocuments');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> document main Category  was not Updated.. Try again</div>');
								
								 redirect('user/viewmaincategoryofdocuments');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
		public function searchdocuemntsbycategory()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $frotime="00:00:00am";
	  $totime="23:59:59pm";
	   $category = $this->input->post("category");
	  $fromdate = $this->input->post("fromdate");
	  	  $branchname = $this->input->post("branchname");
		
	  $todate = $this->input->post("todate");

	  $daterange = $this->input->post("daterange");
	
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	$finalfromdate=$fromdate;
	$finaltodate=$todate;
	$data['finaltodate']=$finaltodate;
		$data['finalfromdate']=$finalfromdate;
	$data['supplier']="all";
			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['viewdocuments'] = $this->usermodel->searchdocuemntsbycategory($fromdate,$todate,$companyid,$category,$branchname,$daterange);
		  $data['total_rows']=count($data['viewdocuments']);
		  $data['links']=1;

				$this->load->view('userdata/viewdocuments',$data);
		$this->load->view("template/footerpage");
	}
	
	
 
 
  public function getpaymentsdkpush() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	$amount = trim($this->input->post("total"));

	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
$myconsumer_key=$configuration[0]["consumer_key"];
$myconsumer_secret=$configuration[0]["consumer_secret"];
$shortcode=$configuration[0]["shortcode"];
$confirmationurl=$configuration[0]["confirmationurl"];
$passkey=$configuration[0]["responseType"];

$errors  = array();
$errmsg  = '';
/*
$config = array(

//

    "env"              => "live",
    "BusinessShortCode"=> $shortcode,
    "key"              => $myconsumer_key, //Enter your consumer key here
    "secret"           => $myconsumer_secret, //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	 "code" => $shortcode, // business short code
	  "till" => responseType,
	  "initiator" => "cashier", // optional initiator name
	"credential" => "levi-cred++==" , // optional security credential

    "passkey"          => $passkey, //Enter your passkey here
    "CallBackURL"      => $confirmationurl, //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);


*/


/*
$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "4956000",
    "key"              => "cUKRTIfdj4l02VSyyBsQggcFz3b4LY52BSBvCycOnyU7fAf7", //Enter your consumer key here
    "secret"           => "A4e1qzuGP1bSNooALFFSXCLL9ZDt0xJZzuPlkaJJoaiBMxIXWtwNr0tfa2bU4fyV", //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	
    "passkey"          => "16acf8f91f75b4f9766eb50f7f5d686cea54e6032ab69c01f08b26fd46605fd0", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);

*/


$config = array(
    "env"              => "live",
    "BusinessShortCode"=> $shortcode,
	
	"key"              => $myconsumer_key, //Enter your consumer key here
    "secret"           => $myconsumer_secret, //Enter your consumer secret here
    "username"         => "",
   // "TransactionType"  => "CustomerPayBillOnline",
	"TransactionType"  => "CustomerBuyGoodsOnline",

    "passkey"          => $passkey, //Enter your passkey here
    "CallBackURL"      => $confirmationurl, //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);


/*

$errors  = array();
$errmsg  = '';

$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "4079491",
    "key"              => "6ZTfjQGGySUWUxLnB4IUzmZy3AbD8Zkp", //Enter your consumer key here
    "secret"           => "E2fGPbNy9JzHC93N", //Enter your consumer secret here
    "username"         => "judiest",
    "TransactionType"  => "complete",
    "passkey"          => "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using Localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "Bulk SMS" ,
);

*/

if (isset($_POST['phone'])) {

    $phone = $_POST['phone'];
    $orderNo = $_POST['invoice'];
   // $amount = 5;

    $phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;



    $access_token = ($config['env']  == "live") ? "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" : "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"; 
    $credentials = base64_encode($config['key'] . ':' . $config['secret']); 
    
    $ch = curl_init($access_token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic " . $credentials]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    echo $response = curl_exec($ch);
    curl_close($ch);
	
	
	

    $result = json_decode($response); 
    $token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";

    $timestamp = date("YmdHis");
    $password  = base64_encode($config['BusinessShortCode'] . "" . $config['passkey'] ."". $timestamp);

    $curl_post_data = array( 
        "BusinessShortCode" => $config['BusinessShortCode'],
        "Password" => $password,
        "Timestamp" => $timestamp,
        "TransactionType" => $config['TransactionType'],
        "Amount" => $amount,
        "PartyA" => $phone,
        //"PartyB" => "772740",
		//"PartyB" => $config['totalsms'],
		 "PartyB" => $configuration[0]["totalsms"],

        "PhoneNumber" => $phone,
        "CallBackURL" => $config['CallBackURL'],
        "AccountReference" => $config['AccountReference'],
        "TransactionDesc" => $config['TransactionDesc'],
    ); 

    $data_string = json_encode($curl_post_data);

    $endpoint = ($config['env'] == "live") ? "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest" : "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"; 

    $ch = curl_init($endpoint );
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer '.$token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   echo $response     = curl_exec($ch);
    curl_close($ch);

    $result = json_decode(json_encode(json_decode($response)), true);

    if(!preg_match('/^[0-9]{10}+$/', $phone) && array_key_exists('errorMessage', $result)){
        $errors['phone'] = $result["errorMessage"];
    }
	

    if($result['ResponseCode'] === "0"){
		
		
		 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Request has been sent to phone No:('.$phone.') . Kindly key in your pin to complete the sale.  </div>');
	redirect($myview,$data);
		
		
		return false;
		
		
        //STK Push request successful
        
        $MerchantRequestID = $result['MerchantRequestID'];
        $CheckoutRequestID = $result['CheckoutRequestID'];

        $conn = mysqli_connect("localhost","root","","mpesa");
       
        $sql = "INSERT INTO orders(ID, OrderNo, Amount, Phone, CheckoutRequestID, MerchantRequestID) VALUES ('','".$orderNo."','".$amount."','".$phone."','".$CheckoutRequestID."','".$MerchantRequestID."');";
        
        if ($conn->query($sql) === TRUE){
            $_SESSION["MerchantRequestID"] = $MerchantRequestID;
            $_SESSION["CheckoutRequestID"] = $CheckoutRequestID;
            $_SESSION["phone"] = $phone;
            $_SESSION["orderNo"] = $orderNo;

            header('location: confirm-payment.php');
        }else{
            $errors['database'] = "Unable to initiate your order Please contact Kemru on system@kemrut.com: ".$conn->error;;  
            foreach($errors as $error) {
                $errmsg .= $error . '<br />';
            } 
        }
        
    }else{
        $errors['mpesastk'] = $result['errorMessage'];
        foreach($errors as $error) {
            $errmsg .= $error . '<br />';
        }
    }
    
}





	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') could be wrong or there is configuration error..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
  
  

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function getpaymentsdkpush______() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	   
	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];

   
$errors  = array();
$errmsg  = '';

$config = array(



    "env"              => "live",
    "BusinessShortCode"=> "6811821",
    "key"              => "G3p5qG76c9M3P7wJTZHn7vSGHqEfwmaCyQCrIk6lp4SxFAcf", //Enter your consumer key here
    "secret"           => "eHZAR6HP0oIJAUoBz5rDalnd1mgyIrvPI4fl6Q0XVvZDX38RbYqvAhGtKNPnTwYK", //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	 "code" => "6811821", // business short code
	  "till" => "4235838",
	  "initiator" => "levizwannah", // optional initiator name
	"credential" => "levi-cred++==" , // optional security credential

    "passkey"          => "eadf11070cb71a81b13dfc31b9dd754d6ada9075a46a2dc292d3bfd0ace363b2", //Enter your passkey here
    "CallBackURL"      => "http://kicas.robisearch.com/getpayment", //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);




/*
$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "5017639",
    "key"              => "Ek12dMymcl3AtHSQIy4BAhUK5QLelZm2", //Enter your consumer key here
    "secret"           => "mDIef2sGIDMqjcLv", //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	
    "passkey"          => "763987b5a070372631fe9610e3a6c45ad96be9110f9390caa29b1db3983d0e8f", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);




$errors  = array();
$errmsg  = '';

$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "4079491",
    "key"              => "6ZTfjQGGySUWUxLnB4IUzmZy3AbD8Zkp", //Enter your consumer key here
    "secret"           => "E2fGPbNy9JzHC93N", //Enter your consumer secret here
    "username"         => "judiest",
    "TransactionType"  => "complete",
    "passkey"          => "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using Localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "Bulk SMS" ,
);

*/

if (isset($_POST['phone'])) {

    $phone = $_POST['phone'];
    $orderNo = $_POST['invoice'];
    $amount = 5;

    $phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;



    $access_token = ($config['env']  == "live") ? "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" : "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"; 
    $credentials = base64_encode($config['key'] . ':' . $config['secret']); 
    
    $ch = curl_init($access_token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic " . $credentials]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    echo $response = curl_exec($ch);
    curl_close($ch);
	
	
	

    $result = json_decode($response); 
    $token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";

    $timestamp = date("YmdHis");
    $password  = base64_encode($config['BusinessShortCode'] . "" . $config['passkey'] ."". $timestamp);

    $curl_post_data = array( 
        "BusinessShortCode" => $config['BusinessShortCode'],
        "Password" => $password,
        "Timestamp" => $timestamp,
        "TransactionType" => $config['TransactionType'],
        "Amount" => $amount,
        "PartyA" => $phone,
        "PartyB" => $config['BusinessShortCode'],
        "PhoneNumber" => $phone,
        "CallBackURL" => $config['CallBackURL'],
        "AccountReference" => $config['AccountReference'],
        "TransactionDesc" => $config['TransactionDesc'],
    ); 

    $data_string = json_encode($curl_post_data);

    $endpoint = ($config['env'] == "live") ? "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest" : "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"; 

    $ch = curl_init($endpoint );
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer '.$token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   echo $response     = curl_exec($ch);
    curl_close($ch);

    $result = json_decode(json_encode(json_decode($response)), true);

    if(!preg_match('/^[0-9]{10}+$/', $phone) && array_key_exists('errorMessage', $result)){
        $errors['phone'] = $result["errorMessage"];
    }
	
exit;
    if($result['ResponseCode'] === "0"){
        //STK Push request successful
        
        $MerchantRequestID = $result['MerchantRequestID'];
        $CheckoutRequestID = $result['CheckoutRequestID'];

        $conn = mysqli_connect("localhost","root","","mpesa");
       
        $sql = "INSERT INTO orders(ID, OrderNo, Amount, Phone, CheckoutRequestID, MerchantRequestID) VALUES ('','".$orderNo."','".$amount."','".$phone."','".$CheckoutRequestID."','".$MerchantRequestID."');";
        
        if ($conn->query($sql) === TRUE){
            $_SESSION["MerchantRequestID"] = $MerchantRequestID;
            $_SESSION["CheckoutRequestID"] = $CheckoutRequestID;
            $_SESSION["phone"] = $phone;
            $_SESSION["orderNo"] = $orderNo;

            header('location: confirm-payment.php');
        }else{
            $errors['database'] = "Unable to initiate your order Please contact Kemru on system@kemrut.com: ".$conn->error;;  
            foreach($errors as $error) {
                $errmsg .= $error . '<br />';
            } 
        }
        
    }else{
        $errors['mpesastk'] = $result['errorMessage'];
        foreach($errors as $error) {
            $errmsg .= $error . '<br />';
        }
    }
    
}

























	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') does not exist or belong to different branch..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
  
  

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function bulkproductcreateserials() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
   
			
$description = $this->input->post("description");

			
$sellingprice = $this->input->post("sellingprice");
$buyingprice = $this->input->post("buyingprice");
$qty = $this->input->post("qty");
$otherserial = $this->input->post("otherserial");
$serial = $this->input->post("serial");			
	$mydate = $this->input->post("mydate");			
	$code = $this->input->post("code");
$name = $this->input->post("name");
$invoice = $this->input->post("finalsalesid");
$itemid = $this->input->post("myid");
$branch = $this->input->post("branch");	
$name = $this->input->post("name");	
$batchno = $this->input->post("batchno");	
$myqty = $this->input->post("myqty");
$finalid = $this->input->post("finalid");	
	$mybranchid = $this->input->post("mybranchid");	

$finaloldqty=0;
		$view = $this->input->post("view");	
			$mainview = $this->input->post("mainview");	
			$id = $this->input->post("id");	
			$status = $this->input->post("status");	
		 $confirmqty= $this->usermodel->viewserialconfirmation($companyid,$finalid);
$finaloldqty=$confirmqty[0]["qty"];

	$currentqty=0;
	
		$finalcurrentqty=0;

   	if ($this->input->post('btn_bulkproductsreceiving') == "bulkinsertserials")
					   {
	


			$data = array();
			
			 $count =count((array)$itemid);

   for($i=0; $i< $count; $i++) {
	   
	   
	   	$currentqty=$currentqty+$qty[$i];
	
       $data[] = array(
	   	'invoice'=>$invoice[$i],
			   	'companyid'=>$companyid,
			   	'userid'=>$userid,

		'code'=>$code[$i],
				'description'=>$description[$i],
				'batchno'=>$batchno[$i],

	   	'itemid'=>$itemid[$i],
	'branch'=>$branch[$i],
		'sellingprice'=>$sellingprice[$i],
			'buyingprice'=>$buyingprice[$i],
				'qty'=>$qty[$i],
					'serial'=>$serial[$i],
			'createdate'=>$mydate[$i],
						'name'=>$name[$i],

					'otherserial'=>$otherserial[$i],

             );
			 	
  		//$usr_result = $this->usermodel->add($data,'serials');

   }
   
 
   	  $usr_result =$this->db->insert_batch('serials', $data); 



        if($this->db->affected_rows() > 0)
	{
		
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added products   ..</div>');	
							redirect($mainview);																
							}else {
							   

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Products were not added into the system.. Try again</div>');
								
							redirect($mainview);																
							}
		
		
	}
  }
 
 
 
 
 
 
 
 
 
  public function bulkrequistion() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
  
			
$description = $this->input->post("description");
$taskid = $this->input->post("taskid");
$subtaskid = $this->input->post("subtaskid");			

			
$bprice = $this->input->post("bprice");
$qty = $this->input->post("qty");
	$code = $this->input->post("code");
$invoice = $this->input->post("invoice");
$itemid = $this->input->post("myid");
$branch = $this->input->post("branch");	



   	if ($this->input->post('btn_bulkrequst') == "bulkinsertrquest")
					   {
	


			$data = array();
			
			
			  $selector = $this->input->post("selector");
					
			
			
			
			
			 $count =count((array)$selector);

   for($i=0; $i< $count; $i++) {
	   
	   
	   	//$currentqty=$currentqty+$qty[$i];
	
       $data[] = array(
	   
			   	'companyid'=>$companyid,
			   	'userid'=>$userid,
			   	'invoice'=>$invoice,
			   	'subtaskid'=>$subtaskid,
			   	'taskid'=>$taskid,

		'code'=>$code[$i],
				'description'=>$description[$i],
	
	'branch'=>$branchid,

			'bprice'=>$bprice[$i],
				'qty'=>$qty[$i],
			'createdate'=>$dateposted,
				

             );
			 	
  		//$usr_result = $this->usermodel->add($data,'serials');

   }
   
 
   	  $usr_result =$this->db->insert_batch('requisitionitems', $data); 



        if($this->db->affected_rows() > 0)
	{
		
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted the request    ..</div>');	
							redirect("user/viewprojets");																
							}else {
							   

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Request was not saved. Try again</div>');
								
							redirect("user/viewprojets");																
							}
		
		
	}
  }
 
 
 
 
 
 
 
  public function bulkproductsreceivings() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
   
			
$description = $this->input->post("description");

			
$sellingprice = $this->input->post("sellingprice");
$buyingprice = $this->input->post("buyingprice");
$qty = $this->input->post("qty");
$otherserial = $this->input->post("otherserial");
$serial = $this->input->post("serial");			
	$mydate = $this->input->post("mydate");			
	$code = $this->input->post("code");
$name = $this->input->post("name");
$invoice = $this->input->post("finalsalesid");
$itemid = $this->input->post("myid");
$branch = $this->input->post("branch");	
$name = $this->input->post("name");	
$batchno = $this->input->post("batchno");	
$myqty = $this->input->post("myqty");
$finalid = $this->input->post("finalid");	
	$mybranchid = $this->input->post("mybranchid");	

$finaloldqty=0;
		$view = $this->input->post("view");	
			$mainview = $this->input->post("mainview");	
			$id = $this->input->post("id");	
			$status = $this->input->post("status");	
			
			$finalsalesid = $this->input->post("invoice");
	$mainsupplier = $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
		  		  	  
 $supplier=$mainsupplier[0]['supplier'];


		 $confirmqty= $this->usermodel->viewserialconfirmation($companyid,$finalid);
$finaloldqty=$confirmqty[0]["qty"];

	$currentqty=0;
	
		$finalcurrentqty=0;

   	if ($this->input->post('btn_bulkproductsreceiving') == "bulkinsert")
					   {
	


			$data = array();
			
			 $count =count((array)$itemid);

   for($i=0; $i< $count; $i++) {
	   $testserail= $this->usermodel->geteserials($serial[$i],$branchid);


	   if($testserail !=false){
		   
		      	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> The  serials you are trying to add so far ('.$serial[$i].')  exist..  .try again.</div>');	
																						
			redirect($view);
			false;
	   }
	   
	   	$currentqty=$currentqty+$qty[$i];
	
       $data[] = array(
	   	'invoice'=>$invoice[$i],
			   	'companyid'=>$companyid,
			   	'userid'=>$userid,

		'code'=>$code[$i],
				'description'=>$supplier,
				'batchno'=>$batchno[$i],

	   	'itemid'=>$itemid[$i],
	'branch'=>$branch[$i],
		'sellingprice'=>$sellingprice[$i],
			'buyingprice'=>$buyingprice[$i],
				'qty'=>$qty[$i],
					'serial'=>$serial[$i],
			'createdate'=>$mydate[$i],
						'name'=>$name[$i],

					'otherserial'=>$otherserial[$i],

             );
			 	
  		//$usr_result = $this->usermodel->add($data,'serials');

   }
   
    
	$finalcurrentqty=$currentqty+$finaloldqty;
 	   if( $finalcurrentqty>$myqty){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> The total serials you are trying to add so far ('.$finalcurrentqty.') are higher than the original quantity captured on the purchase ('.$myqty.') .try again.</div>');	
																						
			redirect($view);																
																			return false;
		 }
   	  $usr_result =$this->db->insert_batch('serials', $data); 



        if($this->db->affected_rows() > 0)
	{
		
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added products   ..</div>');	
							redirect($mainview);																
							}else {
							   

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Products were not added into the system.. Try again</div>');
								
							redirect($mainview);																
							}
		
		
	}else if ($this->input->post('btn_bulkproductsreceiving') == "bulkupdate")
					   {
	
			
			 $count =count((array)$itemid);

   for($i=0; $i< $count; $i++) {
	   
	   $data2[] =array(
      // $data = array(
	   	'invoice'=>$invoice[$i],
		
			   	'companyid'=>$companyid,
			   	'userid'=>$userid,

		'code'=>$code[$i],
						'description'=>$supplier,

				//'description'=>$description[$i],
				'batchno'=>$batchno[$i],
				'status'=>$status[$i],
	'id'=>$id[$i],
	   	'itemid'=>$itemid[$i],
	'branch'=>$mybranchid[$i],
		'sellingprice'=>$sellingprice[$i],
			'buyingprice'=>$buyingprice[$i],
				'qty'=>$qty[$i],
					'serial'=>$serial[$i],
			'createdate'=>$mydate[$i],
						'name'=>$name[$i],
	
					'otherserial'=>$otherserial[$i],

             );
			 	
  		//$usr_result = $this->usermodel->updatedata($data,'serials','id',$id[$i]);

   }
	   	 $usr_result =	$this->db->update_batch('serials',$data2, 'id');
	
		
		
			if($this->db->affected_rows() > 0)
						{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the products   ..</div>');	
							redirect($mainview);																
							}
							else 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Products were not updated into the system.. Try again</div>');
								
							redirect($mainview);																
							}
		
		
	}
  }
 
 
 
 
 
 
 
  public function bulkpsavinglabour() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
   
		$rate = $this->input->post("rate");
	
$myid = $this->input->post("myid");
$mainview = $this->input->post("mainview");

			
$slarymonth = $this->input->post("slarymonth");
$category = $this->input->post("category");
$qty = $this->input->post("qty");


   	if ($this->input->post('btn_bulklabours') == "bulkinsert")
					   {
	


			
			 $count =count((array)$myid);

   for($i=0; $i< $count; $i++) {
	   if($qty[$i] !=""){
		   
		   
	   $data2[] =array(
    
		
	
			
				'salary'=>$qty[$i]*$rate[$i],
			'id'=>$myid[$i],
	  

             );
			 	
	   }
   }
	   	 $usr_result =	$this->db->update_batch('people',$data2, 'id');
	
		
		
			if($this->db->affected_rows() > 0)
						{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the salary   ..</div>');	
							redirect("user/salaryhistory");																
							}
							else 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Salary were not updated into the system.. Try again</div>');
								
							redirect("user/salaryhistory");																
							}
		
		
	}
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function bulkproductsmissings() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
   
			
$description = $this->input->post("description");

			
$sellingprice = $this->input->post("sellingprice");
$buyingprice = $this->input->post("buyingprice");
$qty = $this->input->post("qty");
$otherserial = $this->input->post("otherserial");
$serial = $this->input->post("serial");			
	$mydate = $this->input->post("mydate");			
	$code = $this->input->post("code");
$name = $this->input->post("name");
$invoice = $this->input->post("finalsalesid");
$itemid = $this->input->post("myid");
$branch = $this->input->post("branch");	
$name = $this->input->post("name");	
$batchno = $this->input->post("batchno");	
$myqty = $this->input->post("myqty");
$finalid = $this->input->post("finalid");	
	$mybranchid = $this->input->post("mybranchid");	

$finaloldqty=0;
		$view = $this->input->post("view");	
			$mainview = $this->input->post("mainview");	
			$id = $this->input->post("id");	
			$status = $this->input->post("status");	
		 $confirmqty= $this->usermodel->viewserialconfirmation($companyid,$finalid);
$finaloldqty=$confirmqty[0]["qty"];

	$currentqty=0;
	
		$finalcurrentqty=0;

 if ($this->input->post('btn_bulkproductsreceiving') == "bulkupdatemissing")
					   {
	
			
			 $count =count((array)$itemid);

   for($i=0; $i< $count; $i++) {
       $data = array(
	  
				'status'=>$status[$i],

             );
			 	
  		$usr_result = $this->usermodel->updatedata($data,'serials','id',$id[$i]);

   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the products   ..</div>');	
							redirect($mainview);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Products were not updated into the system.. Try again</div>');
								
							redirect($mainview);																
							}
		
		
	}
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function updateserials() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		  $dateposted = date('Y-m-d H:i:s');
        	
   
		$status = $this->input->post("status");
	
$description = $this->input->post("description");

			
$sellingprice = $this->input->post("sellingprice");
$buyingprice = $this->input->post("buyingprice");
$qty = $this->input->post("qty");
$otherserial = $this->input->post("otherserial");
$serial = $this->input->post("serial");			
	$mydate = $this->input->post("mydate");			
	$code = $this->input->post("code");
$name = $this->input->post("name");
$invoice = $this->input->post("finalsalesid");
$itemid = $this->input->post("myid");
$branch = $this->input->post("branch");	
$name = $this->input->post("name");	
$batchno = $this->input->post("batchno");	

		$view = $this->input->post("view");	
			$mainview = $this->input->post("mainview");	
			 $id = $this->input->post("id");	
	
   
   if ($this->input->post('btn_updateserials') == "update")
					   {
									$confirmdata= $this->usermodel->populateallarray('serials','id',$id);

			


       $data = array(
	   	'invoice'=>$invoice,
			   	'companyid'=>$companyid,
			   	'userid'=>$userid,

		'code'=>$code,
				'description'=>$description,
				'batchno'=>$batchno,

	   	'itemid'=>$itemid,
	'branch'=>$branch,
		'sellingprice'=>$sellingprice,
			'buyingprice'=>$buyingprice,
				'qty'=>$qty,
					'serial'=>$serial,
			'createdate'=>$mydate,
						'name'=>$name,
					'status'=>$status,

					'otherserial'=>$otherserial,

             );
			 	
  		$usr_result = $this->usermodel->updatedata($data,'serials','id',$id);

   
		
			if ($usr_result ==TRUE) //active user record is present
							{
								

							$finalqty=0;
						  if ($confirmdata !=false)
						   {
							   
							   
						  $currentstatus=$confirmdata[0]['status'];
								
 
			  if($currentstatus!=$status){
				
			if($branch=="Main"){
								        		$productname = $this->usermodel->populateallarray('products','code', $code);

			}else{
				

				
				   								$productname = $this->usermodel->populatealldataarray('productlist','code', $code,'branch', $branch);

			}
		
					 
					 
   $productid=$productname[0]['id']; 

  
  
   $availableqty=$productname[0]['qty']; 
   
   
   	if($status=="new"){
   $finalqty=($availableqty+$qty);
	}else{
		
		
		  if(($currentstatus=="used") ||($currentstatus=="damaged")) {
			  	   $finalqty=($availableqty);

			  }else{
			  			  	   $finalqty=($availableqty-$qty);


			  }
			 

	
	}
												$myproductdata=array(		
												'qty'=>$finalqty,
													);
   
	 
	
			
				if($branch=="Main"){
					
										 $myusr_result =  $this->usermodel->updatedata($myproductdata,'products','id',$productid);

			}else{
				

				
										 $myusr_result =  $this->usermodel->updatedata($myproductdata,'productlist','id',$productid);

			}							
				

												



				

										}
							}
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the products   ..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Products were not updated into the system.. Try again</div>');
								
							redirect($view);																
							}
		
		
	}
  }
 
 
 
 
 
  
 
 public function updatereconciliation() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:s');
        
		  $dateposted = date('Y-m-d H:i:s');

   	if ($this->input->post('updatebakreconciliation') == "all")
					   {
	
   
			
			 $categoryid = $this->input->post("categoryid");
			
						 $salesid = $this->input->post("selector");

	 	 $bankname = $this->input->post("bankname");   
		 		 	 $balance = $this->input->post("balance");   

		 	 $startdate = $this->input->post("startdate");   
			     
			    $enddate = $this->input->post("enddate");   

						    $confirm = $this->input->post("confirm");   

									    $type = $this->input->post("type");   

												    $lastmonthbalance = $this->input->post("lastmonthbalance");   

			
			
			 $count =count((array)$salesid);

   for($i=0; $i< $count; $i++) {

			 
			 	$updateArray[] =array(	
		'id'=>$salesid[$i],
	 	'confirm'=>"Yes",
		
			'updatedat'=>$dateposted,
					'updatedby'=>$userid,
		);	

		  }


			 	
  		//$usr_result = $this->usermodel->updatedata($data,'debitcredit','id',$salesid[$i]);

   
   	 $RESULT =	$this->db->update_batch('debitcredit',$updateArray, 'id');

				if($this->db->affected_rows() > 0)
						{
			
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the sales banks  ..</div>');	
				 redirect("user/startreconciliation?bankname=".$bankname."&balance=".$balance."&startdate=".$startdate."&enddate=".$enddate."&type=".$type."&lastmonthbalance=".$lastmonthbalance);	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank was not updated.. Try again</div>');
								
				 redirect("user/startreconciliation?bankname=".$bankname."&balance=".$balance."&startdate=".$startdate."&enddate=".$enddate."&type=".$type."&lastmonthbalance=".$lastmonthbalance);	
							}
		
		
	}
	
	
	else{
		
		redirect("login");
	}
  }
	
 
 
 
 
 
 
 
 
 
 
 public function groupbycategory() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:s');
        		  $invoice = "";

		  $dateposted = date('Y-m-d H:i:s');
		  						  $mytype = strtolower($this->input->post("type"));
			  $categoryid = $this->input->post("categoryid");

		  
		  
		  	$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		  		  	  
 $activatebank=$smsconfig[0]['bankcode'];
 $finalaccount="";

	
		
		  
 	if ($this->input->post('groupbycategory') == "all")
					   {
	
   						 //$invoice = $this->input->post("invoice");

						 $mytable = $this->input->post("mytable");
						 $type = $this->input->post("type");

						 $selector = $this->input->post("selector");
//var_dump( $selector);
						 $cash = $this->input->post("cash");

						 $salesid = $this->input->post("selector");
						 $finaltotal = $this->input->post("finaltotal");

							 $view = $this->input->post("view");

			
			  $count =count((array)$selector);
			
	//
   for($i=0; $i< $count; $i++) {
	   		$money=$this->usermodel->getesmade($selector[$i]);
		$ttamount=$money[0]['total'];
	    $myinvoice=$money[0]['invoice'];
		
		
	   		if(	$type=="Cash"){
       $data = array(
	   'paymentstatus'=>$categoryid,
			///'ordersales'=>$ordersales,
		
			'updatedat'=>$dateposted,
					'updatedby'=>$userid,
					'type'=>$type,
				'ordersales'=>"printed",

             );
			}else{
				
				
				
				
				
			    $data = array(
	   	'paymentstatus'=>$categoryid,
			//'ordersales'=>$ordersales,
				'ordersales'=>"printed",

			'updatedat'=>$dateposted,
					'updatedby'=>$userid,

					'type'=>$type,
					"$type" =>$ttamount,

						//"$type" =>$finaltotal[$i],
						'cash'=>0,
             );	
				
			}
			
			
  		$usr_result = $this->usermodel->updatedata($data,'sales','id',$salesid[$i]);

			$roomsdata=array(		
			'updatedby'=>$userid,
			
			'updatedat'=>$dateposted,
				'status'=>$categoryid,
			
								);
		$this->usermodel->updatedata($roomsdata,'roomsales','invoice',$myinvoice);

										
			
		  			
						if($activatebank=="yes"){
$confirmaccounts = $this->usermodel->populatealldatanoarray('paymentmethodes','branchid', $branchid,'companyid', $companyid);
if(is_array($confirmaccounts)){
	   foreach($confirmaccounts as $row)
	   {
		   	$mybankname=$row->name;
		     $myaccountno=$row->type;
		   
		   if(($mybankname==$mytype) && ($ttamount != 0)){
		    $finalaccount =  $myaccountno=$row->type;
 
		   }
	   }
	   
}
	$updatedebitcredit=array(		
			'account'=>$finalaccount,
												
	);
	$this->usermodel->updatedatabytwo($updatedebitcredit,'debitcredit','code',$myinvoice,'type','Payment');
				}
		  	
   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the sales status  ..</div>');	
							redirect($view);																
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales were not updated.. Try again</div>');
								
							redirect($view);																
							}
		
		
	}else 	if ($this->input->post('groupbycategory') == "print")
					   {
	
   
						 $mytable = $this->input->post("mytable");
						 $type = $this->input->post("type");

						 $selector = $this->input->post("selector");
//var_dump( $selector);
			 $categoryid = $this->input->post("categoryid");
						 $cash = $this->input->post("cash");

						 $salesid = $this->input->post("selector");
						 $finaltotal = $this->input->post("finaltotal");

							 $view = $this->input->post("view");


			
			  $count =count((array)$selector);
		
			
			
	
   for($i=0; $i< $count; $i++) {
	   		$money=$this->usermodel->getesmade($selector[$i]);
		$ttamount=$money[0]['total'];
		$invoice=$money[0]['invoice'];
		$myinvoice=$money[0]['invoice'];

	    
	   		if(	$type=="Cash"){
       $data = array(
	   	'paymentstatus'=>$categoryid,
		
			'updatedat'=>$dateposted,
					'updatedby'=>$userid,
					'type'=>$type,
				'ordersales'=>"printed",

             );
			}else{
				
				
			    $data = array(
	   	'paymentstatus'=>$categoryid,
			'ordersales'=>"printed",

			'updatedat'=>$dateposted,
					'updatedby'=>$userid,

					'type'=>$type,
					"$type" =>$ttamount,

						//"$type" =>$finaltotal[$i],
						'cash'=>0,
             );	
				
			}
			
			
  		$usr_result = $this->usermodel->updatedata($data,'sales','id',$salesid[$i]);

			$roomsdata=array(		
			'updatedby'=>$userid,
			
			'updatedat'=>$dateposted,
				'status'=>$categoryid,
			
								);
		$this->usermodel->updatedata($roomsdata,'roomsales','invoice',$myinvoice);
		
		
				if($activatebank=="yes"){
$confirmaccounts = $this->usermodel->populatealldatanoarray('paymentmethodes','branchid', $branchid,'companyid', $companyid);
if(is_array($confirmaccounts)){
	   foreach($confirmaccounts as $row)
	   {
		   	$mybankname=$row->name;
		     $myaccountno=$row->type;
		   
		   if(($mybankname==$mytype) && ($ttamount != 0)){
		   echo $finalaccount =  $myaccountno=$row->type;
 
		   }
	   }
	   
}
	$updatedebitcredit=array(		
			'account'=>$finalaccount,
												
	);
	$this->usermodel->updatedatabytwo($updatedebitcredit,'debitcredit','code',$myinvoice,'type','Payment');
				}
		  				
					
		  			
								
								
								
					
		
		
		
		
		
		
		
		
		
		
		

   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
								
								
							
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
									//$invoice=$money[0]['invoice'];
 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the sales status  ..</div>');	
							redirect("user/printpending?invoice=".$invoice."&view=user/clearsales&receipt=receipts");
						
							
							//redirect("user/printreceipts?invoice=".$invoice);

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales were not updated.. Try again</div>');
								
							redirect($view);																
							}
		
		
	}else if ($this->input->post('mergebill') == "merge")
					   {
		
	
   
			
			 $categoryid = $this->input->post("categoryid");
						 $myinvoice = $this->input->post("myinvoice");

						 $salesid = $this->input->post("selector");

							 $myview = $this->input->post("myview");
							 $view = $this->input->post("view");

			
			
			$finaluserid=0;
						$finalbranchid=0;

					$ourtotal="";
			
			 $count =count((array)$salesid);

   for($i=0; $i< $count; $i++) {
	   	  $sales = $this->usermodel->populateallarray('sales','id',$salesid[$i]);
		 	  $salesinvoice=$sales[0]['invoice'];
			   $finaluserid=$sales[0]['userid'];
			   			   $finalbranchid=$sales[0]['branch'];

	   //$mysalesid=$salesid[$i];
	   $money=$this->usermodel->getesmade($salesid[$i]);
		$amount=$money[0]['total'];
	  
  					  		$ourtotal=(double)$ourtotal +(double)$amount;

       $data = array(
	   	   	'salesid'=>$salesid[$i],

	   	'type'=>"merge",
		
			'dateposted'=>$dateposted,
					'userid'=>$finaluserid,
'companyid'=>$companyid,
	'branchid'=>$finalbranchid,
										'invoice'=>$myinvoice,

             );
			 	
  		$usr_result = $this->usermodel->add($data,'splitbill');
		
				$mytype="";
		$mysalesperson="";
		$mytable="";
		$mysalestype="";


		$mycustomers="";
if ($usr_result ==TRUE){

	  $myid=$sales[0]['id'];			  
			  		$mycustomers=$sales[0]['customer'];
			  		$mytype=$sales[0]['type'];
								  		$mysalestype=$sales[0]['salestype'];

			  		$mysalesperson=$sales[0]['salesperson'];
		$mytable=$sales[0]['mytable'];
	$debitcreditdata = array(
			'code'=>$myinvoice,

             );
	$salesdata = array(
	   	   	'user'=>$myinvoice,
			'invoice'=>$myinvoice,

             );
	$this->usermodel->updatedata($salesdata,'sales_order','invoice',$salesinvoice);
	$this->usermodel->updatedata($debitcreditdata,'debitcredit','code',$salesinvoice);
			 $this->usermodel->deletedata($salesid[$i],"id","sales");
			 
			 
			 
			 
			 
			 

}





   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
						$mydata = array(
	   	   

	   	'type'=>"merge",
		
			'dateposted'=>$dateposted,
					'userid'=>$finaluserid,
'companyid'=>$companyid,
					'branch'=>$finalbranchid,
										'invoice'=>$myinvoice,

             );		
								 
								 
 
								 
								 
								 if($this->usermodel->add($mydata,'splitbillmaster')){
									 
			

$salesdata=array(
											
			'userid'=>$finaluserid,
			
				'type'=>$mytype,
			'customer'=>$mycustomers,
		  	'cash'=>$ourtotal,
								 
		'cardnumber'=>$customerpin,

					  	'salestype'=>$mysalestype,
			   			  // 'cashier' => $accountno, 
						//'name' => $name,  
			'companyid'=>$companyid,
			'dateposted'=>$dateposted,
			'total' => $ourtotal,
///'branch'=>$branchid,		  
		     'invoice' => $myinvoice,  
		     //'balance' => $finalbalance, 
			   			 //  'due_date' => $due, 
		  'mytable' => $mytable,  
					 // 'maincategory' => $maincategory,  
					   //'paymentstatus' => $paymentstatus,   

				//  'maindiscount' => $maindiscount,    
		    // 'discountedtotal' => $discountedtotal, 
					//  'description' => $mydescription,  
			  
			 			 			     'salesperson' => $mysalesperson, 

			'updatedby'=>$userid,
			'updatedat'=>$dateposted,
			
								); 
									 
							$usr_result = $this->usermodel->add($salesdata,'sales');		 





	
}									 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully merged the bills ..</div>');	
							//
							
							
							redirect("user/clearsales");																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The bills were not merged. Try again</div>');
								
							redirect($view);																
							}
		
		
	}else if(($this->input->post('groupbycategory') == "Served")||($this->input->post('groupbycategory') == "Ready"))
					   {	
	$categoryid = $this->input->post("categoryid");
		$groupbycategory = $this->input->post("groupbycategory");

	$view = $this->input->post("view");

								 $salesid = $this->input->post("selector");

			if($categoryid=="Served"){
				$ordersales=$groupbycategory;
				$categoryid="No";
					
				}else{
				$ordersales=$groupbycategory;

				//$ordersales="printed";
				$categoryid=$categoryid;			
				}
		
		
		
		
			 $selector = $this->input->post("selector");

			
			  $count =count((array)$selector);
			
	//
   for($i=0; $i< $count; $i++) {
	   		
				
				
			    $data = array(
	   //	'paymentstatus'=>$categoryid,
			'ordersales'=>$ordersales,
				

			'updatedat'=>$dateposted,
					'updatedby'=>$userid,

             );	
				
	  		$usr_result = $this->usermodel->updatedata($data,'sales','id',$salesid[$i]);
		
			
   }
   
  
		if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully served  the order  ..</div>');	
							redirect($view);																
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Order was not served.. Try again</div>');
								
							redirect($view);																
							}
		
		
		
	}else{
		
		redirect("login");
	}
  }
	
 
 
 
 
 
 
	 public function openemployeeshift() {
   	if ($this->input->post('startemployeeshift') == "all")
					   {
			
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
        		
   	
			
			 $categoryid = $this->input->post("categoryid");
			
						 $memberid = $this->input->post("selector");

			
			
			
			
			
			
			 $count =count((array)$memberid);

   for($i=0; $i< $count; $i++) {
       $data = array(
	   
			'status'=>$categoryid,
		  
		//'memberid' =>$memberid[$i],
             );
			 	
	
		$usr_result =	$this->usermodel->updatedata($data,'people','id',$memberid[$i]);
		  
			  
   

       }
	
		
			if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the data  ..</div>');	
								redirect('user/viewmember');	
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The shift was not opened. Try again</div>');
																redirect('user/opencloseshift');	

							}
		
		
	}else{
		
		redirect("user/viewmember");
	}
  }
	
 
 public function splitsale() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
        		         $dateposted = date('Y-m-d H:i:s');

   	 if ($this->input->post('splitbill') == "split")
					   {
		
	
   
			
			 $categoryid = $this->input->post("categoryid");
						 $myinvoice = $this->input->post("myinvoice");

						 $salesid = $this->input->post("selector");

							 $myview = $this->input->post("myview");
							 $view = $this->input->post("view");
							 $qty = $this->input->post("myqty");
							 $price = $this->input->post("price");

										 $originalinvoice = $this->input->post("originalinvoice");

		
			
			
			  $count =count((array)$salesid);
			  
			   if( $count<1){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You have not selected any item from the list.Please do so then try again.</div>');	
																						
														redirect($myview);																
																			return false;
																			   }

   for($i=0; $i< $count; $i++) {
	   //$mysalesid=$salesid[$i];
	   
	  
  
       $data = array(
	   	   	'salesid'=>$salesid[$i],
	   	   	'qty'=>$qty[$i],
	   	   	'price'=>$price[$i],

	   	'type'=>"split",
		
			'dateposted'=>$dateposted,
					'userid'=>$userid,
'companyid'=>$companyid,
			'branchid'=>$branchid,
				'invoice'=>$myinvoice,
				'originalinvoice'=>$originalinvoice,

             );
			 	
  		$usr_result = $this->usermodel->add($data,'splitbill');
if ($usr_result ==TRUE){
	 	
	$salesdata = array(
	   	   
			'user'=>$myinvoice,

             );
	$this->usermodel->updatedata($salesdata,'sales_order','id',$salesid[$i]);
}

   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
						$mydata = array(
	   	   

	   	'type'=>"split",
		
			'dateposted'=>$dateposted,
					'userid'=>$userid,
'companyid'=>$companyid,
					'branch'=>$branchid,
									'originalinvoice'=>$originalinvoice,

										'invoice'=>$myinvoice,

             );		
								 
								 
						$this->usermodel->add($mydata,'splitbillmaster');
 
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully splited the bills ..</div>');	
							//
							
													//	redirect($myview);																

						redirect("user/printsplitedbill?invoice=".$myinvoice."&view=user/mergebill");																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The bills were not splited. Try again</div>');
								
							redirect($myview);																
							}
		
		
	}
	
	
	else{
		
		redirect("login");
	}
  }
	
 
 
 
 
 
 
 public function mergempesasales() {
	 
	 	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 $userid = $data['id'];
  
 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
        		         $dateposted = date('Y-m-d H:i:s');

   	 if ($this->input->post('mergempesas') == "merge")
					   {
		
	
   
			 $view = $this->input->post("view");
			 $amount = $this->input->post("amount");
						 $code = $this->input->post("code");
				$id = $this->input->post("id");
						 $salesid = $this->input->post("selector");
						 $myview = $this->input->post("myview");
$totalamounts=0;
							 
$allcodes="";

		
			
			
			  $count =count((array)$salesid);
			  
			   if( $count<1){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You have not selected any item from the list.Please do so then try again.</div>');	
																						
														redirect($myview);																
																			return false;
																			   }

   for($i=0; $i< $count; $i++) {
	   
	   $money = $this->usermodel->populateallarray('mergedmpesa','id',$salesid[$i]);
$myid=$money[0]['id'];
		$mycode=$money[0]['code'];
	    $myamount=$money[0]['amount'];
	   
	   
	  $totalamounts = $totalamounts + $myamount;	

  if($i==0){
	  
	   $allcodes.="". $mycode;
 
  }else{
	  
	 $allcodes.=",". $mycode; 
  }

       $data = array(
	   	   	'id'=>$myid,
	   	   	'code'=>$mycode,
	   	   	'amount'=>$myamount,

	   

             );
			 	
  		//$usr_result = $this->usermodel->add($data,'splitbill');


   }
   
   
 
   //redirect('user/viewsales',$data);	
		redirect($view.'?transactioncode='.$allcodes.'&mpesaamount='.$totalamounts);	

	return false;
			if ($usr_result ==TRUE) //active user record is present
							{
				
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully splited the bills ..</div>');	
							//
							
													//	redirect($myview);																

						redirect("user/printsplitedbill?invoice=".$myinvoice."&view=user/mergebill");																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The bills were not splited. Try again</div>');
								
							redirect($myview);																
							}
		
		
	}
	
	
	else{
		
		redirect("login");
	}
  }
	
 
 
 
 
 
 
 
 
   public function searchforinvoice() {
	   	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
		 $userid = $data['id'];
	   		  $code =  htmlspecialchars($this->input->post("code"));

		  	      $viewall=$this->usermodel->populatuserpermissionsdataarray('cashiersales','all',$userid);

$status="";
if($viewall==true){
$status="all";	
}else{
	$status="one";	

}
	  	   $view = $this->input->post("view");   
	   $data['salesreport'] = $this->usermodel->populatemyinvoicebycode($code,$companyid,$userid,$status);
	  
							       $data["viewexpenses"] = false;
							       $data["allcollections"] = false;

	  
  if($data['salesreport']!=false){
	  
	  $data["total_rows"] =1;
		$data["links"] = 1;
	  $this->load->view("template/headerpagemin");	
if($view=="user/mysales"){

						$this->load->view('userdata/mysales', $data);	
}else{
	
						$this->load->view('userdata/clearsales', $data);
}	  
								$this->load->view("template/footerpage");
								
								
	  
  }else{
 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Receipt number does not exist..try again  </div>');
	redirect($view );
		 }
   }
 
 
 
 
 
 
 
  public function searchinvoice() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	
			  

	 $companyid = $data['companyid'];
	    if (isset($_GET['code'])){
	
    
      $code= $_GET['code'];
	  $data['viewreceipt'] = $this->usermodel->populateinvoicebycode($code,$companyid);

 if($data['viewreceipt']!=false){
	 $salesid = $data['viewreceipt']['0']['invoice'];
	 $salestype = $data['viewreceipt']['0']['salestype'];
	  $data['salesid']=$salesid ;
	   $data['salestype']=$salestype;
	   $data['viewreturnsales'] = $this->usermodel->getReturnesales_orderReceipt($salesid,$companyid);


     $this->load->view("template/headerpagemin");				
						//$this->load->view('userdata/viewreturnsales', $data);
											$this->load->view('userdata/searchinvoice', $data);

								//redirect('user/searchinvoice');
	
								
								$this->load->view("template/footerpage");

	 
 }else{
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Receipt number does not exist..try again  </div>');
	redirect('user/viewreturnsales');
		//redirect('user/searchinvoice');


	}
    }else{
		
		
	
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
		  $code =  htmlspecialchars($this->input->post("code"));

  
	 

 
 $data['viewreceipt'] = $this->usermodel->populateinvoicebycode($code,$companyid);

 if($data['viewreceipt']!=false){
	 $salesid = $data['viewreceipt']['0']['invoice'];
	 $salestype = $data['viewreceipt']['0']['salestype'];
	  $data['salesid']=$salesid ;
	   $data['salestype']=$salestype;
	  $data['salesid']=$salesid ;
	   $data['viewreturnsales'] = $this->usermodel->getReturnesales_orderReceipt($salesid,$companyid);


     $this->load->view("template/headerpagemin");	
	//redirect('user/searchinvoice');
	 											$this->load->view('userdata/searchinvoice', $data);

						//$this->load->view('userdata/viewreturnsales', $data);
								$this->load->view("template/footerpage");

	 
 }else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Receipt number does not exist..try again  </div>');
redirect('user/viewreturnsales');
	
		//redirect('user/searchinvoice');

		 }
	
  }
  

	}
 
  public function searchinvoicehold() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	
			  

	 $companyid = $data['companyid'];
	    if (isset($_GET['code'])){
	
    
      $code= $_GET['code'];
	  $data['viewreceipt'] = $this->usermodel->populateinvoicebycodeHold($code,$companyid);

 if($data['viewreceipt']!=false){
	 $salesid = $data['viewreceipt']['0']['invoice'];
	 $salestype = $data['viewreceipt']['0']['salestype'];
	  $data['salesid']=$salesid ;
	   $data['salestype']=$salestype;
	   $data['viewreturnsales'] = $this->usermodel->getReturnesales_orderReceiptHold($salesid,$companyid);


     $this->load->view("template/headerpagemin");				
						//$this->load->view('userdata/viewreturnsales', $data);
											$this->load->view('userdata/searchinvoicehold', $data);

								//redirect('user/searchinvoice');
	
								
								$this->load->view("template/footerpage");

	 
 }else{
	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Receipt number does not exist..try again  </div>');
	redirect('user/myholdingsales');
		//redirect('user/searchinvoice');


	}
    }else{
		
		
	
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
		  $code =  htmlspecialchars($this->input->post("code"));

  
	 

 
 $data['viewreceipt'] = $this->usermodel->populateinvoicebycodeHold($code,$companyid);

 if($data['viewreceipt']!=false){
	 $salesid = $data['viewreceipt']['0']['invoice'];
	 $salestype = $data['viewreceipt']['0']['salestype'];
	  $data['salesid']=$salesid ;
	   $data['salestype']=$salestype;
	  $data['salesid']=$salesid ;
	   $data['viewreturnsales'] = $this->usermodel->getReturnesales_orderReceiptHold($salesid,$companyid);


     $this->load->view("template/headerpagemin");	
	//redirect('user/searchinvoice');
	 											$this->load->view('userdata/searchinvoice', $data);

						//$this->load->view('userdata/viewreturnsales', $data);
								$this->load->view("template/footerpage");

	 
 }else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Receipt number does not exist..try again  </div>');
redirect('user/viewreturnsales');
	
		//redirect('user/searchinvoice');

		 }
	
  }
  

	}
	  

  public function printinvoice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		 
		 
		   $detailedvatinvoice=$this->usermodel->populatuserpermissionsdataarray('income','detailedvatinvoice',$userid);

		 
		 
		 
 $data['setting'] = $this->usermodel->getsetting();
 //$data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewreceipt'] = $this->usermodel->populateinvoiceAll($invoiceid);


 $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	$this->load->view("template/headerpagemin");
	
	///
	 $restrictbillprintingtotwo=$this->usermodel->populatuserpermissionsdataarray('sales','restrictbillprintingtotwo',$userid);

	   $confirmno=$data['viewreceipt'][0]["baddebt"];
    $counter=0;
	

   if(($confirmno =="") || ($confirmno =="0")){
	    $counter=1;

	   
   }else{
	   
		    $counter=$confirmno+1;
   
   }

 
 	$updatebill=array(		
												'baddebt'=>$counter,
													
													);
									 $this->usermodel->updatedata($updatebill,'sales','invoice',$invoiceid);
 
 
 
	
	
	
	if($detailedvatinvoice==true){
		
$this->load->view('userdata/printinvoicevat', $data);
	}else{
						$this->load->view('userdata/printinvoice', $data);


	}		
		
	}
  }
  
  
  
  
  
  public function printquote() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		 
		 
		   $detailedvatinvoice=$this->usermodel->populatuserpermissionsdataarray('income','detailedvatinvoice',$userid);

		 
		 
		 
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	$this->load->view("template/headerpagemin");
	
	
						$this->load->view('userdata/printquote', $data);


			
		
	}
  }
  
  
  public function printinvoicequotation() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		 
		 
		   $detailedvatinvoice=$this->usermodel->populatuserpermissionsdataarray('income','detailedvatinvoice',$userid);

		 
		 
		 
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	$this->load->view("template/headerpagemin");
	
	
	
	
	
	
	
	if($detailedvatinvoice==true){
		
$this->load->view('userdata/printinvoicevat', $data);
	}else{
						$this->load->view('userdata/printinvoicequotation', $data);


	}		
		
	}
  }
  
  
  
  
  
  
  
  
    
  
  
    
  public function printcreditnote() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_Creditnote($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printcreditnote', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
  public function printa4receipt() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

 $confirmno=$data['viewreceipt'][0]["baddebt"];
    $counter=0;
	

   if(($confirmno =="") || ($confirmno =="0")){
	    $counter=1;

	   
   }else{
	   
		    $counter=$confirmno+1;
   
   }

 
 	$updatebill=array(		
												'baddebt'=>$counter,
													
													);
									 $this->usermodel->updatedata($updatebill,'sales','invoice',$invoiceid);
 
 
 

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printa4receipt', $data);
		
	}
  }
  
    public function printsalesorder() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');
     $type = $_GET['type'];
    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('sales_order','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
				
				if($type=="invoice"){
											$this->load->view('userdata/printsalesorderinvoice', $data);

				}else{
											$this->load->view('userdata/printsalesorder', $data);

				}
		
	}
  } 
  
  
   public function printpurchaseorder() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	   $type = $_GET['type'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
				$data['type'] = $type;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printpurchaseorder', $data);
		
	}
  }
  
  
  
    
	
	
	
	
	
	
	 public function printpurchaseordernoprice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printpurchaseordernoprice', $data);
		
	}
  }
  
  
	
	
	
	
	
	
   public function printreturnedserialnos() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		
// $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);





		  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("serials","companyid",$companyid,"status","return","invoice",$invoiceid);













          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreturnedserialnos', $data);
		
	}
  }
  
  
  
  
  
   public function printinternalinvoice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		   $type = $_GET['type'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);




if($type =="receiving"){
	  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("newstock","companyid",$companyid,"itemstatus<>","returned","invoice_number",$invoiceid);


}else{
		  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("newstock","companyid",$companyid,"itemstatus<>","returned","invoice",$invoiceid);

							//$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

}










          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printinternalinvoice', $data);
		
	}
  }
  
  
  
  
  
  
     public function receivepurchases() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['finalsalesid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['purchaseorder'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewreceivings']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/receivepurchases', $data);
		
	}
  }
  
  
     public function receivedispatch() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['finalsalesid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['purchaseorder'] = $this->usermodel->populateallarray('bulkdispatch','invoice',$invoiceid);
						$data['viewreceivings']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/receivedispatch', $data);
		
	}
  }
  
  
    
  
     public function receiveitems() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['finalsalesid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['purchaseorder'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
		
		
		
								//$data['viewreceivings']= $this->usermodel->populatealldatanoarraythree('uomproducts','code', $mycode,'status',"child",'branch',$branchid);

		
						$data['viewreceivings']  = $this->usermodel->populatealldatanoarraythreeDISPATCH('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid, '0',0 );

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/receivedispatcheditems', $data);
		
	}
  }
  
  
  
  
  
  
  
   
   public function printsinglegrn() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	      $batchid = $_GET['batchid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
				$data['batchid'] = $batchid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['batchlist'] = $this->usermodel->populateallarray('batchlist','batchid',$batchid);
			$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('orderlist','batchid', $batchid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printsinglegrn', $data);
		
	}
  }
  
  
  
  
   
   public function printgrn() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	  $type = $_GET['type'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 
	 $this->load->view("template/headerpagemin");
 
	           		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


if($type =="receiving"){
		 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);


	  				//$data['viewsales'] = $this->usermodel->populatealldatanoarraythreeForPurchases("newstock","companyid",$companyid,"itemstatus<>","returned","invoice_number",$invoiceid);
	$data['viewsales'] = $this->usermodel->getreceivings($invoiceid);

								//	$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice_number', $invoiceid,'companyid', $companyid);

	$data['view']="user/viewpurchases";
							$this->load->view('userdata/printgrnpurchase', $data);

} else if ($type =="dispatched"){
 $data['viewreceipt'] = $this->usermodel->populateallarray('bulkdispatch','invoice', $invoiceid);
   	$data['viewsales'] = $this->usermodel->populateall('newstock','invoice', $invoiceid);
	
	
	$data['view']="user/viewbulkdispatch";
						$this->load->view('userdata/printdispatchedproducts', $data);

}else if ($type =="Move From"){
 $data['viewreceipt'] = $this->usermodel->populateallarray('bulkdispatch','invoice', $invoiceid);
   	//$data['viewsales'] = $this->usermodel->populateall('newstock','invoice', $invoiceid);
		$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'stockto',"Move From" );

	
	$data['view']="user/viewbulkdispatch";
						$this->load->view('userdata/printdispatchedproducts', $data);

} else if ($type =="Move"){
	
	$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'stockto',"Move" );

 $data['viewreceipt'] = $this->usermodel->populateallarray('bulkdispatch','invoice', $invoiceid);
   //	$data['viewsales'] = $this->usermodel->populateall('newstock','invoice', $invoiceid);
	
	
	$data['view']="user/viewbulkdispatch";
						$this->load->view('userdata/printdispatchedproducts', $data);

}else{
		 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);

						//	$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);
		  				$data['viewsales'] = $this->usermodel->populatealldatanoarraythree("newstock","companyid",$companyid,"itemstatus<>","returned","invoice",$invoiceid);

	
	$data['view']="user/allpurchaseorder";
						$this->load->view('userdata/printgrnpurchase', $data);

}



				
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
      public function printdeliverysingle() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	  $batchid = $_GET['batchid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  //$data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
				
				$data['batchlist'] = $this->usermodel->populateallarray('batchlist','batchid',$batchid);
			//$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('orderlist','batchid', $batchid,'companyid', $companyid);	
				
				
				

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printdeliverysingle', $data);
		
	}
  }
  
  
  
  
    public function printtillcollection() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 //$data['setting'] = $this->usermodel->getsetting();

 $data['collections'] = $this->usermodel->populateallarraytwo('tillcollection','id',$invoiceid,'id >',0);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printtillcollections', $data);
		
	}
  }
  
  
  
  
  
    public function printcollections() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();

 $data['collections'] = $this->usermodel->populateallarray('dailycollections','id',$invoiceid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printcollections', $data);
		
	}
  }
  
  
		public function price()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
			
				
		 

$mytotal_amount = $this->usermodel->countamount($userid);

	$total_amount=$mytotal_amount[0]['totalsms'];			
				
				$config['base_url'] = base_url('Systemusers/price');

		$config['total_rows'] = $this->usermodel->count_allwhere('recharge','userid',$userid);


		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
        $data["viewrecharging"] = $this->usermodel->displayall($config["per_page"], $page,'recharge','userid',$userid);
			$data['total_sms'] = $this->usermodel->countAlerts($userid); 

			
				
				
      //   $this->load->view("userdata/price");
		 	         $this->load->view("template/headerpage");

		
	//$data['mycategory'] = $this->usermodel->populatecategory($userid);
			
		$data["total_rows"] =$config['total_rows'];
		$data["total_amount"] =$total_amount;
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/price',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
  
  
  
  
  
    public function printdelivery() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printdelivery', $data);
		
	}
  }
   public function printrequest() {
	
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
										$data['viewstatement']  = $this->usermodel->populatealldatanoarray('statement','invoice', $invoiceid,'companyid', $companyid);

		 		$data['viewexpenses'] = $this->usermodel->populateallarray('expenses','invoice',$invoiceid);

						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printrequest', $data);
		
	}
  }
  
  
  
  
  
  
  
	  public function printproductionformula() {
	
   if (!isset($_GET['codeitemids'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['codeitemids'];
	      $status = $_GET['status'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['itemid'] = $itemid;
		 $userid = $data['id'];
$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

	$data['uomprice']  = $this->usermodel->populatealldatanoarray('uomproducts','code', $itemid,'status',$status );
					$data['child']  = $this->usermodel->populatealldatanoarraythreechild('uomproducts','code', $itemid,'status',$status ,'branch',$branchid);


   			        	$data['viewprice'] = $this->usermodel->populateall('productlist','code', $itemid);
   			        	$data['product'] = $this->usermodel->populateall('products','code', $itemid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printproductionformula', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
   public function printmyexpense() {
	
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
										$data['viewstatement']  = $this->usermodel->populatealldatanoarray('statement','invoice', $invoiceid,'companyid', $companyid);

		 		$data['viewexpenses'] = $this->usermodel->populateallarray('expenses','invoice',$invoiceid);

						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printexpense', $data);
		
	}
  }
  
  
   public function printreceivedpayments() {
	
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['randomitemidentifier'];
	 $myid = $_GET['myid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewbill'] = $this->usermodel->populateallarray('sales','invoice',$invoiceid);
						$data['viewcollection']  = $this->usermodel->populatealldatanoarray('collection','id', $myid,'companyid', $companyid);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreceivedpayments', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
    
   public function printadvancereceipt() {
	
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['randomitemidentifier'];
	 $myid = $_GET['myid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
		$data['myid'] = $myid;

	 					$data['advance'] = $this->usermodel->populateall('advance', 'id',$invoiceid);


          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printadvancereceipt', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
   public function printbillpaymentsbulk() {
	
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = trim($_GET['randomitemidentifier']);
	 $myid = $_GET['myid'];
	 $transactioncode = $_GET['transactioncode'];
	 
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewbill'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						//$data['viewcollection']  = $this->usermodel->populatealldatanoarray('collection','id', $myid,'companyid', $companyid);

		  				//$data['viewcollection'] = $this->usermodel->populatealldatanoarraythree("collection","companyid",$companyid,"id<>",0,"transactioncode",$transactioncode);
$data['viewcollection']  = $this->usermodel->populatealldatanoarray('collection','transactioncode', $transactioncode,'companyid', $companyid);


          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printbillpaymentsbulk',$data);
		
	}
  }
  
  
  
  
  
  
  
  
    public function printbillpayments() {
	
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = trim($_GET['randomitemidentifier']);
	 $myid = $_GET['myid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewbill'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
						$data['viewcollection']  = $this->usermodel->populatealldatanoarray('collection','id', $myid,'companyid', $companyid);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printbillpayments',$data);
		
	}
  }
  
  
  
    public function printbillpaymentsbill() {
	
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = trim($_GET['randomitemidentifier']);
	 $myid = $_GET['myid'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewbill'] = $this->usermodel->populateallarray('expenses','invoice',$invoiceid);
						$data['viewcollection']  = $this->usermodel->populatealldatanoarray('collection','id', $myid,'companyid', $companyid);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printbillpaymentsbill',$data);
		
	}
  }
  
  
  
  
  
  
  
   public function printmybill() {
	
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
										$data['viewstatement']  = $this->usermodel->populatealldatanoarray('statement','invoice', $invoiceid,'companyid', $companyid);

		 		$data['viewexpenses'] = $this->usermodel->populateallarray('expenses','invoice',$invoiceid);

						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printmybill', $data);
		
	}
  }

     public function printbankdeposits() {
	
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray(' banks','invoice',$invoiceid);
										$data['viewstatement']  = $this->usermodel->populatealldatanoarray('statement','invoice', $invoiceid,'companyid', $companyid);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printbankdeposits', $data);
		
	}
  }

   public function printmyjournal() {
	
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('journal','invoice',$invoiceid);
										$data['viewstatement']  = $this->usermodel->populatealldatanoarray('debitcredit','code', $invoiceid,'companyid', $companyid);



          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printmyjournal', $data);
		
	}
  }

  
  
   public function printquotation() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarrayorderby('purchaseorderlist','id',"asc",'invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printquotation', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
   public function printquotationhp() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printquotationhp', $data);
		
	}
  }
  
  
  
  
  
  
  
   public function printrequisition() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printrequisition', $data);
		
	}
  }
  
  
  
  
   public function printrequisitionnoprice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printrequisitionnoprice', $data);
		
	}
  }
  
  
   
   public function loadingsheet() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/loadingsheet', $data);
		
	}
  }
  
  
  
  
   public function printprofomainvoice() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarraySales('purchaseorderlist','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printprofomainvoice', $data);
		
	}
  }
  
  
  
  
 public function printreceipts() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoiceAll($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
				
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 	  $view=$smsconfig[0]['view'];	
  $receipt=$smsconfig[0]['receipt'];	
	
		 $this->load->view("template/headerpagemin");
		$data['receipt'] =$receipt;
						
				

 $restrictbillprintingtotwo=$this->usermodel->populatuserpermissionsdataarray('sales','restrictbillprintingtotwo',$userid);
	   $confirmno=$data['viewreceipt'][0]["baddebt"];
    $counter=0;
	

   if(($confirmno =="") || ($confirmno =="0")){
	    $counter=1;

	   
   }else{
	   
		    $counter=$confirmno+1;
   
   }

 
 	$updatebill=array(		
												'baddebt'=>$counter,
													
													);
									 $this->usermodel->updatedata($updatebill,'sales','invoice',$invoiceid);
 
 
 				
						
						

if($receipt=="Three Without Automatic Logout"){

	$this->load->view('userdata/printreceipt', $data);

}else if($receipt=="Three With Automatic Logout"){

	$this->load->view('userdata/printreceipt', $data);

}else if($receipt=="One With Automatic Logout"){

	$this->load->view('userdata/printreceiptpos', $data);

}else if($receipt=="One Without Automatic Logout"){

	$this->load->view('userdata/printreceiptpos', $data);

}else if($receipt=="Two Without Automatic Logout"){

	$this->load->view('userdata/printreceipt', $data);

}else if($receipt=="Two With Automatic Logout"){

	$this->load->view('userdata/printreceipt', $data);

}else{

	$this->load->view('userdata/printreceiptpos', $data);

}



		
	}
  }
 
 public function printpending() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		 $invoiceid = $_GET['invoice'];
     $receipt = $_GET['receipt'];
	      $view = $_GET['view'];

	 	$data['receipt'] =$receipt;
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		$data['view']= $view;
		  $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$this->printreceiptcopy($invoiceid)		


 $confirmno=$data['viewreceipt'][0]["baddebt"];
    $counter=0;
	

   if(($confirmno =="") || ($confirmno =="0")){
	    $counter=1;

	   
   }else{
	   
		    $counter=$confirmno+1;
   
   }

 
 	$updatebill=array(		
												'baddebt'=>$counter,
													
													);
									 $this->usermodel->updatedata($updatebill,'sales','invoice',$invoiceid);
 
 
 




	
		 $this->load->view("template/headerpagemin");
	
						$this->load->view('userdata/printreceiptpos', $data);
						




		
	}
  }
 
   
  public function printtimer() {
  
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		 $invoiceid = $_GET['invoice'];
    
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
		$data['viewsales'] = $this->usermodel->populateall('timer','invoice',$invoiceid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$this->printreceiptcopy($invoiceid)		
          		$data['viewreceipt'] = $this->usermodel->populateallarray('timer','invoice',$invoiceid);

	
		 $this->load->view("template/headerpagemin");
	
						$this->load->view('userdata/printtimer', $data);
						




		
	}
  }
 
  
  
  
  
 public function printreceiptcopy() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$this->printreceiptcopy($invoiceid)		

	
		 $this->load->view("template/headerpagemin");
	
						$this->load->view('userdata/printreceiptcopy', $data);
						




		
	}
  }
 
  public function printreceiptcopy1($invoiceid) {
   
$invoiceid = $invoiceid;
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreceiptcopy', $data);
		
	
  }
 
 
 
 
   public function printreceiptcopy2($invoiceid) {
   
$invoiceid = $invoiceid;
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreceipt', $data);
		
	
  }
 
 
 
 
 
 
 public function printbill() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoiceAll($invoiceid);
		      $restrictbillprintingtotwo=$this->usermodel->populatuserpermissionsdataarray('sales','restrictbillprintingtotwo',$userid);
	   $confirmno=$data['viewreceipt'][0]["baddebt"];
    $counter=0;
	

   if(($confirmno =="") || ($confirmno =="0")){
	    $counter=1;

	   
   }else{
	   
		    $counter=$confirmno+1;
   
   }

 
 	$updatebill=array(		
												'baddebt'=>$counter,
													
													);
									 $this->usermodel->updatedata($updatebill,'sales','invoice',$invoiceid);
 
 
 
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
										$this->load->view('userdata/printbill', $data);

						//$this->load->view('userdata/printreceipt', $data);
		
	}
  }
 
 
 
 
 public function printmergedbill() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populatemergedinvoice($invoiceid);
 

  $data['viewsales'] = $this->usermodel->getesales_ordermergedbill($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printmergedbillall', $data);
		
	}
  }
 
 
 
 public function printsplitedbill() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populatemergedinvoice($invoiceid);
 

  $data['viewsales'] = $this->usermodel->getesales_ordermergedbill($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printsplitedbillall', $data);
		
	}
  }
 
 
 
 public function printsplitedbillold() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populatemergedinvoice($invoiceid);
 

  $data['viewsales'] = $this->usermodel->getesales_ordermergedbillold($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		
	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printsplitedbillall', $data);
		
	}
  }
 
 
 public function printmyorder() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
	 			
			 $this->load->view("template/headerpagemin");

     $invoiceid = $_GET['invoice'];
	      $nextcounter = $_GET['nextcounter'];
	      $myview = $_GET['myview'];

 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
			        	$data['nextcounter'] = $nextcounter;
			        	$data['myview'] = $myview;
	
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
           		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$kitchenid=$data['configuration'][0]['kitchenid'];
$receipt=$data['configuration'][0]['receipt'];


 	if($data['configuration'][0]['kitchen']=="yes"){
		
		
		  $data['viewsales'] = $this->usermodel->getesalesmy_orderonlyNoKitchen($invoiceid,$companyid,$kitchenid);

if( $data['viewsales']==false){
	


		
if($receipt=="Two Without Automatic Logout"){


redirect('user/viewsales');
 
}else if($receipt=="Two With Automatic Logout"){


redirect('login');

	

	}else if($receipt=="Three Without Automatic Logout"){

redirect('user/viewsales');

 
}else if($receipt=="Three With Automatic Logout"){


redirect('login');
  
}else{
	

	if($nextcounter==1){
	//redirect('user/viewmysales?invoice=$invoiceid&myview=$myview');

		redirect('user/viewsales');
		}else{
		
redirect('user/viewsales');
			
		}
	
}












	
	//return false;
}


	}else{
		  $data['viewsales'] = $this->usermodel->getesalesmy_orderonly($invoiceid,$companyid);

		
	}

	 
	 
//
						$this->load->view('userdata/printorder', $data);
		
	}
  }
 
 
 
 
 
 public function printorder() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
	 
	  $smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 	 	
  $receipt=$smsconfig[0]['receipt'];
  
    $kitchen=$smsconfig[0]['kitchen'];
    $kitchenid=$smsconfig[0]['kitchenid'];	
	    $data['receipt']=$receipt;	
		if($kitchen=="yes"){
		 $data['viewsales'] = $this->usermodel->getesalesmy_orderNoKitchen($invoiceid,$companyid,$branchid);

//$data['viewsales']=FALSE;
		}else{
		  $data['viewsales'] = $this->usermodel->getesalesmy_order($invoiceid,$companyid);
	
		}

  
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
	
				
				 if($data['viewsales']==false){
					 
					 if($receipt=="One Without Automatic Logout"){
redirect('user/viewsales');

}else if($receipt=="One With Automatic Logout"){
	redirect('login');

 
}else  if($receipt=="Two Without Automatic Logout"){
	redirect('user/viewsales');

}else if($receipt=="Two With Automatic Logout"){
	redirect('login');

}else if($receipt=="Three Without Automatic Logout"){
	redirect('user/viewsales');

}else if($receipt=="Three With Automatic Logout"){
	redirect('login');

}else{
	

	if($nextcounter==1){
			redirect("user/viewmysales?invoice=".$invoiceid."&myview=".$myview);

	
		}else{
			redirect('user/viewsales');

		}
	
}

					 
					 
					 
					 
					 
					 
					 
					 
					 
					 
					 
					 
					 
					 
	 						//$this->load->view('userdata/backprintorder', $data);

						 }else{
							$this->load->view('userdata/printorder', $data);
							 
						 }

		
	}
  }
 
 
 
 
 
 
 
 
  public function printholdreceipt() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['invoiceid'] = $invoiceid;
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 		
$data['viewreceipt'] = $this->usermodel->populateallarray('sales_holding','invoice',$invoiceid);
	
	$data['viewsales'] = $this->usermodel->populateall('sales_orderholding','invoice',$invoiceid);
	
				
				
				$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printorderhold', $data);
		
	}
  }
 
 
 
 
  public function printreceiptswholesale1() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['invoiceid'] = $invoiceid;
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($invoiceid);
  $data['viewsales'] = $this->usermodel->getesales_orderReceiptWholesale($invoiceid,$companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('userdata/printreceiptswholesale', $data);
		
	}
  }
    
    public function viewmysales() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	      $myview = $_GET['myview'];

 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
			 
			 	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
			 
			 $this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
								        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);

		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);
		$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
				}else{
							$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);

				}
				
				
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);

				}
				
				
				
				
				
				
						 $userid = $data['id'];
		$data['salesid'] = $invoiceid;
				$data['return'] = $invoiceid;
				
				
			 
			 ///tesa
			 
			
			 
			 $allsales = $this->usermodel->last_recordsalesraw($branchid,$userid);


		 	
 		
			//
			
		
 if($allsales !=FALSE){
	 	
		
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
					 <strong>Error!</strong> You have Incomplete/pending sales that you  need to complete before you add more sales..Go to sales window or click on merge button on sales window to complete them by clicking order/Dont print button or suspending them... Try again.</div>');
							//redirect($view ,$data);
							
						redirect("user/viewsales");	
 	
 }
   
			 
			 
			 	
			 
			 
								$sales_orderdata = array();
	//$solditems= $this->usermodel->geteallsales_orderoriginal($invoiceid);
			$solditems= $this->usermodel->geteallsales_orderoriginalNoreturn($invoiceid);

	if(is_array($solditems)){
	
	   foreach($solditems as $row)
	   {
		   // $this->usermodel->deletedata($invoiceid,"invoice","sales_orderraw");
			    $myid=trim($row->id);
		$code=$row->code;
		$myqty=$row->qty;
		$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
					
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 $taxcode=$row->taxcode;
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$type=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;
$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
		
$sales_orderdata[]=array(	
'customer'=>$row->customer,
				'mode'=>$row->mode,
'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,



			'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,
				'taxcode'=>$taxcode,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoiceid,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
		  
		  
		  
		}
		  	  $usr_result =$this->db->insert_batch('sales_orderraw', $sales_orderdata); 

		  
		        if($this->db->affected_rows() > 0)
	{
							 	 $this->usermodel->deletedata($invoiceid,"invoice","sales_order");
	
		


 	  $statusdata=array(		
												'status'=>'new',
													'ordersales'=>'printed',
													);
 //$this->usermodel->updatedata($statusdata,'sales_order','invoice',$invoiceid);
									$this->usermodel->updatedatabytwo($statusdata,'sales_orderraw','invoice',$invoiceid,'status<>','returned');

			 

		
		}	
		
		
		
		
	}	
	
								
								
								
								
								
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 



		
	$data['viewsales'] = $this->usermodel->getesales_orderraw($invoiceid,$userid);

								//$this->load->view($myview,$data);

if($myview=="user/viewwholesales"){
					$this->load->view('userdata/viewwholesales',$data);

}else{
				$this->load->view('userdata/viewsales',$data);
	
}


		
	}
  }
  
  
  
  
  
    public function viewmysalesholding() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	      $myview = $_GET['myview'];

 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
			 
			 
			 
			 $this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
								        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);

		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);
		$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
				}else{
							$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);

				}
				
				
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);

				}
				
				
				
				
				
				
						 $userid = $data['id'];
		$data['salesid'] = $invoiceid;
				$data['return'] = $invoiceid;
				
				
			 
			 
			 
			
			 
			 
			 //
			 
			 
			 
			 	
			 
			 
								$sales_orderdata = array();
	$solditems= $this->usermodel->geteallsales_orderoriginalHold($invoiceid);
	
	if(is_array($solditems)){
	
	   foreach($solditems as $row)
	   {
		   // $this->usermodel->deletedata($invoiceid,"invoice","sales_orderraw");
			    $myid=trim($row->id);
		$code=$row->code;
		$myqty=$row->qty;
		$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
					
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$type=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;
$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
		
$sales_orderdata[]=array(	

'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,


		'userid'=>$row->userid,
			//	'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoiceid,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' =>"new", 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
		  
		  
		  
		}
		  	  $usr_result =$this->db->insert_batch('sales_orderraw', $sales_orderdata); 

		  
		        if($this->db->affected_rows() > 0)
	{
							 	 $this->usermodel->deletedata($invoiceid,"invoice","sales_orderholding");
								 	 $this->usermodel->deletedata($invoiceid,"invoice","sales_holding");

		


 	  $statusdata=array(		
												'status'=>'new',
													'ordersales'=>'printed',
													);
 //$this->usermodel->updatedata($statusdata,'sales_order','invoice',$invoiceid);
								//	$this->usermodel->updatedatabytwo($statusdata,'sales_orderraw','invoice',$invoiceid,'status<>','returned');

			 

		
		}	
		
		
		
		
	}	
	
								
								
								
								
								
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 



		
	$data['viewsales'] = $this->usermodel->getesales_orderraw($invoiceid,$userid);

								//$this->load->view($myview,$data);

if($myview=="user/viewwholesales"){
					$this->load->view('userdata/viewwholesales',$data);

}else{
				$this->load->view('userdata/viewsales',$data);
	
}


		
	}
  }
  
  
  
  
  
  
  
  
    public function viewmyreturnedsales() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
	      $myview = $_GET['myview'];
		

 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
			 
			 
			 
			 $this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
	
	
	$invoiceidfinal=$invoiceid-1;
	
	
	
	
	
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
								        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);

		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);
		$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
				}else{
							$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);

				}
				
				
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
		$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);

				}
				
				
				
				
				
				
						 $userid = $data['id'];
		$data['salesid'] = $invoiceidfinal;
				$data['return'] = $invoiceidfinal;
				
				
			 
			 
			 
			
			 
			 
			 //
			 
			 
			 
			 	
			 $i=0;
			 
								$sales_orderdata = array();
	$solditems= $this->usermodel->geteallsales_orderoriginalReturned($invoiceid);
		
	if(is_array($solditems)){
	
	   foreach($solditems as $row)
	   {
		    $i++;
			
			
			$myinvoices = time(). $userid+ $i;
		
	
			
			
			
			
		   // $this->usermodel->deletedata($invoiceid,"invoice","sales_orderraw");
			    $myid=trim($row->id);
		$code=$row->code;
		$myqty=$row->qty;
				$taxcode=$row->taxcode;

		$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
					
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$type=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;
$salesaccount=$row->salesaccount;
			$expenseaccount=$row->expenseaccount;
				$producttype=$row->producttype;
					$assetaccount=$row->assetaccount;
		
$sales_orderdata[]=array(	

'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,



			'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoices,
			'taxcode'=>$taxcode,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoiceidfinal,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' =>"new", 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => "new", 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
		  
		   	  $statusdata=array(		
												//'status'=>'new',
													'ordersales'=>'returned',
													);
 $this->usermodel->updatedata($statusdata,'sales_order','id',$myid);
							
		  
		}
		  	  $usr_result =$this->db->insert_batch('sales_orderraw', $sales_orderdata); 

		  
		        if($this->db->affected_rows() > 0)
	{
							 	// $this->usermodel->deletedata($invoiceid,"invoice","sales_order");
	
		


	
								
								$this->usermodel->updatedatabytwo($statusdata,'sales_orderraw','invoice',$invoiceidfinal,'status','returned');

			 

		
		}	
		
		
		
		
	}	
	
								
								
								
								
								
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 
			 



		
	$data['viewsales'] = $this->usermodel->getesales_orderraw($invoiceidfinal,$userid);

								//$this->load->view($myview,$data);

if($myview=="user/viewwholesales"){
					$this->load->view('userdata/viewwholesales',$data);

}else{
				$this->load->view('userdata/viewsales',$data);
	
}


		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
    public function viewsubcategory() {
   if (!isset($_GET['maincategory'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $maincategory = trim($_GET['maincategory']);
	  $type = trim($_GET['type']);
		$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);

												if($type=="retail"){
													redirect('user/viewsales?maincategory='.$maincategory);	
		

															}else{
													redirect('user/viewwholesales?maincategory='.$maincategory);	

									
														}
	}
	
	
	}
	
	
  
  
  
  
  
  
  
  
  
    public function viewprodubyctcategory() {
   if (!isset($_GET['productcategory'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $productcategory = trim($_GET['productcategory']);
	  $type = trim($_GET['type']);
	  	  $maincategory = trim($_GET['maincategory']);

		$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,'branch',$branchid);

												if($type=="retail"){
													redirect('user/viewsales?productcategory='.$productcategory."&maincategory=".$maincategory);	
		

															}else{
													redirect('user/viewwholesales?productcategory='.$productcategory."&maincategory=".$maincategory);	

									
														}
	}
	
	
	}
	
	
  
  
  
  
  
  
  
  
  
  
  
  
  
  public function uploadcustomerstoEtims()
    {
		
		
		
		
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];

		
		
		$myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								$etims=$myconfiguration[0]["hscode"];

								
							   if ($etims =="EnableEtims"){
														   
						
						 
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
						   redirect('user/viewconfiguration');
						   

						   
						   return false;
						   }											
							
						  
										  
						  $combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
				  
						  
						  
				  
						  

$kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);
if($onlineoffline=="OSCU"){
		 $apiUrl = ''.$etimsurl.'/etims-api/saveBhfCustomer';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/branches/saveBrancheCustomers';

			 }
		
		
		
		
		
			$category = trim($this->input->get_post('category', TRUE));

	$branchid = trim($this->input->get_post('branchid', TRUE));


	$stocklist  = $this->usermodel->populatealldataarrayfour('people','branchid', $branchid,'recoverpassword<>',0,'idnumber<>', "",'category',$category);

		
if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	      $code=trim($row->code);
		  
		   $firstname="";
		  
		  
		  if($row->company !=""){
			  $firstname=$row->firstname;

		  }else{
			 $firstname=$row->company;

			  
		  }
		  
		  
		  
		   $data = [
		    "tin" => $kra_pin,
             "bhfId" => $branch_id,
            "custNo" => $row->idno,
            "custTin" => $row->idnumber,
            "custNm" => $firstname,
            "adrs" => "customer",
            "telNo" => $row->phone,
            "email" => $row->email,
            "faxNo" => null,
            "useYn" => "Y",
            "remark" => null,
            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];

        // Convert the data to JSON format
        $jsonData = json_encode($data);

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
        // Check for cURL errors
     
						
						
						
							    // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS customer :'.curl_error($ch).'. Try again </div>');
								
						  redirect('user/viewconfiguration');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);


			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			 $resultMsg = $responseArray['resultMsg'];




            if ($resultCd == '000') {
						   
				$updatedataetims=array(
											
			'recoverpassword'=>"1",		

								);							
						$usr_result =$this->usermodel->updatedata($updatedataetims,'people','id',$row->id);
						
								   
						   
						   
						   
			}else{
			   $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Error!  </strong>Error occurred during saving  ETIMS Items :'.curl_error($ch).'. Try again </div>');
								
						  redirect('user/viewconfiguration');
						   	
				
			}
		
		
		}		   
		
		  
   }	  
		  
		  
		  
		  
		  
		  
		  
	 
		

		
   }else{
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your dont have customers who have KRA Pins which have not been uploaded to ETIMS. Try again or add kra pins then try again.</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;   
	   
	   
   }
		 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully reset uploaded customers to etims..</div>');	
										
													redirect('user/viewconfiguration');	
	
														
   }	
	
	}
 
 
 
 
  
  
  
  
  
  

  
  public function suspendsalesmade() {
	if (!$this->input->post('btn_suspendallsales') == "allsolditems"){
		
		
					  

    
      show_error('No identifier provided', 500);
    }
    else {
	
	//
		  $password = $this->input->post("password"); 
	
	  $type = $this->input->post("type");
	  $salesid = $this->input->post("randomitemidentifier");		  
		  $view = $this->input->post("view"); 

		$confirmuser = $this->usermodel->getcashiers($password);
				
							//check if email and password is correct
							if ($confirmuser < 1) //active user record is present
							{
									 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Error!</strong> Wrong Login Details. Try again </div>');
								if($type=="retail"){
									
								redirect($view);

								}else{			
								redirect($view);
								}
								return false;
									
								 
								 
								 
							}else{
								  $companyid=$confirmuser[0]->companyid;
								    
							 	$employeeno=$confirmuser[0]->id;
							
										  		  	      $suspendsales=$this->usermodel->populatuserpermissionsdataarray('sales','suspend',$employeeno);

										 if( $suspendsales !=true){
											 
											 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Error!</strong> You dont have right to Cancel or suspend sales. Request for Admin to help. Try again </div>');
								if($type=="retail"){
									
								redirect($view);

								}else{			
								redirect($view);
								}
								return false;
									
											 
											 
										 }else{
											 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	// $view = trim($_GET['view']);
	 // $salesid = trim($_GET['randomitemidentifier']);
	
	   
	         	//	$mysoldproducts = $this->usermodel->populateall('sales_order','invoice', $salesid);
		  $mysoldproducts = $this->usermodel->populatealldatanoarray('sales_orderraw','invoice', $salesid,'ordersales', 'new');

		
	  	if(is_array($mysoldproducts)){
	 
	 
	 foreach ($mysoldproducts as $c){
		  $transactionid=$c->id;
		 	 $itemid=$c->code;
			  $totalqty=$c->qty;
			  			  $myserialname=$c->serial;

			  $branch=$c->branch;
		 //$myproducts=$this->usermodel->geteproductbyid($itemid);
		 
		  $myproducts = $this->usermodel->populatealldataarray('productlist','code', $itemid,'branch', $branch);

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
		
   $finalqty=($availableqty+$totalqty);
	
		 	 $this->usermodel->deletedata($transactionid,"id","sales_orderraw");

		 //$usr_result = $this->usermodel->deletedata($invoice_number,"invoice_number","newstock");
		 $productdata=array(		
												'qty'=>$finalqty,
													);
								
							//	$usr_result = 	 $this->usermodel->updateproduct($productdata,$mycode); 
		 								$usr_result = 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);
				if ($myserialname !="")
						   {
									$serialdata=array(		
						'status'=>"new",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$myserialname);

						   }
	 
	 
	 //
	 
	 
		   $mystatus=$c->status;
	
	   $transactionid=$c->id; $itemid=$c->code;$totalqty=$c->qty;$mybranch=$c->branch;$mytotal=$c->amount;
		  $producttype=$c->producttype;
		

			 $mybprice=$c->bprice;
			  $correctqty=$c->qty;
			  $finalbprice=((double)$mybprice*(double)$correctqty);
			 
		$salesaccount=$c->salesaccount;
		  $costofgoodsold=$c->expenseaccount;
		   $inventoryaccount=$c->assetaccount;
	 
	   
	   
	      $myid=trim($c->id);
				
				
				
		$assetaccount=$c->assetaccount;
		$salesaccount=$c->salesaccount;
		$expenseaccount=$c->expenseaccount;
			$producttype=$c->producttype;	

			
				
				
				
				
				
		$code=$c->code;
		$myqty=$c->qty;
		$invoice=$c->invoice;
				$dateposted=$c->dateposted;
	 $ordersales=$c->ordersales;

	 $status=$c->status;
	 
	 
	 		$myinvoice=$c->myinvoice;

	 $branch=$c->branch;
		$sprice=$c->sprice;
	$salestype=$c->salestype;
	
	 $address=$c->address;
		$vattype=$c->vattype;
	$mytype=$c->type;
	 $myqty=$c->qty;

	$taxable=$c->taxable;
		$taxindicator=$c->taxindicator;
				$updatedby=$c->updatedby;

		 $uom=$c->uom;
		$bprice=$c->bprice;
	$taxable=$c->taxable;
	$amount=$c->amount;
	$tax=$c->tax;
	$discount=$c->discount;

	 $tax2=$c->tax2;
		$maincategory=$c->maincategory;
	$category=$c->category;
		$stockafter=$c->stockafter;
		 	$uomqty=$c->uomqty;
		 	$serial=$c->serial;

		 	$stockbefore=$c->stockbefore;

		
		
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$c->userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								}
									$usr_result2 =$this->db->insert_batch('sales_ordercancelled', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
	 
	 
	 
		}
	 

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								
									// $this->usermodel->updateproduct($productdata,$mycode); 
								
										 								 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);

								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Deleted successfully </div>');
								redirect($view);
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
					redirect($view);					
							
							}
	  
	  
	  
	  
	  
	  
	  
	  
							}
							}
							
	}
  }	
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  public function suspendsales() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		$data['id'] = $session_data['id'];
		 $userid = $data['id'];
		 
		 
	 $view = trim($_GET['view']);
	   $salesid = trim($_GET['randomitemidentifier']);
	 $returnclearedsales  =$this->usermodel->populatuserpermissionsdataarray('viewreturnsales','returnclearedsales',$userid);

	   if($returnclearedsales==true){
		   
		  	$mysoldproducts = $this->usermodel->populateall('sales_orderraw','invoice', $salesid); 
		   
	   }else{
		   
		   	 $mysoldproducts = $this->usermodel->populatealldatanoarray('sales_orderraw','invoice', $salesid,'ordersales', 'new');

		   
	   }
	         

		
	  	if(is_array($mysoldproducts)){
	 
	 
	 foreach ($mysoldproducts as $c){
		  $transactionid=$c->id;
		 	 $itemid=$c->code;
			  $totalqty=$c->qty;
			  			  $myserialname=$c->serial;

			  $branch=$c->branch;
		 //$myproducts=$this->usermodel->geteproductbyid($itemid);
		 
		  $myproducts = $this->usermodel->populatealldataarray('productlist','code', $itemid,'branch', $branch);

		 $mycode=$myproducts[0]['code'];
		 $availableqty=$myproducts[0]['qty'];
		
   $finalqty=($availableqty+$totalqty);
	
		 	 $this->usermodel->deletedata($transactionid,"id","sales_orderraw");

		 //$usr_result = $this->usermodel->deletedata($invoice_number,"invoice_number","newstock");
		 $productdata=array(		
												'qty'=>$finalqty,
													);
								
							//	$usr_result = 	 $this->usermodel->updateproduct($productdata,$mycode); 
		 								$usr_result = 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);
				if ($myserialname !="")
						   {
									$serialdata=array(		
						'status'=>"new",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$myserialname);

						   }
						   
		
		   $mystatus=$c->status;
	
	   $transactionid=$c->id; $itemid=$c->code;$totalqty=$c->qty;$mybranch=$c->branch;$mytotal=$c->amount;
		  $producttype=$c->producttype;
		

			 $mybprice=$c->bprice;
			  $correctqty=$c->qty;
			  $finalbprice=((double)$mybprice*(double)$correctqty);
			 
		$salesaccount=$c->salesaccount;
		  $costofgoodsold=$c->expenseaccount;
		   $inventoryaccount=$c->assetaccount;
	 
	   
	   
	      $myid=trim($c->id);
				
				
				
		$assetaccount=$c->assetaccount;
		$salesaccount=$c->salesaccount;
		$expenseaccount=$c->expenseaccount;
			$producttype=$c->producttype;	

			
				
				
				
				
				
		$code=$c->code;
		$myqty=$c->qty;
		$invoice=$c->invoice;
				$dateposted=$c->dateposted;
	 $ordersales=$c->ordersales;

	 $status=$c->status;
	 
	 
	 		$myinvoice=$c->myinvoice;

	 $branch=$c->branch;
		$sprice=$c->sprice;
	$salestype=$c->salestype;
	
	 $address=$c->address;
		$vattype=$c->vattype;
	$mytype=$c->type;
	 $myqty=$c->qty;

	$taxable=$c->taxable;
		$taxindicator=$c->taxindicator;
				$updatedby=$c->updatedby;

		 $uom=$c->uom;
		$bprice=$c->bprice;
	$taxable=$c->taxable;
	$amount=$c->amount;
	$tax=$c->tax;
	$discount=$c->discount;

	 $tax2=$c->tax2;
		$maincategory=$c->maincategory;
	$category=$c->category;
		$stockafter=$c->stockafter;
		 	$uomqty=$c->uomqty;
		 	$serial=$c->serial;

		 	$stockbefore=$c->stockbefore;

						   
						   
						   
				
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$c->userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);		   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
	 }
	 
	 
	 
	 
	 		
		$usr_result2 =$this->db->insert_batch('sales_ordercancelled', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
		
	 
	 
		}
	 

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								
									// $this->usermodel->updateproduct($productdata,$mycode); 
								
										 								 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);

								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Deleted successfully </div>');
								redirect($view);
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Sales not suspended  </div>');
					redirect($view);					
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }	
	
  
  
  	public function viewreturnsales22()
	{ 
					$this->load->view("template/headerpagemin");

	$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];

	$code="-1";
		 $data['viewreceipt'] = $this->usermodel->populateinvoicebycode($code,$companyid);
 if($data['viewreceipt']!=false){
	 
	 
 }else{
	$invoiceid = $data['viewreceipt']["invoice"];
	   $data['viewreturnsales'] = $this->usermodel->getesales_order($invoiceid,$companyid);

	 
 }

	
				$this->load->view('userdata/viewreturnsales',$data);
		$this->load->view("template/footerpage");
	}
	
  
  	public function viewreturnsales()
	{ 
								 redirect('user/mysales');
	}
  
  
   function createRandomPasswordForsales() {
	  	$session_data = $this->session->userdata('logged_in');

			$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	$chars =  $userid.time()."00323230323202323202345678945324213123142532524EFGHIJKLMNOPQRSTU12312353253256325213213546121425453553245355ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					  //$chars = '2342355ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+';
	srand((int)microtime()*19999000000000000000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 10) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}

  function createRandomPassword() {
	  	$session_data = $this->session->userdata('logged_in');

			$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	$chars =  $userid.time()."00323230323202323202345678945324213123142532524EFGHIJKLMNOPQRSTU12312353253256325213213546121425453553245355ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					  //$chars = '2342355ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+';

	srand((int)microtime()*1000000000000000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 15) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}

	public function verifysetails()
	{ 
		$session_data = $this->session->userdata('logged_in');

	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
						$currentdate=date('Y-m-d');

								  	$MAINbusinesskey = $this->usermodel->populateallarray('smsconfig','id',$companyid);

								  		
									
						$deadline =trim($this->encryption->decrypt($MAINbusinesskey[0]["deadline"]));
			  $defautpage=trim($MAINbusinesskey[0]["defautpage"]);
									
									
									 $deadlinedetails=$MAINbusinesskey[0]["deadlinedetails"];
									  $businesskey=trim($MAINbusinesskey[0]["businesskey"]);
								  
								  
								  
						
															 

 								 $finalserialdecoded =trim($this->encryption->decrypt($businesskey));
								 
								 
								  $finaldate = strtotime(date($deadline));
									$mycurrentdate = strtotime(date($currentdate));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
								
									  $serial =trim(`wmic bios get serialnumber 2>&1`) ;

								$myfinalserial= explode("SerialNumber",str_replace("", "", $serial));
								 $finalserial = trim($myfinalserial[1]);
 								
								  
								   $localIP = getHostByName(getHostName());
if($finalserial==""){
$finalserial=$localIP;
}	
								  
							
							
 									$confirmkey="#@!!@#FILGONA#@!";
 								 $MYBUSINESSKEY =trim($this->encryption->decrypt($businesskey));
								  $CORRECTDATA= explode("OUKOMANDELA",$MYBUSINESSKEY);
								  $finalserialdecoded = ($CORRECTDATA[0]);
								   $correctdbkey = trim($CORRECTDATA[1]);
								   
								     /// $CORRECTDATA=  explode(',', $MYBUSINESSKEY);
									  
								if($businesskey==""){
									$this->session->set_userdata('logged_in', $sessiondata);

									$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>You do not have valid  license to use our software.Kindly purchase a license first to be able to use our software. Kindly contact Robisearch Limited( www.robisearch.com/ info@robisearch.com /0780655987 /0718667391 /0716413386 ).</div>');

									   
								 redirect('login');
									  return  false;
								  }
										
	
 
							if($confirmkey != $correctdbkey){
									$this->session->set_userdata('logged_in', $sessiondata);

									$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>You do not have valid  license to use our software.Kindly purchase a license first to be able to use our software. Kindly contact Robisearch Limited( www.robisearch.com/ info@robisearch.com /0780655987 /0718667391 /0716413386 ).</div>');

									   
								 redirect('login');
									  return  false;
								  }

								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								 
								  	 
							
													  							
				if($finalserialdecoded == $finalserial){
		$session_data = $this->session->userdata('logged_in');
	
 $data['days'] = $session_data['days'];
	 $days = $data['days'];				
				
					
					if($days<=7){
											
									

												

									   		  if($days<1){
												  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your  have '.$days.' days remaining to renew or comply with your agreement and ROBISEARCH LTD. Your license will expire on '.$deadline.' thereafter  you will not be able to acces your details though your data is safely stored.This is because of:'.$deadlinedetails.'.. Kindly contact Robisearch Limited( www.robisearch.com/ info@robisearch.com /0780655987 /0718667391 /0716413386 ).</div>');

						
									   
											      }else{
													  
													  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your  have '.$days.' days remaining to renew or comply with your agreement and ROBISEARCH LTD. Your license will expire on '.$deadline.' thereafter  you will not be able to acces your details though your data is safely stored.This is because of:'.$deadlinedetails.'.. Kindly contact Robisearch Limited( www.robisearch.com/ info@robisearch.com /0780655987 /0718667391 /0716413386 ).</div>');

								
													  
												  }
												  
									   
							
										}
					
					
					
					
					
					
					
					
					
					if($defautpage!=""){
						
						   redirect($defautpage);
					}else{
						
						   redirect("user/home");
					}
														
														   													// redirect("admin/viewpallmyplots");

				}else{
					
					 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Error!</strong> You dont have valid License Key to use ROBISEARCH SYSTEM. Contact ROBISEARCH LTD. 0718667391/0716413386/0780655987 to get the License Key</div>');
								
									   
								redirect('login');
				}
					
	}










  
  	public function viewsales()
	{ 
	$this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 	 		$config['base_url'] = base_url('Systemusers/viewsales');

        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);
	  		$data['viewmaincategory']  = $this->usermodel->populatealldatanoarrayorderby('maincategory','id','ASC','companyid', $companyid,'status','active');


		
		
		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);

		//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
							 		//$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);

	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategory','name','ASC','maincategory', $maincategory,'status','active');


				}else{
							//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
					 		//$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategory','name','ASC','maincategory', $maincategory,'status','active');

				}
				
				
				
				if (isset($_GET['currentqty'])){
									  $currentqty=trim($_GET['currentqty']);
	$data['currentqty']= $currentqty;
				}else{
$data['currentqty']="1";
				}
				
			
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);


		//$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
	$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);
	//$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category >',0,$branchid);

				}
				
				
				
				
				
		 $userid = $data['id'];
				
				
				
						       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);








$finalsalesid=0;


   
   
      if (isset($_GET['salesid'])){
	    $finalsalesid=$_GET['salesid'];

   }else{
		//exit;
		
	
	  $sale = $this->usermodel->last_recordsalesraw($branchid,$userid);


   //$sale = $this->usermodel->last_recordsale($companyid,$userid);
		 	
 		
			//
			
		
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();
 	
 }else{
	 
$finalsalesid=$sale[0]['invoice']; 


 }
   
   
   }






		   $countSales =count((array)$this->usermodel->countSales($branchid,$userid));
if($countSales >1){
	
	
		$data['salesid'] = $finalsalesid;
	

	$this->load->view('mypendingsales',$data);
				
		$this->load->view("template/footerpage");





					
			//redirect('user/pendingsales?randomitemidentifier='.$finalsalesid'$view=');						   
						   

						   
						   return false;
}
			
 
   	/*
   
      if (isset($_GET['salesid'])){
	   
	    $finalsalesid=$_GET['salesid'];
		
	   
   }else{
	   
	  $sale = $this->usermodel->last_recordsale($companyid,$userid);


	 		
			
			
			
			
			
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();
		 	
 }else{
	 
$finalsalesid=$sale[0]['invoice']; 


 }
   
   
   }

  */
   
   
   
   
   
   
   


		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

   		$data['maincategory'] = $maincategory;
   		$data['productcategory'] = $productcategory;

   
		
		$query  = $this->usermodel->displayallsalesdata($config["per_page"], $page,'sales_orderraw','invoice',$finalsalesid,'status','new');

 if (is_array($query)) {
     	$config['total_rows'] = $query['records'];  
    } else {
			$config['total_rows'] =false;
    }











	
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		
	
					$data['salesid'] = $finalsalesid;


		 
		 		$this->pagination->initialize($config);

		//$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			
	
 if (is_array($query)) {
		$data['viewsales'] = $query['data'];
    } else {
				$data['viewsales'] = false;

    }




				$this->load->view('userdata/viewsales',$data);
				
		$this->load->view("template/footerpage");
	}
	
  
  	public function viewwholesales()
	{ 
	$this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 	 		$config['base_url'] = base_url('Systemusers/viewsales');

        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);
	  		$data['viewmaincategory']  = $this->usermodel->populatealldatanoarrayorderby('maincategory','id','ASC','companyid', $companyid,'status','active');


		
		
		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);

		//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
							 		//$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);

	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategory','name','ASC','maincategory', $maincategory,'status','active');


				}else{
							//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
					 		//$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategory','name','ASC','maincategory', $maincategory,'status','active');

				}
				
				
				
				if (isset($_GET['currentqty'])){
									  $currentqty=trim($_GET['currentqty']);
	$data['currentqty']= $currentqty;
				}else{
$data['currentqty']="1";
				}
				
			
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);


		//$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
	$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);
	//$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category >',0,$branchid);

				}
				
				
				
				
				
		 $userid = $data['id'];
				
				
				
						       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);








$finalsalesid=0;


   
   
      if (isset($_GET['salesid'])){
	    $finalsalesid=$_GET['salesid'];

   }else{
		//exit;
		
	
	  $sale = $this->usermodel->last_recordsalesraw($branchid,$userid);


   //$sale = $this->usermodel->last_recordsale($companyid,$userid);
		 	
 		
			//
			
		
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();
 	
 }else{
	 
$finalsalesid=$sale[0]['invoice']; 


 }
   
   
   }




		   $countSales =count((array)$this->usermodel->countSales($branchid,$userid));
if($countSales >1){
	
	
		$data['salesid'] = $finalsalesid;
	

	$this->load->view('mypendingsales',$data);
				
		$this->load->view("template/footerpage");





					
			//redirect('user/pendingsales?randomitemidentifier='.$finalsalesid'$view=');						   
						   

						   
						   return false;
}
			
 
   	/*
   
      if (isset($_GET['salesid'])){
	   
	    $finalsalesid=$_GET['salesid'];
		
	   
   }else{
	   
	  $sale = $this->usermodel->last_recordsale($companyid,$userid);


	 		
			
			
			
			
			
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();
		 	
 }else{
	 
$finalsalesid=$sale[0]['invoice']; 


 }
   
   
   }

  */
   
   
   
   
   
   
   


		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

   		$data['maincategory'] = $maincategory;
   		$data['productcategory'] = $productcategory;

   
		
		$query  = $this->usermodel->displayallsalesdata($config["per_page"], $page,'sales_orderraw','invoice',$finalsalesid,'status','new');

 if (is_array($query)) {
     	$config['total_rows'] = $query['records'];  
    } else {
			$config['total_rows'] =false;
    }











	
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		
	
					$data['salesid'] = $finalsalesid;


		 
		 		$this->pagination->initialize($config);

		//$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			
	
 if (is_array($query)) {
		$data['viewsales'] = $query['data'];
    } else {
				$data['viewsales'] = false;

    }




				$this->load->view('userdata/viewwholesales',$data);
				
		$this->load->view("template/footerpage");
	}
  
  public function viewwholesales2222()
	{ 
	$this->load->view("template/headerpagemin");
	$session_data = $this->session->userdata('logged_in');
$maincategory="";
$productcategory="";

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 	 		$config['base_url'] = base_url('Systemusers/viewsales');

        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		//$data['viewmaincategory'] = $this->usermodel->populateall('maincategory','companyid',$companyid);
	  		$data['viewmaincategory']  = $this->usermodel->populatealldatanoarrayorderby('maincategory','id','ASC','companyid', $companyid,'status','active');


		
		
		    if (isset($_GET['maincategory'])){
	  $maincategory=trim($_GET['maincategory']);

		//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
							 		$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);

				}else{
							//$data['viewsubcategory'] = $this->usermodel->populateall('productcategory','maincategory',$maincategory);
					 		$data['viewsubcategory'] = $this->usermodel->populatealldatawhere('productcategory','name','ASC','maincategory',$maincategory);

				}
				
				
				    if (isset($_GET['productcategory'])){
	  $productcategory=trim($_GET['productcategory']);
		$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);


		//$data['viewproductcategory'] = $this->usermodel->populateall('products','category',$productcategory);
				}else{
		$data['viewproductcategory'] = $this->usermodel->populateallproductlist('productlist','category',$productcategory,$branchid);

				}
				
				
				
					if (isset($_GET['currentqty'])){
									  $currentqty=trim($_GET['currentqty']);
	$data['currentqty']= $currentqty;
				}else{
$data['currentqty']="1";
				}
				
				
		 $userid = $data['id'];
				
				
				
						       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);


		 // $sale = $this->usermodel->last_recordsale($companyid,$userid);

 
			$finalsalesid=0;
	
   

   
      if (isset($_GET['salesid'])){
	   
	    $finalsalesid=$_GET['salesid'];
		
	   
   }else{
	   
	  $sale = $this->usermodel->last_recordsalesraw($companyid,$userid);

	 
	 		
			
			
			
			
			
 if($sale==FALSE){
	 	$finalsalesid = $userid.time();
		 	
 }else{
	 
$finalsalesid=$sale[0]['invoice']; 


 }
   
   
   }
		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;


  
		
		
		//$query  = $this->usermodel->displayallsalesdata($config["per_page"], $page,'sales_order','invoice',$finalsalesid,'status','new');
		$query  = $this->usermodel->displayallsalesdata($config["per_page"], $page,'sales_orderraw','invoice',$finalsalesid,'status','new');

	 if (is_array($query)) {
$config['total_rows'] = $query['records'];
    } else {
				$config['total_rows']  = false;

    }



		
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		
	
					$data['salesid'] = $finalsalesid;


		 
		 		$this->pagination->initialize($config);

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			
	 if (is_array($query)) {
		$data['viewsales'] = $query['data'];
    } else {
				$data['viewsales'] = false;

    }

	

		
				$this->load->view('userdata/viewwholesales',$data);
		$this->load->view("template/footerpage");
	}
	
  
  
  
  
  
			public function viewreceivedproducts()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	         		          		$getbranch = $this->usermodel->populateallarray('purchaseorder','invoice',$invoice_number);
$branchto=$getbranch[0]["branchto"];
		$data['branchto'] = $branchto;
			$data['salesid'] = $invoice_number;
	$data['shippingto'] = $getbranch[0]["shippingto"];
	$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/viewreceiving',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
		public function printserialcodes()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	      $myid = $_GET['myid'];
	      $myqty = $_GET['myqty'];
	      $mycode = $_GET['mycode'];
	      $columns = $_GET['columns'];


		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
				$data['myid'] = $myid;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;

		  				$data['columns'] = $columns;

		//$data['viewserials']= $this->usermodel->populatealldatawhere('serials','id','ASC','itemid',$myid);
	  		$data['viewserials']  = $this->usermodel->populatealldatanoarrayorderby('serials','id','ASC','itemid', $myid,'invoice',$invoice_number);

		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/printserialcodes',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
		public function generatebulklabels()
	{ 
	

	   if (!isset($_GET['branchid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	
	//
		  $branchid =$_GET['branchid'];
	


		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
	

			$data['viewserials'] = $this->usermodel->populatealldatanoarraythree('labels','userid', $userid,'branch',$branchid,'companyid',$companyid);

						$this->load->view('userdata/printbulklables',$data);


		$this->load->view("template/footerpage");
	}
	}
	
	
	
		public function clearlables()
	{ 
	

	   if (!isset($_GET['branchid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	
	//
		  $branchid =$_GET['branchid'];
	


		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 			$cleardata=	$this->usermodel->deletedatatwo("labels","userid",$userid,"branch",$branchid);

		  if ($cleardata ==false)
						   {
							   
							   
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The products were not cleared. Try again.</div>');

						  
								redirect("user/viewbulklables");
	   return false;
						   }else{
							   
							
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Cleared the data.. You can scan a fresh ones..</div>');	
							   
							 				redirect("user/viewbulklables");
	   return false;  
							   
						   }
						   			






		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
		public function generatebarcode()
	{ 
	
	
	
	  	if (!$this->input->post('btn_barcode') == "barcode"){
		
		
					  

    
      show_error('No identifier provided', 500);
    }
    else {
	
	//
		  $shortname = $this->input->post("shortname"); 
	
	 $myqty = $this->input->post("myqty");
	
	  $mycode = $this->input->post("mycode");
		  	  $columns = $this->input->post("columns");

		  $view = $this->input->post("view"); 
   		  $codetype = $this->input->post("codetype"); 

	  

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
	
				$data['shortname'] = $shortname;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;
				$data['columns'] = $columns;


		$data['viewserials']= $this->usermodel->populatealldatawhere('products','name','ASC','code',$mycode);
		
	  		//$data['viewserials']  = $this->usermodel->populatealldatanoarrayorderby('serials','id','ASC','itemid', $myid,'invoice',$invoice_number);

	if($codetype=="Labels"){
						$this->load->view('userdata/printbarcodeslabels',$data);

	}else{
		
						$this->load->view('userdata/printbarcodes',$data);

	}
	
								//$this->load->view('userdata/printbarcodes',$data);

		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
public function splitpurchases() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];

	
	  $salesid = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	 

		$productname=$this->usermodel->geteeceivedproduct($transactionid);


 
			
		$date=$productname[0]['date']; 

			$type=$productname[0]['type']; 
		$description=$productname[0]['description']; 
			$mycompanyid=$productname[0]['companyid']; 
			$invoice_number=$productname[0]['invoice_number']; 
		$tax=$productname[0]['tax']; 
		$code=$productname[0]['item_id']; 
	$supplier=$productname[0]['supplier'];




			
		$sellingprice=$productname[0]['sellingprice']; 

			$buyingprice=$productname[0]['buyingprice']; 
			$stockfrom=$productname[0]['stockfrom']; 
		$stockto=$productname[0]['stockto']; 
			$balance=$productname[0]['balance']; 
			$item_id1=$productname[0]['item_id1']; 
				$itemstatus=$productname[0]['itemstatus']; 
							$status=$productname[0]['status']; 

							$myuserid=$productname[0]['userid']; 







		$myqty=$productname[0]['total'];

		$qty=$productname[0]['qty'];
		
	
		$data = array();
	
			
		  for($i=0; $i< $myqty; $i++) {
			  
			
			 
$data[]=array(		
				'updatedat'=>$updatedat,
				'userid'=>$myuserid,
			'updatedby'=>$userid,
			'itemstatus'=>$itemstatus,
							'tax'=>$tax,
	'qty'=>$qty,
				'item_id'=>$code,
			'total'=>1,
		  	'invoice_number'=>$invoice_number,
					  	'status'=>$status,

						'companyid'=>$mycompanyid,
'description'=>$description,
'type'=>$type,
			'date'=>$date,
			'supplier' => $supplier,		  
		  		    'sellingprice' => $sellingprice, 

		    'buyingprice' => $buyingprice, 
			     
  'stockfrom' => $stockfrom,		  
		  
		    'stockto' => $stockto, 
				
				'balance'=>$balance,
								'item_id1'=>$item_id1,
			
			
								);
								
		  }	
		  
		  
		
		  	  $usr_result =$this->db->insert_batch('newstock', $data); 

		  
		        if($this->db->affected_rows() > 0)
	{
					 	 $this->usermodel->deletedata($transactionid,"id","newstock");

						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully splited the transaction  !</div>');
								
								redirect('user/viewreceivedproducts?randomitemidentifier='.$salesid);	
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The prosuct sales was not splited. TRY AGAIN</div>');
								redirect('user/viewreceivedproducts?randomitemidentifier='.$salesid);	
							}









		  
								


	}
}


	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function printsingleserial()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	      

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		

		$data['viewserials']= $this->usermodel->populatealldatawhere('serials','id','ASC','id',$invoice_number);

		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/printserialcodes',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
		public function viewassignedbanks()
	{ 
	
	
	
	  if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	     
	      $mycode = $_GET['mycode'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								//$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;

					  		$data['paymentmethodes']  = $this->usermodel->populatealldatanoarray('rentalpaymentmethodes','companyid', $companyid,'chargeid',$mycode);

  
		
	
	
				$this->load->view('userdata/accountingrental',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
		public function viewcurrentserials()
	{ 
	
	
	
	  if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $mybranch = $_GET['branch'];
	      $mycode = $_GET['mycode'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;

		$data['viewserials']  = $this->usermodel->populatealldatanoarray('serials','branch', $mybranch,'code',$mycode);

  
		
	
	
				$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function viewcurrentserialsprint()
	{ 
	
	
	
	  if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $mybranch = $_GET['branch'];
	      $mycode = $_GET['mycode'];
	      $columns = $_GET['columns'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;
				$data['columns'] = $columns;

		$data['viewserials']  = $this->usermodel->populatealldatanoarray('serials','branch', $mybranch,'code',$mycode);

  
		
	
					$this->load->view('userdata/printserialcodes',$data);

			//	$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	public function checkinoutgatepass()
	{ 
	
	
	
	  if (!isset($_GET['passid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $passid = $_GET['passid'];
	      $status = $_GET['status'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	
 		  $dateposted = date('Y-m-d H:i:s');

  if(trim($status)=="Check-In"){
	  
	$allgatepass = $this->usermodel->populateallarray('gatepass','id',$passid);
		//$mycode=$allgatepass[0]['code'];


									
												$checkindata=array(		
			'userid'=>$userid,
				'visitorid'=>$passid,

				'category'=>"General",
				
				'subject'=>"",
				'createdate'=>$dateposted,
				'receiver'=>$allgatepass[0]['receiver'],
				'email'=>$allgatepass[0]['email'],

				'description'=>$allgatepass[0]['description'],
				
				'phone'=>$allgatepass[0]['phone'],


				'status'=>"Active",
				 'companyid'=>$allgatepass[0]['companyid'],

				'idno'=>$allgatepass[0]['idno'],
				
				'name'=>$allgatepass[0]['name'],
				'business'=>$allgatepass[0]['business'],
				'vehicleno'=>$allgatepass[0]['vehicleno'],
				'vehiclecolor'=>$allgatepass[0]['vehiclecolor'],
				'vehiclemodel'=>$allgatepass[0]['vehiclemodel'],
				'location'=>$allgatepass[0]['location'],
				'checkindate'=>$allgatepass[0]['checkindate'],
				
			
								);



	  
	  
	  	$data=array(		
			'updatedby'=>$userid,
			'status'=>"Active",
			'updateddate'=>$dateposted,

			'checkindate'=>$dateposted,

			
								);
	  
	  							$usr_result = $this->usermodel->add($checkindata,'checkin');

  }else{
	  
	  	$data=array(		
			'updatedby'=>$userid,
			
			'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,

			
								);
	  
	  
								$checkindata=array(		
													'updatedby'=>$userid,
			
			'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,
													);
								
									 $this->usermodel->updatedatabytwo($checkindata,'checkin','visitorid',$passid,'status',"Active");

  }
  
  
  				//
							$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$passid);

					 
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully checked  '.$status.' the guest..</div>');	
							redirect('user/viewgatepass');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Visitor   was not Updated.. Try again</div>');
								
								 redirect('user/viewgatepass');
							}
  
  
  
  
  
  
  
  
  
  
  
		
	
					$this->load->view('userdata/printserialcodes',$data);

		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function checkinoutgatepasshistory()
	{ 
	
	
	
	  if (!isset($_GET['passid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $passid = $_GET['passid'];
	      $status = $_GET['status'];
	      $userpassid = $_GET['userpassid'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	
 		  $dateposted = date('Y-m-d H:i:s');


	  
	  	$data=array(		
			'updatedby'=>$userid,
			
			'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,

			
								);
	  
	  
								$checkindata=array(		
				'updatedby'=>$userid,
			
			'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,
													);
								
									 $this->usermodel->updatedatabytwo($checkindata,'checkin','id',$passid,'status',"Active");

  

		   
  
  
  				//
							$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$userpassid);

					 
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully checked  '.$status.' the guest..</div>');	
							redirect('user/viewallgatepassandcheckins');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Visitor   was not Updated.. Try again</div>');
								
								 redirect('user/viewallgatepassandcheckins');
							}
  
  
  
  
  
  
  
  
  
  
  
		
	
					$this->load->view('userdata/printserialcodes',$data);

		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
		public function getviewstocktakingreportserial()
	{ 
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $branchid = $_GET['branchid'];
	      $companyid = $_GET['companyid'];
	      $startdate = $_GET['startdate'];
	      $closedate = $_GET['closedate'];

	
	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		// $data['companyid'] = $session_data['companyid'];
	// $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");
		//  $department = $this->input->post("department");

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
	//	$data['department']=$department;

	$data['branchid']=$branchid;
	
	$view="user/getviewstocktakingreportserial?branchid=". $branchid."&companyid=". $companyid."&closedate=". $closedate."&startdate=".$startdate."";

		        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['viewproducts'] = $this->usermodel->viewstocktakingreportserial($startdate,$companyid,$branchid);
		//var_dump($data['salesreport']);
		//exit;
	$data['startdate']=$startdate;
		$data['view']=$view;
				$this->load->view('userdata/viewtocktakingreportserial',$data);
		$this->load->view("template/footerpage");
	}
	}
	
		public function viewcountedserials()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $mybranch = $_GET['branch'];
	      $mycode = $_GET['randomitemidentifier'];
	      $startdate = $_GET['startdate'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          	//	$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;

$view="user/viewcountedserials?randomitemidentifier=". $mycode."&branch=". $mybranch."&startdate=".$startdate."";

				$data['viewproducts'] = $this->usermodel->viewstocountedserial($startdate,$companyid,$mybranch,$mycode);
			$data['view']=$view;
	$data['startdate']=$startdate;
				$this->load->view('userdata/viewtocktakingreportserial',$data);
	
	
				//$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	public function viewmissingserials()
	{ 
	
	
	
	  if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $mybranch = $_GET['branch'];
	      $mycode = $_GET['mycode'];
	      $startdate = $_GET['startdate'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          	//	$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;


  
		$data['companyid']=$companyid;
	$data['startdate']=$startdate;
				//$this->load->view('userdata/viewtocktakingreportserial',$data);

  				$data['viewserials'] = $this->usermodel->populatealldatanoarrayfourMissing("serials","companyid",$companyid,"status","new","code",$mycode,"branch",$mybranch);


						//$data['viewserials'] = $this->usermodel->populatealldatanoarraythree($startdate,$companyid,$mybranch,$mycode);

	
	
				$this->load->view('userdata/viewmissingserials',$data);
		$this->load->view("template/footerpage");
	
	}
	}
	
	
	
	
	
	
	
	
		public function viewmissingserials22()
	{ 
	
	
	
	  if (!isset($_GET['mycode'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	      $mybranch = $_GET['branch'];
	      $mycode = $_GET['mycode'];

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
								$data['mybranch'] = $mybranch;
				$data['mycode'] = $mycode;

					  		$data['viewserials']  = $this->usermodel->populatealldatanoarray('serials','branch', $mybranch,'status','new');

  
		
	
	
				$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
		public function viewallserials()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	  
		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
			

		$data['viewserials']= $this->usermodel->populateall('serials','invoice',$invoice_number);
  	  	//$data['viewserials']  = $this->usermodel->populatealldatanoarrayorderby('serials','id','ASC','code', $mycode,'itemid',$myid);


		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/viewallcurrentserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
  public function searchallserials()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 		$status = trim($this->usermodel->searchterm_handler($this->input->get_post('status', TRUE)));

		$branch = trim($this->usermodel->searchterm_handler($this->input->get_post('branch', TRUE)));
		 $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier1 = htmlspecialchars(trim($suppliers[0]));
		
		$supplier = trim($this->usermodel->searchterm_handler($supplier1));
		$type = trim($this->usermodel->searchterm_handler($this->input->get_post('type', TRUE)));

	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallproduct';
		$query = $this->usermodel->searchallserials($searchterm,$branch,$status,$limit,$companyid,$supplier,$type);

		$config['total_rows'] = $query['records'];
		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
							$data['viewserials'] = $query['data'];

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			 $this->load->view("template/tableheader");

$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewallcurrentserials',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 
	
		public function viewoldserials()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	      $myid = trim($_GET['myid']);
	      $myqty = $_GET['myqty'];
	      $mycode = trim($_GET['mycode']);

		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		$data['recaiving']= $this->usermodel->populateallarray('newstock','id',$myid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
				$data['myid'] = $myid;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;


		//$data['viewserials']= $this->usermodel->populateall('serials','invoice',$invoice_number);
  	  	$data['viewserials']  = $this->usermodel->populatealldatanoarrayorderby('serials','id','ASC','code', $mycode,'itemid',$myid);


		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/viewoldserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
		public function createserials()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	      $myid = $_GET['myid'];
	      $myqty = $_GET['myqty'];
	      $mycode = $_GET['mycode'];
    $branch = $_GET['branch'];
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
				$data['mybranch'] = $branch;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;
				$data['myid'] = $myid;


		$data['recaiving']= $this->usermodel->populateallarray('products','code',$mycode);

		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/createserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
	
	
		public function generateviewserials()
	{ 
	
	 	if (!$this->input->post('btn_GenerateSerial') == "generate")
					   {
						   

    
      show_error('No identifier provided', 500);
    }
    else {

	
	      $invoice_number = $_POST['invoice'];
		      $myid = $_POST['myid'];
	     // $myqty = trim($_POST['myqty']);
	
		 
		       $myqty =  (round($_POST['myqty'])) ;
		 
		    $startnumber = $_POST['startnumber'];
	      $mycode = $_POST['mycode'];

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
				$data['myid'] = $myid;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;
	$data['startnumber'] = $startnumber;

		$data['recaiving']= $this->usermodel->populateallarray('newstock','id',$myid);

		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/viewserials_az',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
		public function viewserials()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoice_number = $_GET['randomitemidentifier'];
	      $myid = $_GET['myid'];
	      $myqty = $_GET['myqty'];
	      $mycode = $_GET['mycode'];

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $invoice_number;
				$data['myid'] = $myid;
								$data['myqty'] = $myqty;
				$data['mycode'] = $mycode;


		$data['recaiving']= $this->usermodel->populateallarray('newstock','id',$myid);

		
	//$data['viewreceivings'] = $this->usermodel->getreceivings($invoice_number);
	
	
				$this->load->view('userdata/viewserials',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
  
			public function viewnewpurchaseorder()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['purchaseorder']= $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('newstock','invoice',$finalsalesid);
		$data['batch']= $this->usermodel->populateall('batchlist','invoice',$finalsalesid);

	
				$this->load->view('userdata/purchaseorder',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
		public function delivergoods()
	{ 
	

	  if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['invoice'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	       	$data['confirminvoice'] = $this->usermodel->populateallarray('sales','invoice',$finalsalesid);

	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		//$data['purchaseorder']= $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('sales_order','invoice',$finalsalesid);

	
				$this->load->view('userdata/delivergoods',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	
	
	
	
			public function viewnewsalesorder()
	{ 
	

	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	       	$data['confirminvoice'] = $this->usermodel->populateallarray('sales','invoice',$finalsalesid);
		$data['batch']= $this->usermodel->populateall('batchlist','invoice',$finalsalesid);

	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['purchaseorder']= $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('sales_order','invoice',$finalsalesid);

	
				$this->load->view('userdata/viewnewsalesorder',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
			public function viewmyasset()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
			 	$data['links'] = 0;

	 	
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('assets','invoice',$finalsalesid);
		$data['submain']= $this->usermodel->populateall('debitcredit','code',$finalsalesid);
$data['total_rows'] =count((array)$data['submain']);
	
				$this->load->view('userdata/viewmyasset',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function updatemyvaluation()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
			 	$data['links'] = 0;

	 	
		$data['finalsalesid'] = $finalsalesid;

		$data['main']= $this->usermodel->populateallarray('evaluation','id',$finalsalesid);
	
$data['total_rows'] =count((array)$data['main']);
	
				$this->load->view('userdata/updatemyvaluation',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function updatemyassessment()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
			 	$data['links'] = 0;

	 	
		$data['finalsalesid'] = $finalsalesid;

		$data['main']= $this->usermodel->populateallarray(' assessment','id',$finalsalesid);
	
$data['total_rows'] =count((array)$data['main']);
	//
				$this->load->view('userdata/updatemyassessment',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	public function updateasset()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
			 	$data['links'] = 0;

	 	
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('assets','id',$finalsalesid);
	
$data['total_rows'] =count((array)$data['main']);
	
				$this->load->view('userdata/updateasset',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
			public function viewmyjournalentry()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('journal','invoice',$finalsalesid);
			 $type=$data['main'][0]['incharge'];
		
		$data['submain']= $this->usermodel->populateall('debitcredit','code',$finalsalesid);
if( $type=="Single"){
					$this->load->view('userdata/viewjournalentrysingle',$data);

}else{
				$this->load->view('userdata/viewmyjournalentry',$data);
	
}
	
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
			public function editjournalentry()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
				   $data['allsalesdetails']= $this->usermodel->populateallarray('debitcredit','id',$finalsalesid);


	
				$this->load->view('userdata/editjournalentry',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
			public function viewnewbanking()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('banks','invoice',$finalsalesid);
		$data['submain']= $this->usermodel->populateall('statement','invoice',$finalsalesid);

	
				$this->load->view('userdata/viewnewbanking',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	public function editexpense()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	     
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('expenses','invoice',$finalsalesid);
		
		
		
		
		if($data['main']==false){
					$data['action'] = "insert";
					 $data['type'] = $_GET['type'];
		}else{
			$data['action'] = "update";
			
		}
		
		
		
			$data['viewdocuments']= $this->usermodel->populateall('documents','mydocuments',$finalsalesid);

		$data['submain']= $this->usermodel->populateall('statement','invoice',$finalsalesid);
		$data['mysubmain']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);


				$this->load->view('userdata/editexpense',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function editexpenserequest()
	{ 
	
	//
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('expenses','invoice',$finalsalesid);
		//$data['submain']= $this->usermodel->populateall('statement','invoice',$finalsalesid);
		
				$data['submain']= $this->usermodel->populatealldatawhere('statement','id','ASC','invoice',$finalsalesid);
			$data['viewdocuments']= $this->usermodel->populateall('documents','mydocuments',$finalsalesid);

		$data['mysubmain']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);


				$this->load->view('userdata/editexpenserequest',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function editbill()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['main']= $this->usermodel->populateallarray('expenses','invoice',$finalsalesid);
		$data['submain']= $this->usermodel->populateall('statement','invoice',$finalsalesid);
		$data['mysubmain']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);


				$this->load->view('userdata/editbill',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	public function viewpaidbills()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	
		$data['main']= $this->usermodel->populateallarray('expenses','invoice',$finalsalesid);
		$data['viecollection']= $this->usermodel->populateall('collection','invoice',$finalsalesid);
	


				$this->load->view('userdata/viewpaidbillslatest',$data);
		$this->load->view("template/footerpage");
	}
	}
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
	
	public function viewpaidsuppliers()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 	 
		$data['itemid'] = $finalsalesid;
	
		$data['main']= $this->usermodel->populateallarray('purchaseorder','invoice',$finalsalesid);
		$data['viecollection']= $this->usermodel->populateall('collection','invoice',$finalsalesid);
	


				$this->load->view('userdata/viewpaidbills',$data);
		$this->load->view("template/footerpage");
	}
	}
  
			public function viewnewquotation()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['purchaseorder']= $this->usermodel->populateallarray('quotation','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);
					//	$data['viewreceivings']  = $this->usermodel->populatealldatanoarrayorderby('purchaseorderlist','id',"asc",'invoice', $finalsalesid,'companyid', $companyid);

	
				$this->load->view('userdata/editquatation',$data);
		//$this->load->view("template/footerpage");
	}
	}
	
	
	
			public function editparceldelivery()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	
		$data['purchaseorder']= $this->usermodel->populateallarray('parceldelivery','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);

	
				$this->load->view('userdata/editparceldelivery',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
			public function editlease()
	{ 
	
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
	 
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		
	 
		$data['finalsalesid'] = $finalsalesid;
	 
	//$data['viewreceivings'] = $this->usermodel->getreceivings($finalsalesid);
		//$sale = $this->usermodel->populatealldataarray('purchaseorder', 'userid',$userid,'status','new');
		$data['purchaseorder']= $this->usermodel->populateallarray('lease','invoice',$finalsalesid);
		$data['viewreceivings']= $this->usermodel->populateall('purchaseorderlist','invoice',$finalsalesid);

	
				$this->load->view('userdata/editlease',$data);
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
				public function viewwholesales2()
	{ 
	$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
				$this->load->view("template/headerpagemin");
		          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $userid = $data['id'];
					  		$data['viewmaincategory']  = $this->usermodel->populatealldatanoarray('maincategory','companyid', $companyid,'status','active');

				$sale = $this->usermodel->populatealldataarray('sales_order', 'userid',$userid,'status','new');

			//$sale= $this->usermodel->getsales();
			
			$finalsalesid=0;
			 //$salesid=0;
 if($sale==FALSE){
	 	 	$finalsalesid = $userid.time();

	 	//$finalsalesid = $this->createRandomPassword();

	   //$finalsalesid=$salesid + 1;
 }else{
	 //$salesid=$sale[0]['id']; 
  // $finalsalesid=$salesid + 1;	
$finalsalesid=$sale[0]['invoice'];  
 }
    

	
	$finalsalesid = 'RS-'.rand(1000, 990000000).time();
	
		$data['salesid'] = $finalsalesid;
	$data['viewsales'] = $this->usermodel->getesales_order($finalsalesid,$userid);
				$this->load->view('userdata/viewwholesales',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
		
	
	
	
	  public function resetmysales() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 
		     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	  $view = trim($_GET['view']);
	    $salesid = trim($_GET['randomitemidentifier']);
	 // $transactionid = trim($_GET['transactionid']);
	   	  $type = trim($_GET['type']);
		  
		
		  
								$productdata=array(		
												'invoice'=>$salesid,
							'ordersales'=>"printed",
								'status'=>"new",

													);
		  
		  		$myusr_result = $this->usermodel->updatedatabytwo($productdata,'sales_orderraw','userid',$userid,'branch',$branchid);

								
						
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						 $this->session->set_flashdata('productmsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('productmsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect($view);
							}
  
  
  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
	}
	
	  }
	
	
	
	
  public function notavailable() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 
		     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 











			$this->load->view("template/headerpagemin");

$data['branchid']=$userid;
	
		//$this->load->view('userdata/nopayment');

		$this->load->view('notavailable',$data);


	
}
  }
	
	

  public function pendingsales() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		 
		     $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 











			$this->load->view("template/headerpagemin");

$data['branchid']=$userid;
	
		//$this->load->view('userdata/nopayment');

		$this->load->view('mypendingsales',$data);


	
}
  }
	
	  public function deletesoldeproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
	

		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	  $view = trim($_GET['view']);
	  	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

	  $salesid = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	   	  $type = trim($_GET['type']);
	  //$branch = trim($_GET['branch']);
		$myproducts=$this->usermodel->getesoldproductraw($transactionid);
		$mycode=$myproducts[0]['code'];
		$myqty=$myproducts[0]['qty'];
				$myserialname=$myproducts[0]['serial'];

		 $branch=$myproducts[0]['branch'];
	 //$ourinvoice=$myproducts[0]['invoice'];
		
		
		
	         $updatedat = date('Y-m-d H:i:s');

		
		// $productname = $this->usermodel->geteproductbyid($mycode);
													 $productname = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);

  
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$myqty);
    $myname=$productname[0]['name']; 

	//  $usr_result = $this->usermodel->deletedata($transactionid,"id","sales_order");
				



	
	
			$myrawdata=$this->usermodel->getesoldproductrawNoarray($transactionid);

	
	
	if(is_array($myrawdata)){

	
	   foreach($myrawdata as $row)
	   {
		   
		   $mystatus=$row->status;
	
	   $transactionid=$row->id; $itemid=$row->code;$totalqty=$row->qty;$mybranch=$row->branch;$mytotal=$row->amount;
		  $producttype=$row->producttype;
		

			 $mybprice=$row->bprice;
			  $correctqty=$row->qty;
			  $finalbprice=((double)$mybprice*(double)$correctqty);
			 
		$salesaccount=$row->salesaccount;
		  $costofgoodsold=$row->expenseaccount;
		   $inventoryaccount=$row->assetaccount;
	 
	   
	   
	      $myid=trim($row->id);
				
				
				
		$assetaccount=$row->assetaccount;
		$salesaccount=$row->salesaccount;
		$expenseaccount=$row->expenseaccount;
			$producttype=$row->producttype;	

			
				
				
				
				
				
		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$mytype=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;

		
		
		
		
		
		
		
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$row->userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
	   
	   //
		}
		
		
			
		$usr_result =$this->db->insert_batch('sales_ordercancelled', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
		
		
		
		
		
		
		
		
	}





				
					
	  $usr_result ="";
	  if($this->usermodel->deletedata($transactionid,"id","sales_orderraw")){
		  $usr_result =TRUE; 
		  
	  }else{
		  	  if($this->usermodel->deletedata($transactionid,"id","sales_orderraw")){
				 $usr_result =TRUE;   
				  
			  }else{
				  
				 $usr_result =false;   
			  }

		  
		  }
	  

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
														 $returnedproductsdata	=array(		
			'total'=>($myqty),
			'date'=>$updatedat,
				'name'=>$myname,
		  	'item_id'=>$mycode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$mycode,
				'stockfrom'=>$branch,
				'stockto'=>$branch,
				'type'=>$branch,
				'balance'=> $finalqty,
				'item_id1'=>$availableqty,
				'itemstatus'=>"returned",


								);
				$this->usermodel->add($returnedproductsdata,'newstock');


								
								
								
								//	$this->usermodel->deletedata($myproducts[0]['myinvoice'],"invoice","newstock");
		
								
								
								
								

								 $producttype=$productname[0]['orderamount']; 
								 
								 
if($producttype=="production"){
									
									$uomproducts = $this->usermodel->populatealldatanoarraythree('uomproducts','code', $mycode,'status',"child",'companyid',$companyid);

	if(is_array($uomproducts)){
	
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branch);
$mytotal = $myqty*$c->qty;
$availableuomqty=$myproductlist[0]['qty'];
	   $myfinalqty=($availableuomqty+$mytotal);
	   
	$myid =$myproductlist[0]['id'];

	//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);
	
							

	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$myfinalqty,
);	

			
	}
	$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');
							
						
							}		
								
								}
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								// $branch 
								 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);

									// $this->usermodel->updateproduct($productdata,$mycode); 
								if ($myserialname !="")
						   {
									$serialdata=array(		
						'status'=>"new",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$myserialname);

						   }

								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> cancelled successfully </div>');
						if($type=="retail"){
									
								redirect('user/viewsales');

								}else{
								redirect('user/viewwholesales');
									
								}
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
						if($type=="retail"){
									
								redirect('user/viewsales');

								}else{
								redirect('user/viewwholesales');
									
								}
												
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }	
	
	
	
	

	
	
	
	
  public function cancelsoldeproducts() {
  	if (!$this->input->post('btn_deletesales') == "solditems"){
		
		
					  

    
      show_error('No identifier provided', 500);
    }
    else {
	
	//
		  $password = $this->input->post("password"); 
	
	 $transactionid = $this->input->post("transactionid");
	  $type = $this->input->post("type");
	  $salesid = $this->input->post("randomitemidentifier");		  
		  $view = $this->input->post("view"); 

		$confirmuser = $this->usermodel->getcashiers($password);
				
							//check if email and password is correct
							if ($confirmuser < 1) //active user record is present
							{
									 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Error!</strong> Wrong Login Details. Try again </div>');
								if($type=="retail"){
									
								redirect($view);

								}else{			
								redirect($view);
								}
								return false;
									
								 
								 
								 
							}else{
								  $companyid=$confirmuser[0]->companyid;
								    
							 	$employeeno=$confirmuser[0]->id;
							
										  		  	      $suspendsales=$this->usermodel->populatuserpermissionsdataarray('sales','suspend',$employeeno);

										 if( $suspendsales !=true){
											 
											 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Error!</strong> You dont have right to Cancel or suspend sales. Request for Admin to help. Try again </div>');
								if($type=="retail"){
									
								redirect($view);

								}else{			
								redirect($view);
								}
								return false;
									
											 
											 
										 }else{
											 
										
								
								
								
							
	
	
	
	
	
	
	
	
	
	
	


		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	 // $view = trim($_GET['view']);
	  

	  //$salesid = trim($_GET['randomitemidentifier']);
	  //$transactionid = trim($_GET['transactionid']);
	   	  //$type = trim($_GET['type']);
	  //$branch = trim($_GET['branch']);
		$myproducts=$this->usermodel->getesoldproductraw($transactionid);
		$mycode=$myproducts[0]['code'];
		$myqty=$myproducts[0]['qty'];
				$myserialname=$myproducts[0]['serial'];

		 $branch=$myproducts[0]['branch'];
	
			$myrawdata=$this->usermodel->getesoldproductrawNoarray($transactionid);

	
	
	if(is_array($myrawdata)){

	
	   foreach($myrawdata as $row)
	   {
		   
		   $mystatus=$row->status;
	
	   $transactionid=$row->id; $itemid=$row->code;$totalqty=$row->qty;$mybranch=$row->branch;$mytotal=$row->amount;
		  $producttype=$row->producttype;
		

			 $mybprice=$row->bprice;
			  $correctqty=$row->qty;
			  $finalbprice=((double)$mybprice*(double)$correctqty);
			 
		$salesaccount=$row->salesaccount;
		  $costofgoodsold=$row->expenseaccount;
		   $inventoryaccount=$row->assetaccount;
	 
	   
	   
	      $myid=trim($row->id);
				
				
				
		$assetaccount=$row->assetaccount;
		$salesaccount=$row->salesaccount;
		$expenseaccount=$row->expenseaccount;
			$producttype=$row->producttype;	

			
				
				
				
				
				
		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
		$sprice=$row->sprice;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$mytype=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;

		
		
		
		
		
		
		
$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$row->userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
	   
	   //
		}
		
		
			
		$usr_result =$this->db->insert_batch('sales_ordercancelled', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
		
		
	}
		
		
		// $productname = $this->usermodel->geteproductbyid($mycode);
													 $productname = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);

  
   $availableqty=$productname[0]['qty']; 
   $finalqty=($availableqty+$myqty);
   

	  $usr_result = $this->usermodel->deletedata($transactionid,"id","sales_orderraw");
															
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 $producttype=$productname[0]['orderamount']; 
								 
								 
if($producttype=="production"){
									
									$uomproducts = $this->usermodel->populatealldatanoarraythree('uomproducts','code', $mycode,'status',"child",'companyid',$companyid);

	if(is_array($uomproducts)){
	
foreach ($uomproducts as $c){
	$uomcode=$c->uom;

	$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branch);
$mytotal = $myqty*$c->qty;
$availableuomqty=$myproductlist[0]['qty'];
	   $myfinalqty=($availableuomqty+$mytotal);
	   
	$myid =$myproductlist[0]['id'];

	//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);
	
							

	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$myfinalqty,
);	

			
	}
	$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');
							
						
							}		
								
								}
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								// $branch 
								 		 $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);

									// $this->usermodel->updateproduct($productdata,$mycode); 
								if ($myserialname !="")
						   {
									$serialdata=array(		
						'status'=>"new",

								);
								 $this->usermodel->updatedata($serialdata,'serials','serial',$myserialname);

						   }
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Sales cancelled successfully </div>');
								if($type=="retail"){
									
								redirect($view);

								}else{			
								redirect($view);
								
									
								}
								
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not cancelled  </div>');
						if($type=="retail"){
									
								redirect('user/viewsales');

								}else{
								redirect('user/viewwholesales');
									
								}
												
							
							}
	  
	  
	  
	  
	  
	  
	  
	  	
											
										}
								
								
										}
								
								
								

	}
  }	
	
	
	
	
	
	
	 public function confirmetimspurchase() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			 $session_data = $this->session->userdata('logged_in');

 	$data1['id'] = $session_data['id'];
        
		 $userid = $data1['id'];
	         $fromdate = date('Y-m-d H:i:s');
	         $updatedat = date('Y-m-d H:i:s');


    $data1['companyid'] = $session_data['companyid'];
	 $companyid = $data1['companyid'];
 $data1['branchid'] = $session_data['branchid'];
	 $branchid = $data1['branchid'];

	
	  $invoice_number = trim($_GET['randomitemidentifier']);
	
		   
		   
		   
		   
		   	    $purchase = $this->usermodel->populateallarray("purchaseorder",'invoice', $invoice_number);


				
		$availabletotal=$purchase[0]['amount'];
		   
		   //
		   
		   //...
		   
		   
		   
		   	    $peopledata = $this->usermodel->populateallarray("people",'id', $purchase[0]['supplier']);


		
		   
		   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
						   }	


$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
								   
							
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);

if($onlineoffline=="OSCU"){
        $apiUrl = ''.$etimsurl.'/etims-api/insertTrnsPurchase';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/trnsPurchase/savePurchases';

			 }
			   

//




	     // API endpoint URL

 $currentDate = date('YmdHis');
        $currentDateSt = date('Ymd');

$saleCount=0;
$myclosedproducts = $this->usermodel->accountinginventory($invoice_number);
	
	$saleCount=count((array)$myclosedproducts);

		if(is_array($myclosedproducts)){
	
	 foreach ($myclosedproducts as $detail){
		 		 
$transactionid=$detail->id;
$code=$detail->item_id;



		 	$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);
						$qty=$myreceivedproducts[0]['total'];

			$totalqty=$myreceivedproducts[0]['total'];
$supplier=$myreceivedproducts[0]['supplier'];
		$mycode=$myreceivedproducts[0]['item_id'];
				$branchid=$myreceivedproducts[0]['branchid'];

		

			$productname = $this->usermodel->populatealldataarray('products','code', $code,'companyid', $companyid);
	 
				$name=$productname[0]['name']; 
				$itemclassification=$productname[0]['itemclassification']; 
		  	$itemcode=$productname[0]['hscode'];
					  	$packagingunit =$productname[0]['packagingunit']; 
					  	$salesunit=$productname[0]['salesunit']; 
	   					  	$taxcode=$productname[0]['itemtax']; 			
								$buyingprice=$myreceivedproducts[0]['buyingprice'];
									$sellingprice=$myreceivedproducts[0]['sellingprice'];	
								$vatrate=$productname[0]['tax_included'];
		
		
		
		

        $taxableAmount = round(($sellingprice / (1 + ($vatrate / 100))), 2);
        $taxAmount = round(($sellingprice - $taxableAmount), 2);
		$TTtaxableAmount = round((($sellingprice / (1 + ($vatrate / 100))) * $qty), 2);
        $TTtaxAmount = round((($sellingprice - $taxableAmount)* $qty), 2);
		
		
$ttamount=$buyingprice * $qty;



//

            $data['itemSeq'] =  $myreceivedproducts[0]['itemSeq'];
            $data['itemCd'] = $itemcode;
            $data['itemClsCd'] = $myreceivedproducts[0]['itemClsCd'];
            $data['itemNm'] = $name;
            $data['bcd'] = $code;
            $data['pkgUnitCd'] = $myreceivedproducts[0]['pkgUnitCd'];
            $data['pkg'] = $totalqty;
				$data['qtyUnitCd'] = $myreceivedproducts[0]['uom'];

            //$data['qtyUnitCd'] = "KG";
            $data['qty'] = $totalqty;
            $data['prc'] = $myreceivedproducts[0]['buyingprice'];
//


            $data['spplrItemClsCd'] = $myreceivedproducts[0]['itemClsCd'];
            $data['spplrItemCd'] = $myreceivedproducts[0]['item_id1'];
            $data['spplrItemNm'] = $myreceivedproducts[0]['name'];

            $data['splyAmt'] = $ttamount;
            $data['dcRt'] = 0;
            $data['dcAmt'] = 0;
            $data['isr ccCd'] = null;
            $data['isrccNm'] = null;
            $data['isrcRt'] = null;
            $data['isrcAmt'] = null;
            $data['taxTyCd'] = $myreceivedproducts[0]['taxTyCd'];
			$data['taxblAmt'] =$myreceivedproducts[0]['taxable'];
            $data['taxAmt'] =$myreceivedproducts[0]['vat'];
            $data['totAmt'] =$ttamount;
			
            $data['itemExprDt'] = null;
            $pdetails[] = $data;
			
			
			
$this->SendStStockMaster($myreceivedproducts[0]['item_id'],$myreceivedproducts[0]['balance']);


$this-> SendStStockIO($code,$totalqty,$myreceivedproducts[0]['id'],0,"","","02");

			
			

        }
	}
	
	
        $data = [
            "tin" => $kra_pin,
            "bhfId" =>  $branch_id,
            "invcNo" =>(int) $purchase[0]['invoice'],
            "orgInvcNo" => (int)$purchase[0]['invoice'],
            "spplrTin" => $peopledata[0]['idnumber'],
            "spplrBhfId" => $peopledata[0]['city'],
            "spplrNm" => $peopledata[0]['company'],
            "spplrInvcNo" =>(int) $purchase[0]['invoice'],
            "salesTyCd" => "02",
            "pchsTyCd" => "N",
            "pchsDt" => date("Ymd", strtotime($purchase[0]['createdate'])),
            "pchsSttsCd" => "02",
            "regTyCd" => "M",
            "rcptTyCd" => "P",
            "pmtTyCd" => $purchase[0]['deliverymethod'],
            "salesSttsCd" => "02",
            "cfmDt" => $currentDate,
            "salesDt" => date("Ymd", strtotime($purchase[0]['createdate'])),
			

            "stockRlsDt" => date("Ymd", strtotime($purchase[0]['createdate'])),
            "cnclReqDt" => null,
            "cnclDt" => null,
            "rfdDt" => null,
            "rfdRsnCd" => null,
            "totItemCnt" => (int)$saleCount,
			
            "taxblAmtA" => $purchase[0]['EXEMPTED'],
            "taxblAmtB" => $purchase[0]['taxblAmtB'],
            "taxblAmtC" => $purchase[0]['ZERORATED'],
            "taxblAmtD" => $purchase[0]['taxblAmtD'],
            "taxblAmtE" => $purchase[0]['taxblAmtE'],
            "taxRtA" => $purchase[0]['taxRtA'],
            "taxRtB" => $purchase[0]['vatrate'],
            "taxRtC" => $purchase[0]['taxRtC'],
            "taxRtD" => $purchase[0]['taxRtD'],
            "taxRtE" => $purchase[0]['taxRtE'],
	
            "taxAmtA" => $purchase[0]['taxAmtA'],
            "taxAmtB" => $purchase[0]['taxAmtB'],
            "taxAmtC" => $purchase[0]['taxAmtC'],
            "taxAmtD" => $purchase[0]['taxAmtD'],
            "taxAmtE" => $purchase[0]['taxAmtE'],
            "taxAmt" => $purchase[0]['vat'],

            "totTaxblAmt" =>   $purchase[0]['taxable'],
            "totTaxAmt" =>  $purchase[0]['amount'],
            "totAmt" => $purchase[0]['amount'],
            "prchrAcptcYn" => "N",
            "remark" => null,

            "regrNm" => "Admin",
            "regrId" => "Admin",
            "modrNm" => "Admin",
            "modrId" => "Admin",
            "itemList" => $pdetails,

        ];


        // Convert the data to JSON format
        $jsonData = json_encode($data);








        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);


        // Check for cURL errors
        if (curl_errno($ch)) {
           
		
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS Import Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
				
		
		
		
		
		
} else {
            // Process the API response as needed
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];

             if ($resultCd == '000') {
						   
						
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
					<strong>Success!</strong> The import has been submitted to Etims </div>');
						redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
					
	   
						   
						   
						   
			}else{
			    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting  ETIMS imports Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   	
				
			}
		   
		}  
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   



	}
	
	
	 }

	
	
	
	
	 public function Etimsitemslookup() {
  
			 $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	         $fromdate = date('Y-m-d H:i:s');
	         $updatedat = date('Y-m-d H:i:s');


    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
						   }	


$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
								   
							
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


if($onlineoffline=="OSCU"){
  $apiUrl = ''.$etimsurl.'/etims-api/selectItemList';
	

			 }else{
			
			$apiUrl = ''.$etimsurl.'/items/selectItems';

			 }
			      



            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
				// "lastReqDt" => $currentDate
				"lastReqDt" => "20180722212803"


            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS code list:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewproducts');
						   

						   
						   return false;
				
				
				
            } else {
                // Process the API response as needed
                //return $response;
                $responseArray = json_decode($response, true);

                $resultCd = $responseArray['resultCd'];
                $resultMsg = $responseArray['resultMsg'];
                $resultDt = $responseArray['resultDt'];
				

				
				if ($resultCd == '000') {

$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock retreived successfully</div>');	
								//redirect($view);
						
							
						   redirect('user/viewproducts');
   
					
				}else{
					echo "NOT SENT";
					
				}
			}
				
	
	 
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	 public function comfirmstocktransfer() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			 $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	         $fromdate = date('Y-m-d H:i:s');
	         $updatedat = date('Y-m-d H:i:s');


    $data['companyid'] = $session_data['companyid'];
	 $branchid = $data['companyid'];

	

    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 
	  $invoice_number = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	   $mycode = trim($_GET['mycode']);
	 	   $view = ($_GET['view']);

		   
		   
		   		         $status = $_GET['status']; 
  $category = $_GET['category'];
		         $salestype = $_GET['salestype']; 
  		         $type = $_GET['type']; 

		         $tobranch = $_GET['tobranch']; 
		      $frombranch = $_GET['frombranch']; 

    	$this->load->view("template/headerpagemin", $data);
$data['invoice']=$invoice_number;
$data['type']=$type;
$data['salestype']=$salestype;

$data['tobranch']=$tobranch;
$data['frombranch']=$frombranch;
$data['status']=$status;
$data['category']=$category;
	   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   	$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);
			
			$totalqty=$myreceivedproducts[0]['total'];
$supplier=$myreceivedproducts[0]['supplier'];
		$mycode=$myreceivedproducts[0]['item_id'];
				$branchid=$myreceivedproducts[0]['branchid'];

		
				$branch=$myreceivedproducts[0]['type'];

		   
				
		
		   
		   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
						   }	


$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		

		
							
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);


if($onlineoffline=="OSCU"){
  $apiUrl = ''.$etimsurl.'/etims-api/selectStockMoveList';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/stock/selectStockItems';

			 }
			      



            // Data to send in the JSON format
            $data = [
                "tin" => $kra_pin,
                "bhfId" => $branch_id,
				// "lastReqDt" => $currentDate
				"lastReqDt" => "20180722212803"


            ];

            // Convert the data to JSON format
            $jsonData = json_encode($data);


            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('tin:' . $kra_pin,
                    'bhfId:' . $branch_id,
                    'cmcKey:' . $sign_key,
                    'Content-Type: application/json'

                ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute the cURL request
            $response = curl_exec($ch);


				
            // Check for cURL errors
            if (curl_errno($ch)) {


							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during getting ETIMS code list:'.curl_error($ch).'. Try again </div>');
								
						   redirect('user/viewetimscodelist');
						   

						   
						   return false;
				
				
				
            } else {
                // Process the API response as needed
                //return $response;
                $responseArray = json_decode($response, true);

                $resultCd = $responseArray['resultCd'];
                $resultMsg = $responseArray['resultMsg'];
                $resultDt = $responseArray['resultDt'];
				

				
				if ($resultCd == '000') {
					$this->SendStStockMaster($myreceivedproducts[0]['item_id'],$myreceivedproducts[0]['balance']);
$this->SendStStockIO($mycode,$totalqty,$myreceivedproducts[0]['id'],0,"","","04");

$this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> 	New stock Added successfully</div>');	
								//redirect($view);
						
							
	redirect('user/bulkdispatch?invoice='.$invoice_number.'&type='.$type.'&frombranch='.$frombranch.'&tobranch='.$tobranch.'&status='.$status.'&category='.$category .'&salestype='.$salestype);	
   
					
				}else{
					echo "NOT SENT";
					
				}
			}
					
					



//



//


	 
	 
		//echo$finalid=$latestid+1;
		


	
							  


		   
		}  
		   
		   
	 }   
		   
  	   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   



	
	
	
	
	
	
	
	 public function comfirmimportproductitems() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			 $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	         $fromdate = date('Y-m-d H:i:s');
	         $updatedat = date('Y-m-d H:i:s');


    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	
	  $invoice_number = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	   $mycode = trim($_GET['mycode']);
	   	   //$type = trim($_GET['type']);
		   
		   
		   
		    $purchasedata = $this->usermodel->populateallarray("purchaseorder",'invoice', $invoice_number);


				
		$availabletotal=$purchasedata[0]['amount'];
		
		   

		   
		   //
		   
		   
		   
		   
		   
		   
		   	$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);
			
			$totalqty=$myreceivedproducts[0]['total'];
$supplier=$myreceivedproducts[0]['supplier'];
		$mycode=$myreceivedproducts[0]['item_id'];
		
				$branchid=$myreceivedproducts[0]['branchid'];

		
				$branch=$myreceivedproducts[0]['type'];

		   
				
						 $productname = $this->usermodel->populatealldataarray('products','code', $mycode,'companyid', $companyid);

				$itemclassification=$productname[0]['itemclassification']; 
		  	$itemcode=$productname[0]['hscode'];		
		
		   
		
		   
		   
						  $configuration= $this->usermodel->populateallarray('etiminitialization','branchid',$branchid);
						  
						  
						  
						      if ($configuration ==false)
						   {
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your company has not been initialized on ETIMS. Try initialize it first through step 1 or call ROBISEARCH LTD for support </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
						   }											
							$combinedkey=trim($configuration[0]["tin"]).trim($configuration[0]["bhfid"]);
$finalverification =trim($this->encryption->decrypt(trim($configuration[0]["verification"])));
if(($finalverification=="")||($finalverification!=$combinedkey)){
	
	  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Your have not activated your etims. Try submit request to Robisearch team or call ROBISEARCH LTD for support :0790962631/0718667391/0780655987/0716413386</div>');
								
						   redirect('user/viewetiminitializemain');
						   return false;
	}
		
						  $kra_pin=trim($configuration[0]["tin"]);	   
$branch_id=trim($configuration[0]["bhfid"]);
$sign_key=trim($configuration[0]["cmcKey"]);
$mrcNo=trim($configuration[0]["mrcNo"]);
$etimsurl=trim($configuration[0]["url"]);
$onlineoffline=trim($configuration[0]["onlineoffline"]);
if($onlineoffline=="OSCU"){
        $apiUrl = ''.$etimsurl.'/etims-api/updateImportItem';
			

			 }else{
			
			$apiUrl = ''.$etimsurl.'/imports/updateImportItems';

			 }
			     


//



    $date = DateTime::createFromFormat('Y-m-d H:i:s', $myreceivedproducts[0]['date']);
      $importdate = $date->format('dmY');
     
	     // API endpoint URL

        $data = [
		 "tin" => $kra_pin,
           "bhfId" => $branch_id,
            "taskCd" => $myreceivedproducts[0]['taskCd'],
            "dclDe" => $importdate,
            "itemSeq" => $myreceivedproducts[0]['itemSeq'],
            "hsCd" => $myreceivedproducts[0]['item_id1'],
            "itemClsCd" => $itemclassification,
            "itemCd" => $itemcode,
            "imptItemSttsCd" => $myreceivedproducts[0]['imptItemsttsCd'],
            "remark" => "remark",
            "modrNm" => "Admin",
            "modrId" => "Admin"
        ];
		
		
		
		
		
		
		
		
		
		

		

        // Convert the data to JSON format
        $jsonData = json_encode($data);


        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
  // Check for cURL errors

        if (curl_errno($ch)) {
           
		
							    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting ETIMS Import Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   

						   
						   return false;
				
		
		
		
		
		
} else {
            // Process the API response as needed
            $responseArray = json_decode($response, true);

            $resultCd = $responseArray['resultCd'];
            $resultMsg = $responseArray['resultMsg'];
            $resultDt = $responseArray['resultDt'];

             if ($resultCd == '000') {
							
				   
		   $qtyDATAs=array(		
			

										
																  
									'itemstatus' => "etimsfinal", 
							
										);
										
										
			$usr_result=$this->usermodel->updateReceivings($qtyDATAs,$transactionid);
		   
		   
			
$this->SendStStockMaster($myreceivedproducts[0]['item_id'],$myreceivedproducts[0]['balance']);

//

		

	 
	 
		//echo$finalid=$latestid+1;
		

$this-> SendStStockIO($mycode,$totalqty,$myreceivedproducts[0]['id'],0,"","","01");

						$this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> The import has been submitted to Etims </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
					
	   
						   
						   
						   
			}else{
			    $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!  </strong>Error occurred during submitting  ETIMS imports Items :'.curl_error($ch).'. Try again </div>');
								
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
						   	
				
			}
		   
		}  
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   
		   



	}
	
	
	 }

	
	
	
	
	
	
	
	
	 public function deletereceivedproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			 $session_data = $this->session->userdata('logged_in');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	         $fromdate = date('Y-m-d H:i:s');
	         $updatedat = date('Y-m-d H:i:s');


    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	
	  $invoice_number = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	   $itemid = trim($_GET['itemid']);
	   	   $type = trim($_GET['type']);

	  		$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);
			
			$totalqty=$myreceivedproducts[0]['total'];
$supplier=$myreceivedproducts[0]['supplier'];
		//$myproducts=$this->usermodel->getallproductbyid($itemid);
		$mycode=$myreceivedproducts[0]['item_id'];
				$branchid=$myreceivedproducts[0]['branchid'];

		
				$branch=$myreceivedproducts[0]['type'];
				
									if($branch=="Main"){
						 $productlist = $this->usermodel->populatealldataarray('products','code', $mycode,'companyid', $companyid);

								}else{
						 $productlist = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);
	
								}
				
				

		$availableqty=$productlist[0]['qty'];
		
		
		
			
  
   $finalqty=($availableqty-$totalqty);
   
   if( $type=="return"){
	   	  //$usr_result = $this->usermodel->deletedata($transactionid,"id","newstock");
		  
		   $returndata=array(		
												
												'updatedby'=>$userid,
												'updatedat'=>$updatedat,
												'itemstatus'=>"returned",
													);
										 $usr_result =  $this->usermodel->updatedata($returndata,'newstock','id',$transactionid);
			
///








		
		$myclosedproducts = $this->usermodel->returnedinventory($invoice_number);
	  	$accountfinaltotalamount=0;
		if(is_array($myclosedproducts)){
				$this->usermodel->deletedatatwo("debitcredit","code",$invoice_number,"type","Supplier Credit Note");
	$finaltotalamount=0;
		
	 $insertdata = array();
$assetaccount="";
	 foreach ($myclosedproducts as $row){
		 		  $vattype=$row->tax;
		 		  $myid=$row->id;

		 
		  $myyqty=$row->total;
		 	 $myytotal=$row->buyingprice;
			  $currenttotal=$myyqty*$myytotal;
		$finaltotalamount=$finaltotalamount+ $currenttotal;
		
		
		 $transactionid=$row->id; 
		 
		 $accountcode = $this->usermodel->populateallarray('products','code', $row->item_id);
					$myassetaccount=$accountcode[0]['assetaccount'];
					 					   

		 		
	 //$assetaccount=$row->assetaccount;
 if($myassetaccount!=""){ $assetaccount=$myassetaccount;}else{ $assetaccount=1110; }

		
		
							
							$insertdata[]=array( 'userid'=>$userid,'account'=>$assetaccount,'credit'=>$currenttotal,'description'=>"Inventory Returned",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Supplier Credit Note",'refno'=> $row->item_id,'supplier'=> $supplier);


		
	
	 //
	 
	 
	 
	 
	 
		}
		

			if($finaltotalamount > 0){
				
				
				
				

		$usr_result =$this->db->insert_batch('debitcredit', $insertdata); 
		
		
$creditdata=array( 'userid'=>$userid,'account'=>2130,'debit'=>$finaltotalamount,'description'=>"Account payable Returned",'code'=>$invoice_number,'crateddate'=>$fromdate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Supplier Credit Note",'supplier'=> $supplier);

							$susr_result = $this->usermodel->add($creditdata,'debitcredit');

			}
		
		
		
		}
		
		























   }else{
		  $usr_result = $this->usermodel->deletedata($transactionid,"id","newstock");
  
   }
   
   //
															
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$productdata=array(		
												'qty'=>$finalqty,
													);
								
								
								
								
								if($branch=="Main"){
						$this->usermodel->updatedata($productdata,"products",'code',$mycode);

								}else{
																	 $this->usermodel->updateproductlist($productdata,$mycode,$branch) ; 
	
								}
								
								
								
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> The stock is  cancelled successfully </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not cancelled  </div>');
							redirect('user/viewreceivedproducts?randomitemidentifier='.$invoice_number);						   
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }



	
	
	
	
	
	 public function deletepurchasedproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $deltetable = trim($_GET['deltetable']);
	  $maintable = trim($_GET['maintable']);

	   $view = trim($_GET['view']);
	  $invoice_number = trim($_GET['randomitemidentifier']);
	   $itemid = trim($_GET['itemid']);
		 $myreceivedproducts = $this->usermodel->populateallarray($deltetable,'id', $itemid);


	  		//$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);
				$mytype=$myreceivedproducts[0]['type'];

			$currenttotal=$myreceivedproducts[0]['amount'];

		//$myproducts=$this->usermodel->getallproductbyid($itemid);
		
		

			 $productlist = $this->usermodel->populateallarray($maintable,'invoice', $invoice_number);


			
				
		$availabletotal=$productlist[0]['amount'];
		

		//$availableqty=$productlist[0]['qty'];
		
		
		//$finalamount=$availabletotal-$currenttotal;
			
 		$finalamount=(double)$availabletotal-(double)$currenttotal;

   
	  $usr_result = $this->usermodel->deletedata($itemid,"id",$deltetable);
															
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
						$this->usermodel->updatedata($amountdata,$maintable,'invoice',$invoice_number);

								
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> The stock is  cancelled successfully </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
							redirect($view);						   
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }

 public function deletedata() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $deltetable = trim($_GET['deltetable']);
	  $maintable = trim($_GET['maintable']);

	   $view = trim($_GET['view']);
	  $invoice_number = trim($_GET['randomitemidentifier']);
	   $itemid = trim($_GET['itemid']);
	      $fieldname = trim($_GET['fieldname']);
	 
		 $myreceivedproducts = $this->usermodel->populateallarray($deltetable,'id', $itemid);

	  		//$myreceivedproducts=$this->usermodel->geteeceivedproduct($transactionid);

			$currenttotal=$myreceivedproducts[0][$fieldname];

		//$myproducts=$this->usermodel->getallproductbyid($itemid);
		
		

			 $productlist = $this->usermodel->populateallarray($maintable,'invoice', $invoice_number);


			
				
		$availabletotal=$productlist[0]['amount'];
		

		//$availableqty=$productlist[0]['qty'];
		
		
		$finalamount=(double)$availabletotal-(double)$currenttotal;
			
 
   
	  $usr_result = $this->usermodel->deletedata($itemid,"id",$deltetable);
															
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
						$this->usermodel->updatedata($amountdata,$maintable,'invoice',$invoice_number);

								
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> The Data  is  cancelled successfully </div>');
							redirect($view);						   
					

							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
							redirect($view);						   
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }












public function splitpurchasebulk() {
 

$transactionid = $this->input->post("itemid");
	  $firstone = $this->input->post("firstone");
	  $secondone = $this->input->post("secondone");		  
		  $salesid = $this->input->post("invoice"); 
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];

	
	 // $salesid = trim($_GET['randomitemidentifier']);
	 // $transactionid = trim($_GET['transactionid']);
	 

		$productname=$this->usermodel->geteeceivedproduct($transactionid);


 
			
		$date=$productname[0]['date']; 

			$type=$productname[0]['type']; 
		$description=$productname[0]['description']; 
			$mycompanyid=$productname[0]['companyid']; 
			$invoice_number=$productname[0]['invoice_number']; 
		$tax=$productname[0]['tax']; 
		$code=$productname[0]['item_id']; 
	$supplier=$productname[0]['supplier'];




			
		$sellingprice=$productname[0]['sellingprice']; 

			$buyingprice=$productname[0]['buyingprice']; 
			$stockfrom=$productname[0]['stockfrom']; 
		$stockto=$productname[0]['stockto']; 
			$balance=$productname[0]['balance']; 
			$item_id1=$productname[0]['item_id1']; 
				$itemstatus=$productname[0]['itemstatus']; 
							$status=$productname[0]['status']; 

							$myuserid=$productname[0]['userid']; 







		$myqty=$productname[0]['total'];

		$qty=$productname[0]['qty'];
		
	
$firsttotal=(float)$firstone*(float)$sprice;
		  $secondtotal=$secondone*(float)$sprice;
		  
			$firsttax=(float)$firstone*(float)$tax;
			 $secondtax=(float)$secondone*(float)$tax;
			 
			 
			 
			 $totalqty=$firstone+$secondone;
			 
			 				   	 if ($totalqty!= $myqty) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>The total quantity you have put ('.$totalqty.') is not equal to original quantity('.$myqty.').Try again a diffent code.</div>');
								
								 redirect('user/viewreceivedproducts?randomitemidentifier='.$salesid);
								 return false;
							}
						 
			 
			 
			 									// redirect('/employee');

			
			
			
			
			
			
			
			
			
			
			
			
			
			
	
			  
			
			 
$firtdata=array(		
				'updatedat'=>$updatedat,
				'userid'=>$myuserid,
			'updatedby'=>$userid,
			'itemstatus'=>$itemstatus,
							'tax'=>$tax,
	'qty'=>$qty,
				'item_id'=>$code,
			'total'=>$firstone,
		  	'invoice_number'=>$invoice_number,
					  	'status'=>$status,

						'companyid'=>$mycompanyid,
'description'=>$description,
'type'=>$type,
			'date'=>$date,
			'supplier' => $supplier,		  
		  		    'sellingprice' => $sellingprice, 

		    'buyingprice' => $buyingprice, 
			     
  'stockfrom' => $stockfrom,		  
		  
		    'stockto' => $stockto, 
				
				'balance'=>$balance,
								'item_id1'=>$item_id1,
			
			
								);
								
		
		  $seconnddata=array(		
				'updatedat'=>$updatedat,
				'userid'=>$myuserid,
			'updatedby'=>$userid,
			'itemstatus'=>$itemstatus,
							'tax'=>$tax,
	'qty'=>$qty,
				'item_id'=>$code,
			'total'=>$secondone,
		  	'invoice_number'=>$invoice_number,
					  	'status'=>$status,

						'companyid'=>$mycompanyid,
'description'=>$description,
'type'=>$type,
			'date'=>$date,
			'supplier' => $supplier,		  
		  		    'sellingprice' => $sellingprice, 

		    'buyingprice' => $buyingprice, 
			     
  'stockfrom' => $stockfrom,		  
		  
		    'stockto' => $stockto, 
				
				'balance'=>$balance,
								'item_id1'=>$item_id1,
			
			
								);
		

		  
							 		  $usr_result =	  	 $this->usermodel->add($firtdata,'newstock');
										 		  $usr_result =	  	 $this->usermodel->add($seconnddata,'newstock');

	

		  
		        if($usr_result=true)
	{
			
					 	 $this->usermodel->deletedata($transactionid,"id","newstock");

						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully splited the transaction  !</div>');
								
								redirect('user/viewreceivedproducts?randomitemidentifier='.$salesid);	
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The prosuct sales was not splited. TRY AGAIN</div>');
								redirect('user/viewreceivedproducts?randomitemidentifier='.$salesid);	
							}









		  
								


	
}













public function splitproductsbulk() {


    
    
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];




$transactionid = $this->input->post("itemid");
	  $firstone = $this->input->post("firstone");
	  $secondone = $this->input->post("secondone");		  
		  $salesid = $this->input->post("invoice"); 










	
	//  $salesid = trim($_GET['randomitemidentifier']);
	 // $transactionid = trim($_GET['transactionid']);
	 
	   
	  	 // $serial = trim($_GET['serial']);

		$myproducts=$this->usermodel->getesoldproduct($transactionid);
		$code=$myproducts[0]['code'];
		$myqty=$myproducts[0]['qty'];
		$dateposted=$myproducts[0]['invoice'];
				$dateposted=$myproducts[0]['dateposted'];
	 $serial=$myproducts[0]['serial'];
					$taxcode=$myproducts[0]['taxcode'];

	 $branch=$myproducts[0]['branch'];
		$sprice=$myproducts[0]['sprice'];
	$salestype=$myproducts[0]['salestype'];
	
	 $address=$myproducts[0]['address'];
		$vattype=$myproducts[0]['vattype'];
	$type=$myproducts[0]['type'];
	 //$myqty=$myproducts[0]['qty'];

	$taxable=$myproducts[0]['taxable'];
		$taxindicator=$myproducts[0]['taxindicator'];
		 $uom=$myproducts[0]['uom'];
		$bprice=$myproducts[0]['bprice'];
	$taxable=$myproducts[0]['taxable'];
	
	$tax=($myproducts[0]['tax']/$myqty);
			//$amount=($myproducts[0]['amount']/$myqty);  

	 $tax2=$myproducts[0]['tax2'];
		$maincategory=$myproducts[0]['maincategory'];
	$category=$myproducts[0]['category'];
	
		//$data = array();
	
			$firsttotal=$firstone*$sprice;
		  $secondtotal=$secondone*$sprice;
		  
			$firsttax=$firstone*$tax;
			 $secondtax=$secondone*$tax;
			 
			  $ordersales=$myproducts[0]['ordersales'];

	 $status=$myproducts[0]['status'];
	 
	 
	 		   			
			$assetaccount=$myproducts[0]['assetaccount'];
		$salesaccount=$myproducts[0]['salesaccount'];
	$expenseaccount=$myproducts[0]['expenseaccount'];
	 $producttype=$myproducts[0]['producttype'];


			   
			   
			   
			   
			   
			   //
			 
			 $totalqty=$firstone+$secondone;
			 
			 				   	 if ($totalqty!= $myqty) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>The total quantity you have put ('.$totalqty.') is not equal to original quantity('.$myqty.').Try again a diffent code.</div>');
								
								 redirect('user/searchinvoice?code='.$salesid);
								 return false;
							}
						 
			 
			 
			 
			 
		$myinvoices = time(). $userid;	 
					$myinvoices1 =  $userid.time();	 
 
			 
			 
$firtdata=array(		
			'userid'=>$userid,
			
				'code'=>$code,
						'qty'=>$firstone,

					  	'serial'=>$serial,
			'taxcode'=>$taxcode,
'myinvoice'=>$myinvoices,
		  	'discount'=>0,
			
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 

		   'salestype' => $salestype, 
		     'invoice' => $salesid,  
		    'sprice' => $sprice, 
			      'amount' => $firsttotal, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
   'status' => $status, 
      'ordersales' => $ordersales,
			   			      'bprice' => $bprice, 
						'tax' => $firsttax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,
			   
			
								);
						
		  $seconnddata=array(

'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,
			   		  
			'userid'=>$userid,
			
				'code'=>$code,
			'qty'=>$secondone,
					  	'serial'=>$serial,
   'status' => $status, 
      'ordersales' => $ordersales,
		  	'discount'=>0,
			
			'taxcode'=>$taxcode,
'myinvoice'=>$myinvoices1,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 

		   'salestype' => $salestype, 
		     'invoice' => $salesid,  
		    'sprice' => $sprice, 
			      'amount' => $secondtotal, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 

			   			      'bprice' => $bprice, 
						'tax' => $secondtax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
							
		  
										 		  $usr_result =	  	 $this->usermodel->add($firtdata,'sales_order');
										 		  $usr_result =	  	 $this->usermodel->add($seconnddata,'sales_order');

	

		  
		        if($usr_result=true)
	{
					 	 $this->usermodel->deletedata($transactionid,"id","sales_order");

						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully splited the transaction  !</div>');
								
								redirect('user/searchinvoice?code='.$salesid);	
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The prosuct sales was not splited. TRY AGAIN</div>');
								redirect('user/searchinvoice?code='.$salesid);	
							}









		  
								


	
}

public function splitproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];

	
	  $salesid = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	 
	   
	  	  $serial = trim($_GET['serial']);

		$myproducts=$this->usermodel->getesoldproduct($transactionid);
		$code=$myproducts[0]['code'];
		$myqty=$myproducts[0]['qty'];
		$dateposted=$myproducts[0]['invoice'];
				$dateposted=$myproducts[0]['dateposted'];
	 $ordersales=$myproducts[0]['ordersales'];

	 $status=$myproducts[0]['status'];
	 
	 
	 
	 $branch=$myproducts[0]['branch'];
		$sprice=$myproducts[0]['sprice'];
	$salestype=$myproducts[0]['salestype'];
	
	 $address=$myproducts[0]['address'];
		$vattype=$myproducts[0]['vattype'];
	$type=$myproducts[0]['type'];
	 $myqty=$myproducts[0]['qty'];


	 $assetaccount=$myproducts[0]['assetaccount'];
		$salesaccount=$myproducts[0]['salesaccount'];
	$expenseaccount=$myproducts[0]['expenseaccount'];
	 $producttype=$myproducts[0]['producttype'];











	$taxable=$myproducts[0]['taxable'];
		$taxindicator=$myproducts[0]['taxindicator'];
		 $uom=$myproducts[0]['uom'];
		$bprice=$myproducts[0]['bprice'];
	$taxable=$myproducts[0]['taxable'];
		$taxcode=$myproducts[0]['taxcode'];

	$tax=($myproducts[0]['tax']/$myqty);
			$amount=($myproducts[0]['amount']/$myqty);  

	 $tax2=$myproducts[0]['tax2'];
		$maincategory=$myproducts[0]['maincategory'];
	$category=$myproducts[0]['category'];
	
		$data = array();
	
			$b=0;
		  for($i=0; $i< $myqty; $i++) {
			  $b++;
			
			
			$myinvoices = time(). $userid+ $b;
		
$data[]=array(		
'assetaccount'=>$assetaccount,
				'salesaccount'=>$salesaccount,
			'expenseaccount'=>$expenseaccount,	
			'producttype'=>$producttype,
			'userid'=>$userid,
			'myinvoice'=>$myinvoices,

				'code'=>$code,
			'qty'=>1,
					  	'serial'=>$serial,

		  	'discount'=>0,
			'companyid'=>$companyid,
						'companyid'=>$companyid,

			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $type,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 

		   'salestype' => $salestype, 
		     'invoice' => $salesid,  
		    'sprice' => $sprice, 
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,
					'taxcode' => $taxcode,
				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
								
		  }	
		  
		  
		
		  	  $usr_result =$this->db->insert_batch('sales_order', $data); 

		  
		        if($this->db->affected_rows() > 0)
	{
					 	 $this->usermodel->deletedata($transactionid,"id","sales_order");

						
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully splited the transaction  !</div>');
								
								redirect('user/searchinvoice?code='.$salesid);	
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The prosuct sales was not splited. TRY AGAIN</div>');
								redirect('user/searchinvoice?code='.$salesid);	
							}









		  
								


	}
}















public function deletereturnedeproducts() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];
	 /// $salestype = trim($_GET['salestype']);

	
	  $salesid = trim($_GET['randomitemidentifier']);
	  $transactionid = trim($_GET['transactionid']);
	   
	  	  $serial = trim($_GET['serial']);

		$myproducts=$this->usermodel->getesoldproduct($transactionid);
		$mycode=$myproducts[0]['code'];
		$myqty=$myproducts[0]['qty'];
		$code=$myproducts[0]['invoice'];
				 $branch=$myproducts[0]['branch'];
		$myamount=$myproducts[0]['sprice'];





$mybprice=$myproducts[0]['bprice'];
		$finaltotalamount=(double)$myamount*(double)$myqty;
				$salesaccountsalesaccount="";
				  
  $inventoryaccount="";
	$costofgoodsold="";	
				$ttbuying=(double)$mybprice*(double)$myqty;
		
		 $productcode = $this->usermodel->geteproductbyid($mycode);
					 $productname = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $branch);
$mysalesaccount=$productcode[0]['salesaccount'];
   $myinventoryaccount=$productcode	[0]['assetaccount']  ;
					  
			  $mycostofgoodsold=$productcode[0]['expenseaccount'] 	;	  
  















  
  									 if($myinventoryaccount!=""){ $inventoryaccount=$productcode[0]['assetaccount'];}else{ $inventoryaccount=1110; }	

   if($mysalesaccount!=""){ $salesaccount=$productcode[0]['salesaccount'];}else{ $salesaccount=4000; }

    if($mycostofgoodsold!=""){ $costofgoodsold=$productcode[0]['expenseaccount'];}else{ $costofgoodsold=5500; }
  
  
  
  
  
  
  
  								$saleshistory=$this->usermodel->populateallarray('sales','invoice', $salesid);
								
								
								
								 $supplier=$saleshistory[0]['customer']; 
									$creditnote=$saleshistory[0]['creditnote']; 

									  $originalsales=$saleshistory[0]['credit']; 
								
							
								
								
								

 $salestype=$saleshistory[0]['type']; 
  


 $producttype=$productname[0]['orderamount']; 
     $myname=$productname[0]['name']; 
$finalcreditnote=0;
$finalcreditnote=(double)$finaltotalamount+(double)$creditnote;


   $availableqty=$productname[0]['qty']; 
   $finalqty=((double)$availableqty+(double)$myqty);
   
   
	  //$usr_result = $this->usermodel->deletedata($transactionid,"id","sales_order");
	 $returndata=array(		
												
												'updatedby'=>$userid,
												'updatedat'=>$updatedat,
												'status'=>"returned",
													);
										 $usr_result =  $this->usermodel->updatedata($returndata,'sales_order','id',$transactionid);
			
				

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									 $returnedproductsdata	=array(		
			'total'=>($myqty),
			'date'=>$updatedat,
				'name'=>$myname,
		  	'item_id'=>$mycode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'description'=>$mycode,
				'stockfrom'=>$branch,
				'stockto'=>$branch,
				'type'=>$branch,
				'balance'=> $finalqty,
				'item_id1'=>$availableqty,
				'itemstatus'=>"returned",


								);
				$this->usermodel->add($returnedproductsdata,'newstock');


								
								
								
								
							
								
								
								if($producttype=="production"){
									
									$uomproducts = $this->usermodel->populatealldatanoarraythree('uomproducts','code', $mycode,'status',"child",'branch',$branchid);

	if(is_array($uomproducts)){
	
foreach ($uomproducts as $c){
	$uomcode=$c->uom;



	$myproductlist = $this->usermodel->populatealldataarray('productlist','code', $uomcode,'branch', $branchid);

$mytotal = $myqty*$c->qty;
$availableuomqty=$myproductlist[0]['qty'];
	   $finalqty=($availableuomqty+$mytotal);
	   
	$myid =$myproductlist[0]['id'];

	//$mytotalcost=  $mytotalcost+ ($mytotal*$myproductlist[0]['buyingprice']);
	
							

	$updateArray[] =array(	
	'id'=>$myid,													
'qty'=>$finalqty,
);	

			
	}
	$RESULT =	$this->db->update_batch('productlist',$updateArray, 'id');
							
			}	
			
								
								}
								
								if($serial!=""){
								 $serialdata=array(		
												
												'status'=>"new",
												
													);
						 $this->usermodel->updatedata($serialdata,'serials','serial',$serial);
								}
	

								
		
								
							
							
										$accountname=0;
										if(($salestype=="Credit")|| ($salestype=="Invoice")){
												
												$accountname=1100;
											}else{
											$accountname=1000;	
											}
						//$this->usermodel->deletedata($salesid,"code","debitcredit");
						//$this->usermodel->deletedatatwo("debitcredit","code",$invoice,"type","payment");

								
								//
								
								 $creditdata=array( 'userid'=>$userid,'account'=>$accountname,'credit'=>$finaltotalamount,'description'=>"Returned products",'code'=>$salesid,'crateddate'=>$updatedat,'branch' => $branchid,'companyid'=> $companyid,'type'=> "return" ,'supplier'=>$supplier);


							$debitdata=array( 'userid'=>$userid,'account'=>$salesaccount,'debit'=>$finaltotalamount,'description'=>"Returned products",'code'=>$salesid,'crateddate'=>$updatedat,'branch' => $branchid,'companyid'=> $companyid,'type'=> "return" ,'supplier'=>$supplier);

							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							$usr_result = $this->usermodel->add($creditdata,'debitcredit');	
													
													
							
										
									if(($producttype!="Service") && ($mybprice!="")){
	
			 $insertcostofgoodsolddata=array('refno'=>$mycode, 'userid'=>$userid,'account'=>$costofgoodsold,'credit'=>$ttbuying,'description'=>"Cost of goods returned",'code'=>$salesid,'crateddate'=>$updatedat,'branch' => $branchid,'companyid'=> $companyid, 'type'=> 'sales' ,'supplier'=>$supplier);
$insertinventorydata=array( 'userid'=>$userid,'account'=>$inventoryaccount,'debit'=>$ttbuying,'description'=>"Inventory retuned ",'code'=>$salesid,'crateddate'=>$updatedat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','supplier'=>$supplier);
	$this->usermodel->add($insertcostofgoodsolddata,'debitcredit');
		$this->usermodel->add($insertinventorydata,'debitcredit');	
										}


								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								
								$products=$this->usermodel->populateallarray('products','code', $mycode);
									
									$productname=$products[0]['name'];
								$mycustomer=$this->usermodel->populateallarray('people','id', $userid);
							$exactime = date('Y-m-d H:i:s');


			$myname=$mycustomer[0]['firstname'];

		 $actiondone=$myname ." Returned ". $myqty."   ". $productname." with code (". $mycode.") at ".$exactime;
								   $mydata = array(
									
									  'userid' => $userid,
									  	  'companyid' => $companyid,

									  		'ip' => $this->input->ip_address(),		
									
									  'actiondone' =>  $actiondone, 
									
									  'timedone' =>  Date('Y-m-d H:i:s') ,

								 );
								 			  	 $this->usermodel->add($mydata,'activityloggs');
												 
												
							
								$productdata=array(		
												'qty'=>$finalqty,
													);
													
													
								if($producttype !="production"){
									
																	$datasaved= $this->usermodel->updatedatabytwo($productdata,'productlist','code',$mycode,'branch',$branch);
	
									
								}else{
									
								$datasaved=TRUE;
								
								
	
								}
				
													

									//$datasaved=$this->usermodel->updateproduct($productdata,$mycode); 
								if ($datasaved ==TRUE) {
									
			
										$salesresult = $this->usermodel->getReturnesales_orderReceipt($salesid,$companyid);
									$mytotal=0;
															
				
										 if(is_array($salesresult)) 

										 {
					
											 
											 foreach ($salesresult as $c){
											$amount=$c->amount; 
											$mytotal=$mytotal+$amount;
											//$mycash=$mycash+$amount;
				
						
										}
									

										}
										
									
										 $sales_order= $this->usermodel->viewsalesconfirmation($companyid,$salesid);
										$myounts=$sales_order[0]["myamount"];
										
										$finalamounttosave= $originalsales-$finaltotalamount;
										$finalamounttosavecredit= $originalsales-$finaltotalamount;

										 
										 if($originalsales <= 0){
											 $finalamounttosavecredit=0;
											 
										 }
										if(( $salestype=="Invoice") || ($salestype=="Credit")){
												$mysalesdata=array(		
												'total'=>$mytotal,
												'credit'=>$finalamounttosavecredit,
												'creditnote'=>$finalcreditnote,

												'balance'=>"-".$finalamounttosave,
											'maindiscount'=>$myounts,
											'discountedtotal'=>$finalamounttosave,

													);
											
										}else{
											
												$mysalesdata=array(		
												'total'=>$mytotal,
												'cash'=>$mytotal,
												'creditnote'=>$finalcreditnote,

											//'maindiscount'=>$myounts,
											'discountedtotal'=>$myounts,

													);
											
										}
										
										

										
								//$mysalesresult = 	 $this->usermodel->updatedata($mysalesdata,'sales','id',4);
									$mysalesresult= $this->usermodel->updatedatabytwo($mysalesdata,'sales','invoice',$salesid,'companyid',$companyid);


		
		
		
		
		
		
			$people = $this->usermodel->populateallarray('people','id',$supplier);
									$customerbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
		$finalbalance=$customerbalance-$finaltotalamount;
		
								
							
								$peopledata=array(		
												'balance'=>$finalbalance,
													);
								
								
										$this->usermodel->updatedata($peopledata,'people','id',$peopleid);
		
		
		
						
								
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have  successfully returned the product. </div>');
								//redirect('user/mysales');
													redirect("user/searchinvoice?code=".$code);	

											if(( $salestype=="Invoice") || ($salestype=="Credit")){
																				//redirect("user/allcreditors");	
																			//	redirect("user/searchinvoice?code=".$code);	

											}else{
																				//redirect("user/searchinvoice?code=".$code);	

											}
							


									}
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Not deleted  </div>');
				redirect('user/searchinvoice');						
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }
	
	






















  
  public function clearbalance() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	
	  $salesid = trim($_GET['invoice']);
	  $productdata=array(		
	  										'ordersales'=>"printed",

												'paymentstatus'=>'Cleared',
													);
	  $usr_result = $this->usermodel->updatedata($productdata,'sales','invoice',$salesid);

	  

	  
					

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	 
								
								

								
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Sales was cleared successfully </div>');
								//redirect('user/searchinvoice',$code);
								redirect('user/searchinvoice?code='.$salesid);	


							
					
							
								
							}
							else 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sales was not cleared.It seemed it had been cleared or try again  </div>');
								redirect('user/searchinvoice?code='.$salesid);	
							
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  }
	
	
	
   
			public function viewsuppliers()
	{ 
				$this->load->view("template/headerpagemin");
		
		
	
		$data['viewsuppliers'] = $this->usermodel->populatesupplier();

				$this->load->view('userdata/viewsuppliers',$data);
		$this->load->view("template/footerpage");
	}
	

	
	
	
	
	
	
	
	
	
	
	 	public function viewallcreditors()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewpurchases');

			
					//$config['total_rows'] = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'status','Bill');
		$config['total_rows1'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','status','active');

											$config['total_rows'] = $this->usermodel->count_allwheredatathreebalance('purchaseorder','companyid',$companyid,'transactionstatus','closed');

		$config['per_page'] = '50000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
						$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
												$data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','status','active');

		 //$data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','companyid',$companyid,'status','purchases');
			     $data["viewpurchases"] = $this->usermodel->displayalldatathreebalance($config["per_page"], $page,'purchaseorder','companyid',$companyid,'transactionstatus','closed');


         $this->load->view("template/headerpagemin");
	 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["total_rows1"] =$config['total_rows1'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallcreditors',$data);
				
		$this->load->view("template/footerpage");
		
		
	
	}
	
	
	 	public function viewallcreditorssummary()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewpurchases');

			
					//$config['total_rows'] = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'status','Bill');
		$config['total_rows1'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','status','active');

											$config['total_rows'] = $this->usermodel->count_allwheredatathreebalance('purchaseorder','companyid',$companyid,'status','purchases');

		$config['per_page'] = '50000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
												$data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','status','active');

		 //$data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','companyid',$companyid,'status','purchases');
			     $data["viewpurchases"] = $this->usermodel->displayalldatathreebalance($config["per_page"], $page,'purchaseorder','companyid',$companyid,'status','purchases');


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["total_rows1"] =$config['total_rows1'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallcreditorssummary',$data);
				
		$this->load->view("template/footerpage");
		
		
	
	}
	
	 	public function viewpurchases()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

 
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	   $viewallcounters=$this->usermodel->populatuserpermissionsdataarray('purchases','viewallcounters',$userid);



		 $this->load->view("template/headerpagemin");

		$this->load->view("template/tableheader");

$config['base_url'] = base_url('Systemusers/viewpurchases');
 if( $viewallcounters==true){
$config['total_rows'] = $this->usermodel->count_wherepurchases('purchaseorder','companyid',$companyid,'id >',0);

 }else{
	$config['total_rows'] = $this->usermodel->count_wherepurchases('purchaseorder','companyid',$companyid,'branchid',$branchid);
 
	 
 }
  
 

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;



if( $viewallcounters==true){
		$data['viewpurchases'] = $this->usermodel->displayallpurchases($config["per_page"], $page,'purchaseorder','companyid',$companyid,'id >',0);

 }else{
		$data['viewpurchases'] = $this->usermodel->displayallpurchases($config["per_page"], $page,'purchaseorder','companyid',$companyid,'branchid',$branchid);
 
	 
 }



				
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewpurchases',$data);
				
		$this->load->view("template/footerpage");
		
	
	}
	
	
	
	
	
	
	public function mypaybill()
	{ 
		
			  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $mysupplier = $_GET['randomitemidentifier'];
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
	$finalsalesid = $userid.time();

 $data['finalsalesid']="BILL-".$finalsalesid;
				$config['base_url'] = base_url('Systemusers/paybill');
											$config['total_rows'] = $this->usermodel->count_allwheredatathree('expenses','companyid',$companyid,'type','Bill','supplier',$mysupplier);


		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewexpenses"] = $this->usermodel->displayalldatathree($config["per_page"], $page,'expenses','companyid',$companyid,'type','Bill','supplier',$mysupplier);

         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/paybill',$data);
				
		$this->load->view("template/footerpage");
	}
	}
	
	
	
	
	
	
	
	
	
	
		  public function viewmymembershipno() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

        		$data['member'] = $this->usermodel->populatemember($itemid);
   	$data['mycategory'] = $this->usermodel->populatecategory($userid);

    	$this->load->view("template/headerpagemin", $data);
$data['itemid']=$itemid;
		
		 $this->load->view('userdata/viewmymembershipno', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewmypurchases()
	{ 
	
	
	  if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $finalsalesid = $_GET['randomitemidentifier'];
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 



		 $this->load->view("template/headerpagemin");


$config['base_url'] = base_url('Systemusers/viewpurchases');
	

$config['total_rows'] = $this->usermodel->count_wherepurchases('purchaseorder','companyid',$companyid,'supplier',$finalsalesid);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
		$config['per_page'] = '200';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;


		$data['viewpurchases'] = $this->usermodel->displayallpurchases($config["per_page"], $page,'purchaseorder','companyid',$companyid,'supplier',$finalsalesid);

				
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewpurchases',$data);
				
		$this->load->view("template/footerpage");
		
	}
	}
	
	
	
	
	
	
	
	
	 	public function allpurchaseorder()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/allpurchaseorder');

			
			$config['total_rows'] = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'status','p.o');

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
	 	$finalsalesid = $userid.time();



  $ordernumber=0;
  	
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $format=$smsconfig[0]['website'];	
  $latest = $this->usermodel->populatelatestid('purchaseorder', 'id >',0);
  if($latest==FALSE){
	    $ordernumber=$ordernumber+1;
	  
  }else{
	  $mylatestid=$latest[0]['id']; 
	     $ordernumber= $mylatestid+1; 
  }
  

   $data['finalsalesid']=$finalsalesid;
    $data['ordernumber']=$format.$ordernumber;
  
  
  
  
  
  
  
		
		 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','companyid',$companyid,'status','p.o');



			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allpurchaseorder',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
		public function salesorder()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/salesorder');

			
							//$config['total_rows'] = $this->usermodel->count_allwhere('purchaseorder','companyid',$companyid);
							
							
				 $wiewallalesorder=$this->usermodel->populatuserpermissionsdataarray('salesorder ','viewall',$userid);

			
							
							
				 if( $wiewallalesorder==true){
 $config['total_rows'] = $this->usermodel->count_where('purchaseorder','companyid',$companyid,'status','s.o');

				 }else{
$config['total_rows'] = $this->usermodel->count_where('purchaseorder','userid',$userid,'status','s.o');
 
				 }
									
							
							
							
							

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
	 	$finalsalesid = $userid.$companyid.time();

 $data['finalsalesid']=$finalsalesid;

						
				 if( $wiewallalesorder==true){
		 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','companyid',$companyid,'status','s.o');

				 }else{
		 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'purchaseorder','userid',$userid,'status','s.o');
 
				 }
					

		
	
        //$data["viewpurchases"] = $this->usermodel->displayall($config["per_page"], $page,'purchaseorder','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/salesorder',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	 	public function allquatation()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	      $viewallquoation=$this->usermodel->populatuserpermissionsdataarray('quotation','viewall',$userid);

								$config['base_url'] = base_url('Systemusers/allquatation');

				if($viewallquoation==true){
					
								$config['total_rows'] = $this->usermodel->count_allwheredata('quotation','companyid',$companyid,'id >',0);
	
				}else{
					
									$config['total_rows'] = $this->usermodel->count_allwheredata('quotation','companyid',$companyid,'userid',$userid);

					
				}

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
	 	$finalsalesid = $userid.time();

 $data['finalsalesid']=$finalsalesid;
		
		
			if($viewallquoation==true){
					
			 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'quotation','companyid',$companyid,'id >',0);

				}else{
					
		 $data["viewpurchases"] = $this->usermodel->displayalldata($config["per_page"], $page,'quotation','companyid',$companyid,'userid',$userid);

					
				}

		

        //$data["viewpurchases"] = $this->usermodel->displayall($config["per_page"], $page,'quotation','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allquatation',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		public function viewbanktransfer()
	{ 
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/viewbanktransfer');
		$this->load->view("template/footerpage");
	}
	
	
	
		
		public function transfersms()
	{ 
		 $this->load->view("template/headerpagemin");
		
	

				$this->load->view('userdata/transfersms');
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	 	public function viewbanks()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewbanks');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('banks','companyid',$companyid);

	$finalsalesid = $userid.time();

 $data['finalsalesid']="BANK-".$finalsalesid;
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	

        $data["viewbanks"] = $this->usermodel->displayall($config["per_page"], $page,'banks','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewbanks',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	

	
	 	public function viewcheque()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewcheque');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('cheque','companyid',$companyid);

	$finalsalesid = $userid.time();

 $data['finalsalesid']="BANK-".$finalsalesid;
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	

        $data["viewcheque"] = $this->usermodel->displayall($config["per_page"], $page,'cheque','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewcheque',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	 	public function viewjournalentry()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewjournalentry');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('journal','companyid',$companyid);

	$finalsalesid = $userid.time();

 $data['finalsalesid']="JENTRY-".$finalsalesid;
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	

        $data["viewjournalentry"] = $this->usermodel->displayall($config["per_page"], $page,'journal','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewjournalentry',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	

	
	
	
	
	 	public function viewpayments()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewpayments');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('banks','companyid',$companyid);

	$finalsalesid = $userid.time();

 $data['finalsalesid']="BANK-".$finalsalesid;
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	

        $data["viewbanks"] = $this->usermodel->displayall($config["per_page"], $page,'banks','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewpayments',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	

	
	
	
	
	
	public function viewdamages()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewdamages');

			
			
							$config['total_rows'] = $this->usermodel->count_allwhere('damages','companyid',$companyid);

			
			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	

        $data["viewdamages"] = $this->usermodel->displayall($config["per_page"], $page,'damages','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewdamages',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	public function viewlease()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewdamages');

					$this->load->view("template/tableheader");

			
				$config['total_rows'] = $this->usermodel->count_allwheredata('lease','companyid',$companyid,'userid',$userid);

			
			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
         $this->load->view("template/headerpagemin");

		$this->load->view("template/tableheader");

	 $data["viewlease"] = $this->usermodel->displayalldata($config["per_page"], $page,'lease','companyid',$companyid,'userid',$userid);








      //  $data["viewlease"] = $this->usermodel->displayall($config["per_page"], $page,'lease','companyid',$companyid);

			
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewlease',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	public function viewparceldelivery()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewdamages');

					$this->load->view("template/tableheader");

			
				$config['total_rows'] = $this->usermodel->count_allwheredata('parceldelivery','companyid',$companyid,'id >',0);

			
			
			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
         $this->load->view("template/headerpagemin");

		$this->load->view("template/tableheader");

	 $data["viewlease"] = $this->usermodel->displayalldata($config["per_page"], $page,'parceldelivery','companyid',$companyid,'id >',0);







		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewparceldelivery',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function viewincomingstore()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewincomingstore');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('newstock','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
        $data["viewincomingstock"] = $this->usermodel->displayall($config["per_page"], $page,'newstock','companyid',$companyid);

				
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewincomingstore',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
		public function viewincomingstock()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewincomingstock');

				$config['total_rows'] = $this->usermodel->count_allwheredata('newstock','companyid',$companyid,'itemstatus <>',"sold");
						//	$config['total_rows'] = $this->usermodel->count_allwhere('newstock','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
       // $data["viewincomingstock"] = $this->usermodel->displayall($config["per_page"], $page,'newstock','companyid',$companyid);

					 $data["viewincomingstock"] = $this->usermodel->displayalldata($config["per_page"], $page,'newstock','companyid',$companyid,'itemstatus <>',"sold");
	
			
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewincomingstock',$data);
				
		$this->load->view("template/footerpage");
	
	}
	 	public function incomingstorestock()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/incomingstorestock');

			
							$config['total_rows'] = $this->usermodel->count_where('newstock','companyid',$companyid,'type','store');

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
        $data["viewincomingstock"] = $this->usermodel->displayalldata($config["per_page"], $page,'newstock','companyid',$companyid,'type','store');

				
			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/incomingstorestock',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
		
public function addupgrade()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$name = $this->input->post("name");
	  $version = $this->input->post("version");
	  $exactdate = $this->input->post("exactdate");		  
		  $package = $this->input->post("package");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   

		   				  		  $myview = $this->input->post("myview");   

				  		  $categoryid = $this->input->post("categoryid");   

  
				
			  		  $this->form_validation->set_rules("name", "Upgrade Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewupgrade', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_Upgrade') == "Upgrade")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'name'=>$name,
		  	'version'=>$version,
			
			
			'entrydate'=>$dateposted,
			'exactdate' => $exactdate,		  
		  'package' => $package,    
	
		  'description' => $description,   
		   
			
			    'companyid' => $companyid,  
				
			   			    'id' => $categoryid,  

				
			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'upgrade');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'upgrade','invoice',$categoryid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view.$invoice);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($myview);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
public function addbanks()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$bankname = $this->input->post("bankname");
	  $incharge = $this->input->post("incharge");
	  $paiddate = $this->input->post("paiddate");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   

		   				  		  $myview = $this->input->post("myview");   

				  		  $invoice = $this->input->post("invoice");   
				  		  $paiddatefrotime = $this->input->post("paiddatefrotime");   

  	  $paiddate=$paiddate." ".$paiddatefrotime;

				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbanks', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_bank') == "bank")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'bankname'=>$bankname,
		  	'incharge'=>$incharge,
			
			
			'entrydate'=>$dateposted,
			'paiddate' => $paiddate,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   
			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

				
			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'banks');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'banks','invoice',$invoice);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view.$invoice);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($myview);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
public function addchequebanks()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
$bankname1 = $this->input->post("bankname1");

$bankname2 = $this->input->post("bankname2");
	  $incharge = $this->input->post("incharge");
	  $paiddate = $this->input->post("paiddate");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action"); 

  $business = $this->input->post("business");
	  $chequenumber = $this->input->post("chequenumber");		  
		  $exactdate = $this->input->post("exactdate");   
		   $type = $this->input->post("type");		  
		  $status = $this->input->post("status");   
		  
	
if($type=="Outgoing"){
	$bankname = $bankname1;

	
}else{
	
		$bankname = $bankname2;

	
}


					  
				  		  $view = $this->input->post("view");   

		   				  		  $myview = $this->input->post("myview");   

				  		  $invoice = $this->input->post("invoice");   

  
				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewcheque', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postcheque') == "cheque")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'bankname'=>$bankname,
		  	'incharge'=>$incharge,
			'entrydate'=>$dateposted,
			'paiddate' => $paiddate,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   
			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

				
	'business'=>$business,
		  	'type'=>$type,
			'chequenumber'=>$chequenumber,
			'exactdate' => $exactdate,		  
		  'status' => $status, 
			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'cheque');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'cheque','invoice',$invoice);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Posted Cheque.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The cheque   was not posted... Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
public function addjojurnal()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$currency = $this->input->post("currency");
	  $journaldate = $this->input->post("journaldate");	
	  	  $journaldate1 = $this->input->post("journaldate");	

		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $myview = $this->input->post("myview");   

		   
				  		  $invoice = $this->input->post("invoice");   
  $paiddatefrotime = $this->input->post("paiddatefrotime");   

  	  $journaldate=$journaldate." ".$paiddatefrotime;
    $entrytype = $this->input->post("entrytype");   

				
			  		  $this->form_validation->set_rules("journaldate", "journal date", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewjournalentry', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_journalEntry') == "journal")
					   {
												$data=array(		
			'userid'=>$userid,
						'incharge'=>$entrytype,

		
			'currency'=>$currency,
		  	'journaldate'=>$journaldate,
			
			
			'entrydate'=>$journaldate,
		
		  'description' => $description,   
		   
			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

				
			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'journal');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'journal','invoice',$invoice);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
											
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  journal Entry.!</div>');
								
								 
					
								 redirect($view.$invoice);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Journal Entry  was not added/updated.. Try again</div>');
								
								 redirect($myview);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
public function addstatement()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $paymentmethodes = $this->input->post("paymentmethodes");
	  $refno = $this->input->post("refno");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   

		   
				  		  $invoice = $this->input->post("invoice");   

  
				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  
			  
			  	 $productlist = $this->usermodel->populateallarray('banks','invoice', $invoice);


			
				
		$availabletotal=$productlist[0]['amount'];
		

		//$availableqty=$productlist[0]['qty'];
		
		
		 $finalamount=$availabletotal+$amount;
			  
			  
			  
			  
			  
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbanking ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
						'supplier'=>$supplier,

			'crateddate'=>$dateposted,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   			    'paymentmethodes' => $paymentmethodes,  

			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

									    'branch' => $branchid,  

			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'statement');
							
							
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'banks','invoice',$invoice);
							
							
							
							
							
							

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'statement','invoice',$invoice);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									


$debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>"Supplier Bill",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid);


$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$amount,'description'=>"Supplier Bill",'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');






									
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
public function addnewbill()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 		 $mycode=0;

$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $paymentmethodes = $this->input->post("paymentmethodes");
	  $refno = $this->input->post("refno");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $code = $this->input->post("code");   
				  		  $myid = $this->input->post("myid");   

		   			  	  		  $tax = $this->input->post("tax");   

				  		  $invoice = $this->input->post("invoice");   

  
				
			  		  $this->form_validation->set_rules("action", "action", "trim|required");

			  
			  
			  
			  	 $productlist = $this->usermodel->populateallarray('expenses','invoice', $invoice);

		$datespent=$productlist[0]['datespent'];

				$supplier=$productlist[0]['supplier'];
				
		$availabletotal=$productlist[0]['amount'];
		

		//$availableqty=$productlist[0]['qty'];
		
		
		 $finalamount=$availabletotal+$amount;
			  
			  
			  
			  
			  
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbanking ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
						   
						     $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$vatrate=$myconfiguration[0]["tax1rate"]; 

									if ($this->input->post('code'))

					   {
						 $mycode=$code;   
						   
					   }else{
						   
						 $mycode=$mycode;   
  
						   
					   }
						   
						   
						   $finaltax=0; 
								 	 $vatable=0;
						   
						   		
					if($tax=="VATABLE"){
						
						if($mycode >0){
							  $mytax=1+($mycode/100); 
							
						}else{
						  $mytax=1+($vatrate/100); 	
							
							
						}
								
								  
								  
								 $vatable=($amount/$mytax);
								 $myfinaltax=(($amount-$vatable));
								
								$finaltax= $this->formatMoney(($myfinaltax), true);
								$vatable= $this->formatMoney(($vatable), true);

							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
							 
						   
						   
						   
						   
						   
												$updatedata=array(		
		
			'crateddate'=>$dateposted,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		 

				
			 
		   			    'code' => $mycode,  

				
							   
						   'tax'=>$tax,
'vat'=>$finaltax,
'vatable'=>$vatable,
			
								);
							
						   
						   
						   
						   
						   
						 
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
						'supplier'=>$supplier,

			'crateddate'=>$dateposted,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   			    'paymentmethodes' => $paymentmethodes,  

			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

				
			
								    'branch' => $branchid,  
		   			    'code' => $mycode,  

				
							   
						   'tax'=>$tax,
'vat'=>$finaltax,
'vatable'=>$vatable,
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'statement');
							
							
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($amountdata,'expenses','invoice',$invoice);
							
							
							
							
							
							

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($updatedata,'statement','id',$myid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							 if($action=="insert"){		

$debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>"Supplier Bill", 'type'=>"Invoiced Bills", 'code'=>$invoice,'crateddate'=>$datespent,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier);


$creditdata=array( 'userid'=>$userid,'account'=>2130,'credit'=>$amount,'description'=>"Supplier Bill", 'type'=>"Invoiced Bills", 'code'=>$invoice,'crateddate'=>$datespent,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$supplier);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');


							 }



									
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data was not updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
public function addexpensestatement()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $mycode=0;
$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $paymentmethodes = $this->input->post("paymentmethodes");
	  $refno = $this->input->post("refno");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $accounting = $this->input->post("accounting");   

		   				  		  $myid = $this->input->post("myid");   

				  		  $invoice = $this->input->post("invoice");   
				  		  $crateddate = $this->input->post("crateddate");   

  				  		  $mybank = $this->input->post("mybank");   
  				  		  $bankname = $this->input->post("bankname");   

			  	  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
	$vatrate=$myconfiguration[0]["tax1rate"]; 
				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  	  		  $tax = $this->input->post("tax");   

  				  		  $code = $this->input->post("code");   
			  
			  	 $productlist = $this->usermodel->populateallarray('expenses','invoice', $invoice);


				//	$datespent=$productlist[0]['datespent'];

									$datespent=	$crateddate;

		$availabletotal=$productlist[0]['amount'];
		
	$supplier=$productlist[0]['supplier'];
		$bankid=$productlist[0]['bankname'];
					 					$branchid=$productlist[0]['branchid'];

			  
			 
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbanking ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
						   
						   
						   
						   
						    	if ($this->input->post('code'))

					   {
						 $mycode=$code;   
						   
					   }else{
						   
						 $mycode=$mycode;   
  
						   
					   }
						   
						   
						   $finaltax=0; 
								 	 $vatable=0;
						   
						   		
					if($tax=="VATABLE"){
						
						if($mycode >0){
							  $mytax=1+($mycode/100); 
							
						}else{
						  $mytax=1+($vatrate/100); 	
							
							
						}
								
								  
								  
								 $vatable=($amount/$mytax);
								 $myfinaltax=(($amount-$vatable));
								
								$finaltax= $this->formatMoney(($myfinaltax), true);
								$vatable= $this->formatMoney(($vatable), true);

							
							 }else{
								 
									$finaltax=0; 
								 	 $vatable=0;
								 
							 }
							 
						   
						
						   
		
				
				

												$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
						'supplier'=>$supplier,

			'crateddate'=>$crateddate,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   			    'paymentmethodes' => $paymentmethodes,  

					    'branch' => $branchid,  
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  
			   			    'code' => $mycode,  

				
							   
						   'tax'=>$tax,
'vat'=>$finaltax,
'vatable'=>$vatable,
			
			
								);
							
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'statement');
							
								
								
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									
							
							
									$this->usermodel->updatedata($amountdata,'expenses','invoice',$invoice);

							
							
							
							

							}else 	if($action=="update"){
								
								$usr_result = $this->usermodel->updatedata($data,'statement','id',$myid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									
									if($accounting=="yes"){
										
									$debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$datespent,'branch' => $branchid,'companyid'=> $companyid,'transactioncode'=> $refno,'supplier'=>$supplier);


$creditdata=array( 'userid'=>$userid,'account'=>$mybank,'credit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$datespent,'branch' => $branchid,'companyid'=> $companyid,'transactioncode'=>  $refno,'supplier'=>$supplier);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');	
									}
			
	


									
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function addbankstatement()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $paymentmethodes = $this->input->post("paymentmethodes");
	  $refno = $this->input->post("refno");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   

		   				  		  $bankname = $this->input->post("bankname");   

				  		  $invoice = $this->input->post("invoice");   

  				  		  $mybank = $this->input->post("mybank");   

				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  
			  
			  	 $productlist = $this->usermodel->populateallarray('banks','invoice', $invoice);


					$paiddate=$productlist[0]['paiddate'];

				
		$availabletotal=$productlist[0]['amount'];
		

		$bankid=$productlist[0]['bankname'];
		
	
					  	 $glaccounts = $this->usermodel->populateallarray('glaccounts','number', $bankid);
						 $availablebalance=$glaccounts[0]['amount'];
	 $finalbalance=$availablebalance+$amount;
		
		 $finalamount=$availabletotal+$amount;
			  
			  
			   $nextglaccounts = $this->usermodel->populateallarray('glaccounts','number', $bankname);
						  $nextavailablebalance=$nextglaccounts[0]['amount'];
	 $nextfinalbalance=$nextavailablebalance+$amount;
		
		 //$nextfinalamount=$nextavailabletotal+$amount;
			  
			
			  
			  
		
			  
			  
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewnewbanking ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
												$data=array(		
			'userid'=>$userid,
			
							    'branch' => $branchid,  

			'account'=>$bankname,
			
						'supplier'=>$supplier,

			'crateddate'=>$dateposted,
			'refno' => $refno,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   			    'paymentmethodes' => $paymentmethodes,  

			
			    'companyid' => $companyid,  
				
			   			    'invoice' => $invoice,  

				
			
			
			
								);
							
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'statement');
							
								$bankdata=array(		
												'amount'=>$finalbalance,
													);
													$debitdata=array(		
												'amount'=>$nextfinalbalance,
													);
								
								$amountdata=array(		
												'amount'=>$finalamount,
													);
								
									$this->usermodel->updatedata($bankdata,'glaccounts','number',$bankid);
									$this->usermodel->updatedata($debitdata,'glaccounts','number',$bankname);

							
									$this->usermodel->updatedata($amountdata,'banks','invoice',$invoice);

							
							
							
							

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'statement','invoice',$invoice);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
		

$debitdata=array( 'userid'=>$userid,'account'=>$mybank,'debit'=>$amount,'description'=>"Bank Deposite",'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> $finalbalance);


$creditdata=array( 'userid'=>$userid,'account'=>$bankname,'credit'=>$amount,'description'=>"Bank Deposite",'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> $nextfinalbalance);



							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');


















								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated a new  Bank deposit.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank deposit  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
		public function savedoublejournal()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
$banknamecredit = $this->input->post("banknamecredit");
	  $amount = $this->input->post("amount");
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
		   				  		  $itemid = $this->input->post("itemid");   

				  		  $invoice = $this->input->post("invoice");   

				  		  $journaldate = $this->input->post("journaldate");   

    $type = $this->input->post("type");   
  $transactioncode = $this->input->post("transactioncode");  
				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  
			  	$code ="JENTRY-". $userid.time();



 $frombankaccount = $this->usermodel->populateallarray('glaccounts','number', $bankname);
 
 						 $accounttype=$frombankaccount[0]['description'];
						 
						

 
 
						 
						
		
			  
			  
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     								 redirect($view,$data);

		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
						 
	if(($amount==0) ||($amount=="")){
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  You must put amount more than zero or the amount can not be empty. Try again</div>');
								
								 redirect($view);
								 
								 return false;
							
						}
	if($banknamecredit==$bankname){
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  Debit account and Credit Account can not be the same. Please select two different accounts to debit and credit the same time. Try again</div>');
								
								 redirect($view);
								 
								 return false;
							
						}

							
								
												$debitdata=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
			'balance'=>0,

			'crateddate'=>$journaldate,
			'credit' => 0,		  
		  'debit' => $amount,    
	
		  'description' => $description,   
		  'code' => $invoice,   

		  'type' => $type,  
		  
		  'transactioncode' => $transactioncode,  
			
			  
				
			   			    'supplier' => $supplier,  
    'branch' => $branchid, 
				
			  'companyid' => $companyid,  
			
			
								);
							
							
							
							
							$creditdata=array(		
			'userid'=>$userid,
			
		
			'account'=>$banknamecredit,
			
			'balance'=>0,

			'crateddate'=>$journaldate,
			'credit' => $amount,		  
		    			'debit' => 0,		  

	
		  'description' => $description,   
		  'code' => $invoice,   

		  'type' => $type,  
		  
		  'transactioncode' => $transactioncode,  
			
			  
				
			   			    'supplier' => $supplier,  
    'branch' => $branchid, 
				
			  'companyid' => $companyid,  
			
			
								);
							
						
								 if($action=="insert"){
							
								$usr_result = $this->usermodel->add($creditdata,'debitcredit');
															$usr_result = $this->usermodel->add($debitdata,'debitcredit');

							
							
							
							

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'debitcredit','id',$itemid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								


					
							 $frombalance=$frombankaccount[0]['amount'];
						  $accountid=$frombankaccount[0]['id']; 

							
							 if($credit>0){
								   $finaltotal=$frombalance-$credit;

								$gldata=array(		
		
			'amount'=>$myfinaltotal,

								);
											
			
								$usr_result = $this->usermodel->updatedata($gldata,'glaccounts','id',$accountid);
 
								 
							 }
							  if($debit>0){
								     $finaltotal=$frombalance+$debit;

								$gldata=array(		
		
			'amount'=>$myfinaltotal,
			
				
								);
								 
								$usr_result = $this->usermodel->updatedata($gldata,'glaccounts','id',$accountid);
 
							 }
							 
						 



								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated journal entry.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Journal entry  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	public function savejournal()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];

$supplier = $this->input->post("supplier");

$bankname = $this->input->post("bankname");
	  $credit = $this->input->post("credit");
		  $debit = $this->input->post("debit");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
		   				  		  $itemid = $this->input->post("itemid");   

				  		  $invoice = $this->input->post("invoice");   

				  		  $journaldate = $this->input->post("journaldate");   

    $type = $this->input->post("type");   
  $transactioncode = $this->input->post("transactioncode");  
				
			  		  $this->form_validation->set_rules("bankname", "Bank Name", "trim|required");

			  
			  
			  	$code ="JENTRY-". $userid.time();



 $frombankaccount = $this->usermodel->populateallarray('glaccounts','number', $bankname);
 
 						 $accounttype=$frombankaccount[0]['description'];
						 
						

 
						 $JE = $this->usermodel->populateallarray('journal','Invoice', $invoice);
 
						 
						
		
			  
			  
			  
			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     								 redirect($view,$data);

		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_statment') == "statement")
					   {
						   $myfinaltotal="";
						   	 $previousbalance=$frombankaccount[0]['amount'];

						             if(($accounttype==1) && ($debit>0) || ($accounttype==5) && ($debit>0)){
									   $myfinaltotal=$previousbalance+$debit;
									   

							        }else if(($accounttype==1) && ($credit>0) || ($accounttype==5) && ($credit>0)){
									   $myfinaltotal=$previousbalance-$credit;

								   } 
								   if((($accounttype==3) && ($credit>0))|| (($accounttype==4)&& ($credit>0)) || (($accounttype==2) && ($credit>0))){
									   $myfinaltotal=$previousbalance+$credit;
									 		


								   }else if((($accounttype==3)&& ($debit>0)) || (($accounttype==4)&& ($debit>0))|| (($accounttype==2) && ($debit>0))){
									   $myfinaltotal=$previousbalance-$debit;
									
								   }
							
								
												$data=array(		
			'userid'=>$userid,
			
		
			'account'=>$bankname,
			
			'balance'=>$myfinaltotal,

			'crateddate'=>$journaldate,
			'credit' => $credit,		  
		  'debit' => $debit,    
	
		  'description' => $description,   
		  'code' => $invoice,   

		  'type' => $type,  
		  
		  'transactioncode' => $transactioncode,  
			
			  
				
			   			    'supplier' => $supplier,  
    'branch' => $branchid, 
				
			  'companyid' => $companyid,  
			
			
								);
							
						
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'debitcredit');
							
							
								
							
							
							
							
							

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'debitcredit','id',$itemid);

								}
								
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								


					
							 $frombalance=$frombankaccount[0]['amount'];
						  $accountid=$frombankaccount[0]['id']; 

							
							 if($credit>0){
								   $finaltotal=$frombalance-$credit;

								$gldata=array(		
		
			'amount'=>$myfinaltotal,

								);
											
			
								$usr_result = $this->usermodel->updatedata($gldata,'glaccounts','id',$accountid);
 
								 
							 }
							  if($debit>0){
								     $finaltotal=$frombalance+$debit;

								$gldata=array(		
		
			'amount'=>$myfinaltotal,
			
				
								);
								 
								$usr_result = $this->usermodel->updatedata($gldata,'glaccounts','id',$accountid);
 
							 }
							 
						 



								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully Added/Updated journal entry.!</div>');
								
								 
					
								 redirect($view);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Journal entry  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
		
  public function addglaccount()
    {
		
			
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 		 $amount = $this->input->post("amount");
				$accounttype = $this->input->post("accounttype");
			
		$accountname = $this->input->post("accountname");
				$bankname = $this->input->post("bankname");
				$openingdate = $this->input->post("openingdate");
				$currency = $this->input->post("currency");
								$number = $this->input->post("number");

								$action = $this->input->post("action");
								$accountingid = $this->input->post("accountingid");
								$savebalance = $this->input->post("savebalance");
								$accountstatus = $this->input->post("accountstatus");

				
			  		  $this->form_validation->set_rules("accountname", "account name ", "trim|required");
			  		  $this->form_validation->set_rules("accounttype", "account type ", "trim|required");

  $paiddatefrotime = $this->input->post("paiddatefrotime");    


		   
				    	  $openingdate=$openingdate." ".$paiddatefrotime;










			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     
 		 $this->load->view("template/adminheaderpage");
		$this->load->view("template/adminnave");
	

		
		 $this->load->view('admindata/addaccounts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_postgLaccount') == "account")
					   {
								
								
								
								
								
							 if($action=="insert"){	
	
	$confirmaccount = $this->usermodel->populateallarray('glaccounts','number', $number);
		
			if($confirmaccount!=false){
				
				
		
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> New GL Account  Code already exist.. Try use a different code</div>');
								
							redirect('user/allaccounting');	
								 return false;
				
				
			}

							 }


								
								
								
								
								
								
								
								
								
								
								
$acctype = $this->usermodel->populateallarray('glgroups','id', $accounttype);


						 $myaccounttype=$acctype[0]['accounttype'];
					$acctype = $this->usermodel->populateallarray('accounttype','id', $myaccounttype);
						 $description=$acctype[0]['id'];




								$data=array(		
		
			'amount'=>$amount,
				'accounttype'=>$accounttype,
		
		  	'description'=>$description,
		'accountname'=>$accountname,
			//'accountname'=>$accountname,
			'createdate'=>$dateposted,
			'bankname' =>$bankname,
				'openingdate' =>$openingdate,
				'currency'=>$currency,
					'number'=>$number,

				'userid'=>$userid,
				'companyid'=>$companyid,
								'accountstatus'=>$accountstatus,

								);
							
								 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'glaccounts');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'glaccounts','id',$accountingid);

								}
								
							
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{
if($savebalance=="yes"){
if($amount!=0){
		$debitdata=array(		
			'userid'=>$userid,
			
		'account'=>$number,
			'debit'=>$amount,
		  	'description'=>"Opening Balance",
								  	'code'=>"Opening Balance",

					 
			'balance'=>$amount,
			'crateddate'=>$openingdate,
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
									$creditdata=array(		
			'userid'=>$userid,
			
		'account'=>3010,
			'credit'=>$amount,
		  	'description'=>"Opening Balance Equity",
								  	'code'=>"Opening Balance Equity",

					 
			'balance'=>$amount,
			'crateddate'=>$openingdate,
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
						 $this->usermodel->add($creditdata,'debitcredit');
						 $this->usermodel->add($debitdata,'debitcredit');
	
}
}						
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new GL 	Account  ..</div>');	
							redirect('user/allaccounting');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> New GL Account   was not created.. Try again</div>');
								
							redirect('user/allaccounting');	
							}
					   }
					   else
					   {
							redirect('login/admin');
					   }
	    }
    }
	
	
	
	
	
	
  public function addglgroups()
    {
		
			
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		 		
		 	
				$accounttype = $this->input->post("accounttype");
			
		$accountname = $this->input->post("accountname");
				$groupname = $this->input->post("groupname");
			


				
			  		  $this->form_validation->set_rules("accountname", "account name ", "trim|required");
			  		  $this->form_validation->set_rules("accounttype", "account type ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     
 		 $this->load->view("template/adminheaderpage");
		$this->load->view("template/adminnave");
	

		
		 $this->load->view('admindata/glgroups', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_posglaccount') == "account")
					   {
												$data=array(		
		
			
				'accounttype'=>$accounttype,
		
		 
		'accountname'=>$accountname,
			
		
			'groupname' =>$groupname,
			
				
				'userid'=>$userid,
				'companyid'=>$companyid,
				
								);
							$usr_result = $this->usermodel->add($data,'glgroups');
							
							//check if branchname and password is correct
							if ($usr_result ==TRUE) //active branch record is present
							{

							
						
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new GL 	Account  ..</div>');	
							redirect('user/glgroups');	
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> New GL Account   was not created.. Try again</div>');
								
							redirect('user/glgroups');	
							}
					   }
					   else
					   {
							redirect('login/admin');
					   }
	    }
    }










   public function bulkpriceupdate()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$method = $this->input->post("method");
	  $category = $this->input->post("category");
		  $branch = $this->input->post("branch");    


		$amount = $this->input->post("amount");
	  $equalto = $this->input->post("equalto");
		  $description = $this->input->post("description");    
   		  $price = $this->input->post("price");    

				  
  
				
			  		  $this->form_validation->set_rules("method", "Method", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewproducts', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addbbulkpriceupdate') == "bulk")
					   {
						   
							if($branch=="Main"){
								        		$productname = $this->usermodel->bulkstoreupdate($category,$companyid,$branch,$equalto,$method);
			}else{
				

				
				   								$productname = $this->usermodel->bulkbranchupdate($category,$companyid,$branch,$equalto,$method);
			}	
								
								
				
						  
						  
						  $dateposted = date('Y-m-d H:i:s');

					
		$updatebookings = array();
		$savedpoints=0;
$updateArray = array();
						 if(is_array($productname)) 

 {
	 
	

	foreach ($productname as $pricerow){
		$finalbprice=0;
		$finalsprice=0;
		$finalwhprice=0;
					 $myid = $pricerow->id;
				  $sellingprice=$pricerow->sellingprice;	
			  $buyingprice=$pricerow->buyingprice;	

			  $wholesaleprice=$pricerow->wholesaleprice;	
			  
			  
			  if($method=="Percentage"){
	$finalbprice=((($amount /100)*$buyingprice)+$buyingprice);
		$finalsprice=((($amount /100)*$sellingprice)+$sellingprice);
		$finalwhprice=((($amount /100)*$wholesaleprice)+$wholesaleprice);
				  
				
				  
				
				
			  }else   if($method=="Amount"){
				  	$finalbprice=(($amount)+$buyingprice);
		$finalsprice=(($amount)+$sellingprice);
		$finalwhprice=(($amount)+$wholesaleprice);
				  
				  
				  
			  }else{
				  
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Select the correct option</div>');
					
			
				redirect('user/viewproducts');	  
				  
			  }
			  
			  
			  if( $price=="Selling"){
				  
										$updatestocktaingArray[]=array(		
												
											'sellingprice'=>$finalsprice,
													'userid'=>$userid,
																			'id'=>$myid,

													);
				  
				  
			  }else if( $price=="Wholesale"){
				  
				  
				  
										$updatestocktaingArray[]=array(		
																								
											'sellingprice'=>$finalsprice,
											'wholesaleprice'=>$finalwhprice,
													'userid'=>$userid,
							'id'=>$myid,

													);
				  
			  }else{
				  
				  

										$updatestocktaingArray[]=array(		
												
											'wholesaleprice'=>$finalwhprice,
													'userid'=>$userid,
																			'id'=>$myid,

													);
			  }
		
		
			
		
			 
			 
 }
 
 				if($branch=="Main"){
      	 $RESULT =	$this->db->update_batch('products',$updatestocktaingArray, 'id');
			}else{
				

				
      	 $RESULT =	$this->db->update_batch('productlist',$updatestocktaingArray, 'id');
			}	
				



 }
	
	        if($this->db->affected_rows() > 0)
	{
			
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You have Successfully updated the prices</div>');
					
			
				redirect('user/viewproducts');	
	}else{
		

			$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred!</strong> You have not updated the prices.Try again </div>');
redirect('user/viewproducts');					
		
	}

	
	
	

		
							
							
							
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }





   public function assignbank()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$name = $this->input->post("name");
	  $description = $this->input->post("description");
		  $type = $this->input->post("type");    

		  $branchid = $this->input->post("branchid");    
  $action = $this->input->post("action");
		  $categoryid = $this->input->post("categoryid");    
		  $code = $this->input->post("code");    

		   $finalbank="";
		   
				  
  	
				
			  		  $this->form_validation->set_rules("name", "Method Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbanks', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_assignbank') == "bank")
					   {
						  


if(($code =="") && ($type =="na")) {
  	
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you select bank or eneter alternative account  </div>');
								
								 redirect('user/accounting');
		return false;

}


if(($code !="") && ($type !="na")) {
  	
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you select na if you want to use alternative bank codes then try again or else enure alternative account is blank and you select right bank account</div>');
								
								 redirect('admin/viewallpaymentcharge');
		return false;

}	
if(($type =="na") && ($code =="")) {
	
	
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you enter account code/number in alternative field and select na  from Bank Account field then try again or else enure you select right bank account and and leave alternative account to be blank </div>');
								
								 redirect('admin/viewallpaymentcharge');
	return false;
}
						  		
if($code !=""){
   $finalbank=$code;	
	
}else{
	   $finalbank=$type;	

	
}

						   
						   
												$data=array(		
			'userid'=>$userid,
						'chargeid'=>$categoryid,

		
			'name'=>$name,
		  	'description'=>$description,
			
								'branchid'=>$branchid,


			'dateposted'=>$dateposted,
			'type' => $finalbank,		  
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
								
								
								
						 if($action=="insert"){
					
								$usr_result = $this->usermodel->add($data,'rentalpaymentmethodes');

						}else 	if($action=="update"){
							
				 $mycode = $this->input->post("mycode");    
	 $chargeid = $this->input->post("chargeid");
							$updatedata=array(		
			'userid'=>$userid,
						'chargeid'=>$chargeid,

		
			'name'=>$name,
		  	'description'=>$description,
			
								'branchid'=>$branchid,


			'dateposted'=>$dateposted,
			'type' => $finalbank,		  
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
								$usr_result = $this->usermodel->updatedata($updatedata,'rentalpaymentmethodes','id',$categoryid);

							}
							
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success! </strong> You have successfully assigned the charge to the bank!</div>');
								
								
									 if($action=="update"){

																	redirect('user/viewassignedbanks?mycode='.$mycode);																
 
									 }else{
																redirect('admin/viewallpaymentcharge');																
	 
									 }
								
								
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The assigning of the bank  was not successful.. Try again</div>');
								
								 redirect('admin/viewallpaymentcharge');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 


   public function addbank()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$name = $this->input->post("name");
	  $description = $this->input->post("description");
		  $type = $this->input->post("type");    

		  $branchid = $this->input->post("branchid");    
  $action = $this->input->post("action");
		  $categoryid = $this->input->post("categoryid");    
		  $code = $this->input->post("code");    

		   $finalbank="";
		   
				  
  	
				
			  		  $this->form_validation->set_rules("name", "Method Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbanks', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_newbank') == "bank")
					   {
						  


if(($code =="") && ($type =="na")) {
  	
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you select bank or eneter alternative account  </div>');
								
								 redirect('user/accounting');
		return false;

}


if(($code !="") && ($type !="na")) {
  	
		 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you select na if you want to use alternative bank codes then try again or else enure alternative account is blank and you select right bank account</div>');
								
								 redirect('user/accounting');
		return false;

}	
if(($type =="na") && ($code =="")) {
	
	
	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Please ensure you enter account code/number in alternative field and select na  from Bank Account field then try again or else enure you select right bank account and and leave alternative account to be blank </div>');
								
								 redirect('user/accounting');
	return false;
}
						  		
if($code !=""){
   $finalbank=$code;	
	
}else{
	   $finalbank=$type;	

	
}

						   
						   
												$data=array(		
			'userid'=>$userid,
			
		
			'name'=>$name,
		  	'description'=>$description,
			
								'branchid'=>$branchid,


			'dateposted'=>$dateposted,
			'type' => $finalbank,		  
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
								
								
								
						 if($action=="insert"){
					
								$usr_result = $this->usermodel->add($data,'paymentmethodes');

						}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'paymentmethodes','id',$categoryid);

							}
							
								
								
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success! </strong> You have successfully saved  payment method!</div>');
								
							redirect('user/accounting');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment method  was not saved.. Try again</div>');
								
								 redirect('user/accounting');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	      public function addbanktransfer()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
$paiddate = $this->input->post("paiddate");

$frombankname = $this->input->post("frombankname");
	  $description = $this->input->post("description");
		  $tobankname = $this->input->post("tobankname");    
		  $amount = $this->input->post("amount");    
		  $paiddatefrotime = $this->input->post("paiddatefrotime");    
		  $branchname = $this->input->post("branchname");    


$tocurrencyamount = $this->input->post("tocurrencyamount");
	  $tocurrency = $this->input->post("tocurrency");
		  $newcurrency = $this->input->post("newcurrency");  
		  $currency = $this->input->post("currency");  




	$code = "TRANS-".$userid.time();

		   
				    	  $paiddate=$paiddate." ".$paiddatefrotime;
  
				
			  		  $this->form_validation->set_rules("frombankname", "From bank Name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbanktransfer ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_banktransfer') == "bank")
					   {
						   
						   
						   
						      if( $frombankname==$tobankname){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not transfer money to the same bank .Try again.</div>');	
																						
							redirect('user/viewbanktransfer');	
																			return false;
																			   }
						   
					  	 $frombankaccount = $this->usermodel->populateallarray('glaccounts','number', $frombankname);
						 $frombalance=$frombankaccount[0]['amount'];
						  $fromid=$frombankaccount[0]['id'];
						 
						  	 $tobankaccount = $this->usermodel->populateallarray('glaccounts','number', $tobankname);
							  $toid=$tobankaccount[0]['id'];
						 $tobalance=$tobankaccount[0]['amount'];
						 
						 
	// $finaltobalance = $tobankaccount + $amount;
		
		 $finalfrombalance=$frombalance - $amount;
						   
			 $finaltobalance=$tobalance + $amount;			   
						   
		if(($tocurrencyamount > 0) &&  ($newcurrency !="")){
				
				
				
				$creditdata=array(		
			'userid'=>$userid,
			
		'account'=>$frombankname,
			'credit'=>$amount,
					'type'=>"Transfer",

		  	'description'=>$description,
								  	'code'=>$code,

					 			'balance'=>$finalfrombalance,


			'crateddate'=>$paiddate,
		
			    'companyid' => $companyid,  
				
			   
									 			'branch'=>$branchname,

			
			
			
								);				
								
								
								
								
								$debitdata=array(		
			'userid'=>$userid,
			
		'account'=>$tobankname,
			'debit'=>$tocurrencyamount,
		  	'description'=>$description,
					'type'=>"Transfer",

								  	'code'=>$code,

					 			'branch'=>$branchname,

			'balance'=>$finaltobalance,
			'crateddate'=>$paiddate,
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
	
	
	
}else{
	
				$creditdata=array(		
			'userid'=>$userid,
			
		'account'=>$frombankname,
			'credit'=>$amount,
		  		'description'=>$description,
					'type'=>"Transfer",
								  	'code'=>$code,

					 			'balance'=>$finalfrombalance,


			'crateddate'=>$paiddate,
		
			    'companyid' => $companyid,  
				
			   
									 			'branch'=>$branchname,

			
			
			
								);				
								
								
								
								
								$debitdata=array(		
			'userid'=>$userid,
			
		'account'=>$tobankname,
			'debit'=>$amount,
			'description'=>$description,
					'type'=>"Transfer",
								  	'code'=>$code,

					 			'branch'=>$branchname,

			'balance'=>$finaltobalance,
			'crateddate'=>$paiddate,
		
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
	
	
	
	
	}
		














			
						   
						   
						   
									
							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									$fromdata=array(		
												'amount'=>$finalfrombalance,
													);
									$todata=array(		
												'amount'=>$finaltobalance,
													);
								
									$this->usermodel->updatedata($todata,'glaccounts','id',$toid);
										$this->usermodel->updatedata($fromdata,'glaccounts','id',$fromid);
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully transfered the money!</div>');
								
							redirect('user/viewbanktransfer');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bank transfer   was not added.. Try again</div>');
								
								 redirect('user/viewbanktransfer');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
      public function addsmstransfer()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
$paiddate = $this->input->post("paiddate");

$toaccount = $this->input->post("toaccount");
	  $description = $this->input->post("description");
		  $fromaccount = $this->input->post("fromaccount");    
		  $amount = $this->input->post("amount");    

	$code = "TRANS-".$userid.time();

		   
				  
  							  		  $this->form_validation->set_rules("amount", "Total sms Unit", "trim|required");

							  		  $this->form_validation->set_rules("fromaccount", "From Employee name", "trim|required");

							  		  $this->form_validation->set_rules("toaccount", "To Employee name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/transfersms ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_smstransfer') == "sms")
					   {
						   
						   
						   
						      if( $fromaccount==$toaccount){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not transfer sms to the same employee .Try again.</div>');	
																						
							redirect('user/transfersms');	
																			return false;
																			   }
						   
					  	 $frombankaccount = $this->usermodel->populateallarray('people','id', $fromaccount);
						 $frombalance=$frombankaccount[0]['totalsms'];
						  $fromid=$frombankaccount[0]['id'];
						 
						  	 $tobankaccount = $this->usermodel->populateallarray('people','id', $toaccount);
							  $toid=$tobankaccount[0]['id'];
						 $tobalance=$tobankaccount[0]['totalsms'];
						 
						 
		
		 $finalfrombalance=$frombalance - $amount;
						   
			 $finaltobalance=$tobalance + $amount;			   
						   
						   
						   
						   
						   
						
								
									$smsdata=array(		
		
			
				'companyid'=>$companyid,
				'balance'=>$finaltobalance,
		  	'amount'=>0,
					  	'units'=>$amount,
					  	'balancebefore'=>$finalfrombalance,

				'description'=>$description,
			'code' => "Transfer",		  
		  'dateposted' => $paiddate,    
					 'userid' => $toaccount, 
	 'rate' => "Original Rate-Transfer", 
			
		  
								);
								
								
								
								
								
								
								
								
								
							$usr_result = $this->usermodel->add($smsdata,'recharge');

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
									$fromdata=array(		
												'totalsms'=>$finalfrombalance,
													);
									$todata=array(		
												'totalsms'=>$finaltobalance,
													);
								
									$this->usermodel->updatedata($todata,'people','id',$toid);
										$this->usermodel->updatedata($fromdata,'people','id',$fromid);
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully transfered the sms!</div>');
								
							redirect('user/transfersms');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Sms transfer   was not added.. Try again</div>');
								
								 redirect('user/transfersms');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
public function addaccounttype()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 

$name = $this->input->post("name");
	  $description = $this->input->post("description");
	  $type = $this->input->post("type");		  


		   
				  
  
				
			  		  $this->form_validation->set_rules("name", "Account type", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/accounttype', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_accounttype') == "account")
					   {
												$data=array(		
			'userid'=>$userid,
			
		
			'name'=>$name,
		  	'description'=>$description,
			


			'type' => $type,		  
	
		
			
			    'companyid' => $companyid,  
				
			   
				
			
			
			
								);
							$usr_result = $this->usermodel->add($data,'accounttype');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully added account type!</div>');
								
							redirect('user/accounttype');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Account type  was not added.. Try again</div>');
								
								 redirect('user/accounttype');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	
	

	
	
public function adddamages()
    {
		
			$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$entrydate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 


	$codes = explode(':=',$this->input->post("product"));

 
  $product = htmlspecialchars(trim($codes[0]));



	  $method = $this->input->post("method");

	  $mybranch = $this->input->post("branchname");
	 // $supplier = $this->input->post("supplier");


 $suppliers1 = explode(':=',$this->input->post("supplier"));

 
  $supplier = htmlspecialchars(trim($suppliers1[0]));


	  $incharge = $this->input->post("incharge");
	  $datedamaged = $this->input->post("datedamaged");		  
		  $qty = $this->input->post("qty");    
		    
		  $details = $this->input->post("details");   
		     
		   		  $from = $this->input->post("from");   
$mycode="";
								$serilalno="";
				 	$invoice = $userid.rand(100, 900).time();
	  
    // 
				
			  		  $this->form_validation->set_rules("product", "product details", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdamages', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_damage') == "damage")
					   {
						   
						  	if( $method=="Serial"){
						 $getserial = $this->usermodel->populatethreenoarray('serials','serial', $product,'status', "new",'companyid', $companyid);
	   $mycode=$getserial[0]['code'];
	   $serialid=$getserial[0]['id'];

							if( $from=="Main"){
											 $productname = $this->usermodel->populateallarray('products','code', $mycode);

				}else{
										 $productname = $this->usermodel->populatealldataarray('productlist','code', $mycode,'branch', $from);
	
				}
	

	
							}else{
						   
											if( $from=="Main"){
											 $productname = $this->usermodel->populateallarray('products','code', $product);

				}else{
										 $productname = $this->usermodel->populatealldataarray('productlist','code', $product,'branch', $from);
	
				}   
						   
							}	   
						   
						   	 if ($productname ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>The damaged product code you have entered does exist. Try again a diffent code.</div>');
								
								 redirect('user/viewdamages');
								 return false;
							}
						 
						
		$costofgoodsold="";
		$inventoryaccount="";
  
   $availableqty=$productname[0]['qty'];
   			$mybprice=$productname[0]['buyingprice']; 
				$sellingprice=$productname[0]['sellingprice']; 
	  	$myname=$productname[0]['name']; 
  if($costofgoodsold!=""){ $costofgoodsold=$accountcode[0]['expenseaccount'];}else{ $costofgoodsold=5500; }
 if($inventoryaccount!=""){ $inventoryaccount=$accountcode[0]['assetaccount'];}else{ $inventoryaccount=1110; }	  
					  
					    
			  
		 
			  
   $ttbrice=$mybprice*$qty;
   
   
   
	 if ($availableqty<$qty) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
		<strong>Error!</strong>The available quantity ('.$availableqty.') is less than the damaged product ('.$qty.') hence the damaged product could not be saved. Try again a diffent code.</div>');
								
								 redirect('user/viewdamages');
								 return false;
							}
						 
   
   $finalqty=($availableqty-$qty);
   
   	$damageddata=array(		
												'qty'=>$finalqty,
													
													);
													
																
											if( $method=="Serial"){
							   
							 $mycode=  $mycode;
							   
								
								$serilalno=$product;
									}else{
								$mycode=$product;
								$serilalno="n/a";


									}
										
												
										if($from=="Main"){
							$usr_result = $this->usermodel->updatedata($damageddata,'products','code',$mycode);

											}else{
												

															
			$usr_result = $this->usermodel->updatedatabytwo($damageddata,'productlist','code',$mycode,'branch',$from);

											}				
													
   
								
											
						   
						   
						   
						   
						   
						   
						   
						   
												$data=array(	


			'original'=>$availableqty,
		  	'balance'=>$finalqty,
		  	'user'=>$serilalno,

												
			'userid'=>$userid,
			
		
			'product'=>$mycode,
		  	'incharge'=>$incharge,
			
					  	'invoice'=>$invoice,

			'entrydate'=>$entrydate,
			'datedamaged' => $datedamaged,		  
		  'qty' => $qty,    
	
		  'details' => $details,   
		   
						    'branchid' => $mybranch,  

			    'companyid' => $companyid,  

			   			    'expendituretype' => $from,  
'buyingprice' => $mybprice,  

			   			    'ttbrice' => $ttbrice, 
				
		   'supplier' => $supplier, 
			
			
								);
							$usr_result = $this->usermodel->add($data,'damages');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
			$stockdata=array(	

'buyingprice'=>$mybprice,
			'sellingprice'=>$sellingprice,

			
			'total'=> "-".$qty,
			'date'=>$entrydate,
				'name'=>$myname,
		  	'item_id'=>$mycode,
			'userid'=>$userid,
			'companyid'=>$companyid,
				//'description'=>$code,
				'stockfrom'=>$from,
				'stockto'=>'Damaged product',
				'type'=>$mybranch,
				'balance'=>$finalqty,
				'item_id1'=>$availableqty,

				'description'=>$details,

								);
								
							$this->usermodel->add($stockdata,'newstock');

						
								
								
								
								
								
								
								
								 	if( $method=="Serial"){
										 	$serialdata=array(		
												'status'=>"damaged",
													
													);
									 $this->usermodel->updatedata($serialdata,'serials','id',$serialid);

									}
								
							
						
					
								
		if($ttbrice>0){
			$insertinventorydata=array('refno'=>$mycode, 'userid'=>$userid,'account'=>$inventoryaccount,'credit'=>$ttbrice,'description'=>"Inventory damaged",'code'=>$invoice,'crateddate'=>$entrydate,'branch' => $mybranch,'companyid'=> $companyid, 'type'=> 'creditnote');
			$usr_result = $this->usermodel->add($insertinventorydata,'debitcredit');

			
			
			
					$insertcostofgoodsolddata=array('refno'=>$mycode, 'userid'=>$userid,'account'=>$costofgoodsold,'debit'=>$ttbrice,'description'=>"Cost of goods damaged",'code'=>$invoice,'crateddate'=>$entrydate,'branch' => $mybranch,'companyid'=> $companyid,'type'=>'sales' );
					$usr_result = $this->usermodel->add($insertcostofgoodsolddata,'debitcredit');




}
								
								
								
								
								
								
								
								
								 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the damaged product.</div>');	
							redirect('user/viewdamages');														
								
																						
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Damaged product  was not added.. Try again</div>');
								
								 redirect('user/viewdamages');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	
	
public function addparceldelivery()
    {
		
			$session_data = $this->session->userdata('logged_in');
 	$data['branchid'] = $session_data['branchid'];
	 $mybranchid = $data['branchid'];
   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$entrydate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 


	$codes = explode(':=',$this->input->post("product"));

 
  $product = htmlspecialchars(trim($codes[0]));

	  $branchid = $this->input->post("branchid");

	   $view = $this->input->post("view");

	  $mode = $this->input->post("mode");
	  $riderdetails = $this->input->post("riderdetails");



	  $origin = $this->input->post("origin");
	  $dateposted = $this->input->post("dateposted");		  
		  $qty = $this->input->post("qty");    
		    
		  $details = $this->input->post("details");   
		     		   		  $amount = $this->input->post("amount");   
		     		   		  $duedate = $this->input->post("duedate");   
		   		  $receiveridno = $this->input->post("receiveridno");   
		   		  $invoice = $this->input->post("invoice");   

		   		  $from = $this->input->post("from");   
				  		   		  $mycategoryid = $this->input->post("mycategoryid");   
 

 $destination = $this->input->post("destination");   
						 $receiver = $this->input->post("receiver");   
						 $receiverphone = $this->input->post("receiverphone");   
						 $receiveraddress = $this->input->post("receiveraddress");   
						 $status = $this->input->post("status");   
						 $totalvalue = $this->input->post("totalvalue");   
						   						 $receiveremail = $this->input->post("receiveremail");   

		   		  $action = $this->input->post("action");   

$mycode="";
								$serilalno="";
				  
    
				
			  		  $this->form_validation->set_rules("dateposted", "date *posted", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewlease', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_parceldelivery') == "delivery")
					   {
						   
						   
						   
						 
 			$myincharge = explode(':=',$this->input->post("incharge"));

 
  $incharge = htmlspecialchars(trim($myincharge[0]));
   
						   
																
							
						   
						   
						   
						   
						

						
					
								
											
						   
						   
						   
						   $FINALduedate= $duedate." 23:59:59";
						   
						   
						   
						   
												$data=array(	


			'original'=>0,
		  	'balance'=>0,
		  	'serial'=>$serilalno,
		  	'mode'=>$mode,

												
			'userid'=>$userid,
			
					'riderdetails'=>$riderdetails,

			'receiveridno'=>$receiveridno,
		  	'customer'=>$incharge,
					  	'duedate'=>$FINALduedate,
					  	'amount'=>$amount,
			'origin'=>$origin,

										
						'destination'=>$destination,
						'receiver'=>$receiver,
					  	'receiverphone'=>$receiverphone,
					  	'receiveremail'=>$receiveremail,
						'receiveraddress'=>$receiveraddress,
						'status'=>$status,
					  	'totalvalue'=>$totalvalue,
			'entrydate'=>$entrydate,
			'dateposted' => $dateposted,	
				
		  'qty' => 0,    
		  'invoice' => $invoice,   

		  'details' => $details,   
		   
			    'branchid' => $branchid,  
			    'companyid' => $companyid,  

			   			    'branchfrom' => $from,  

				
			
			
			
								);
							
							
							
							
							
							
					
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'parceldelivery');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'parceldelivery','id',$mycategoryid);

								}
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
	
								 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully posted the Delivery.</div>');	
							
								
										 	$taskmessage = "Dear ". $receiver .",Your parcel with Tracking No: ". $invoice ."  has been dispatched ". $details;

								           $this->addallpushedsms($taskmessage,$receiverphone,($view.$invoice));

								
								
								
							
								
							
							
							
							redirect( $view.$invoice );														
																// redirect('user/editparceldelivery?randomitemidentifier='.$invoice.'&user/viewlease&customer='.$incharge);	

																						
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Delivery   was not posted.. Try again</div>');
							redirect( $view.$invoice );														

								 //redirect('user/viewparceldelivery');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	
public function addlease()
    {
		
			$session_data = $this->session->userdata('logged_in');
 	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$entrydate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 


	$codes = explode(':=',$this->input->post("product"));

 
  $product = htmlspecialchars(trim($codes[0]));



	  $method = $this->input->post("method");




	 // $incharge = $this->input->post("incharge");
	  $dateleased = $this->input->post("dateleased");		  
		  $qty = $this->input->post("qty");    
		    
		  $details = $this->input->post("details");   
		     		   		  $amount = $this->input->post("amount");   
		     		   		  $duedate = $this->input->post("duedate");   
		   		  $mode = $this->input->post("mode");   
		   		  $invoice = $this->input->post("invoice");   

		   		  $from = $this->input->post("from");   
				  		   		  $mycategoryid = $this->input->post("mycategoryid");   

		   		  $action = $this->input->post("action");   

$mycode="";
								$serilalno="";
				  
    
				
			  		  $this->form_validation->set_rules("dateleased", "date leased", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewlease', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_lease') == "lease")
					   {
						   
						   
						   
						 
 			$myincharge = explode(':=',$this->input->post("incharge"));

 
  $incharge = htmlspecialchars(trim($myincharge[0]));
   
						   
						   
						   
						   
						   
						   
						   
						
													
   
								
											
						   
						   
						   
						   $FINALduedate= $duedate." 23:59:59";
						   
						   
						   
						   
												$data=array(	


			'original'=>0,
		  	'balance'=>0,
		  	'serial'=>$serilalno,

												
			'userid'=>$userid,
			
		
			'product'=>$mycode,
		  	'incharge'=>$incharge,
					  	'duedate'=>$FINALduedate,
					  	'amount'=>$amount,

			
			'entrydate'=>$entrydate,
			'dateleased' => $dateleased,	
				
		  'qty' => 0,    
			  'mode' => $mode,   
		  'invoice' => $invoice,   

		  'details' => $details,   
		   
			    'branchid' => $branchid,  
			    'companyid' => $companyid,  

			   			    'branchfrom' => $from,  

				
			
			
			
								);
							
							
					
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'lease');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'lease','id',$mycategoryid);

								}
							
							
							
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 	if( $method=="Serial"){
										 	$serialdata=array(		
												'status'=>"used",
													
													);
									 $this->usermodel->updatedata($serialdata,'serials','id',$serialid);

									}
								
								
								
							
								
								
								 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully saved the Leased product.</div>');	
							//redirect('user/viewlease');														
																 redirect('user/editlease?randomitemidentifier='.$invoice.'&user/viewlease&customer='.$incharge);	

																						
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Leased product  was not added.. Try again</div>');
								
								 redirect('user/viewlease');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
	 	public function viewevents()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
								$config['base_url'] = base_url('Systemusers/viewevents');

			
							$config['total_rows'] = $this->usermodel->count_allwhere('events','companyid',$companyid);

			
		$config['per_page'] = '50';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
	
        $data["viewevents"] = $this->usermodel->displayallevents($config["per_page"], $page,'events','companyid',$companyid);

			
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewevents',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	

	
 	public function viedeals()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
 $data['category'] = $session_data['category'];
	 $category = $data['category'];
	
	 
				
				$config['base_url'] = base_url('Systemusers/viedeals');
			
							$config['total_rows'] = $this->usermodel->count_allwhere('deals','userid',$userid);

				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viedeals"] = $this->usermodel->displayall($config["per_page"], $page,'deals','userid',$userid);

			
		$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

		 

		 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 	$this->load->view("template/tableheader");

		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	
	
	
	
 	public function viewotherdeals()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewotherdeals');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('deals','companyid',$companyid);

				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viedeals"] = $this->usermodel->displayall($config["per_page"], $page,'deals','companyid',$companyid);

			
		$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	
	
	public function salesfollowups()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/salesfollowups');
				
				if($usertype=="admin"){
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','companyid',$companyid,'type',"Invoice");

				}else{
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','userid',$userid,'type',"Invoice");

				}
				

				
				
				
				
				
				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		if($usertype=="admin"){
				$data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','companyid',$companyid,'type',"Invoice");

				}else{
				  $data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','userid',$userid,'type',"Invoice");


				}

				

        // $this->load->view("template/headerpagemin");
		
		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallfollowups',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
 	public function viewallfollowups()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewallfollowups');
				
				if($usertype=="admin"){
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','companyid',$companyid,'type',"Deal");

				}else{
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','userid',$userid,'type',"Deal");

				}
				

				
				
				
				
				
				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		if($usertype=="admin"){
				$data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','companyid',$companyid,'type',"Deal");

				}else{
				  $data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','userid',$userid,'type',"Deal");


				}

				

        // $this->load->view("template/headerpagemin");
		
		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallfollowups',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	 public function ecommerce() {
		  		$session_data = $this->session->userdata('logged_in');

   if (!($session_data)){

    
      show_error('No identifier provided', 500);
    }
    else {

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
        
	
        		$data['configuration'] = $this->usermodel->populateallarray('contactdetails','companyid',$companyid);

        	

    	$this->load->view("template/headerpagemin", $data);
$data['userid']=$userid;
		$data['companyid']=$companyid;
		 $this->load->view('userdata/ecommerce', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
	
	 public function updateallecommerce()
    {
		
			$session_data = $this->session->userdata('logged_in');
  $data['id'] = $session_data['id'];
	 $userid = $data['id'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
				  $feedback = $this->input->post("feedback");		

			  $companyid = $this->input->post("companyid");		
 $businessname = $this->input->post("businessname");


		  $telegram = $this->input->post("telegram");		
 $privacy = $this->input->post("privacy");

	  $email = $this->input->post("email");
	  $location = $this->input->post("location");		  
 		  $barcode = $this->input->post("barcode");		
		    $aboutus = $this->input->post("aboutus");   
			 $currencysymbol = $this->input->post("currencysymbol");   
			   $returningpolicy = $this->input->post("returningpolicy");   
			    $deliverytitle = $this->input->post("deliverytitle");   
				 $delivery = $this->input->post("delivery");   
				  
				 $website = $this->input->post("website"); 
				 $privacytitle = $this->input->post("privacytitle"); 

			 $branches = $this->input->post("branches"); 

							 $aboutustitle = $this->input->post("aboutustitle"); 
							 $whyus = $this->input->post("whyus"); 


								 $workinghours = $this->input->post("workinghours");

				
				 $description = $this->input->post("description");
	  $returnpolicy = $this->input->post("returnpolicy");		  
		
						  $termstitle = $this->input->post("termstitle");		  
				  
							
												 
														$business = $this->input->post("business"); 						 


														$whyustitle = $this->input->post("whyustitle"); 						 



														$phone = $this->input->post("phone"); 						 


			$vision = $this->input->post("vision"); 
												 
						$mission = $this->input->post("mission"); 
												 
						$corevalues = $this->input->post("corevalues");
			$ourpromise = $this->input->post("ourpromise"); 



			$facebook = $this->input->post("facebook"); 
												 
						$twitter = $this->input->post("twitter"); 
												 
						$instagram = $this->input->post("instagram"); 						 
						$linkedin = $this->input->post("linkedin"); 
												 
						$youtube = $this->input->post("youtube"); 
												 
						$whatsapp = $this->input->post("whatsapp");
	 							 
	$terms = $this->input->post("terms"); 

	$otherlinktitle = $this->input->post("otherlinktitle"); 
												 
						$otherlinks = $this->input->post("otherlinks");

														$career = $this->input->post("career");
						$careertitle = $this->input->post("careertitle");
				 
				
				
			  		  $this->form_validation->set_rules("businessname", "First name", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/ecommerce', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateecommerce') == "ecommerce")
					   {
						   
						 
						   
												$data=array(
	'facebook'=>$facebook,
	'email'=>$email,
		'aboutustitle'=>$aboutustitle,
		'careertitle'=>$careertitle,
				'career'=>$career,
				'twitter'=>$twitter,
			'instagram' => $instagram,		 							 
						'linkedin' => $linkedin,	
							  	'otherlinktitle'=>$otherlinktitle,
				'otherlinks'=>$otherlinks,
										'terms'=>$terms,
			 
		  	'youtube'=>$youtube,
				'whatsapp'=>$whatsapp,
												
		  	'vision'=>$vision,
				'mission'=>$mission,
			'corevalues' => $corevalues,		 							 
						'ourpromise' => $ourpromise,	
																 
		 	 							 

	 							 
'branches' => $branches,		 							 
	    
		  		  'whyustitle'=>$whyustitle,
  'phone'=>$phone,
								

		  'workinghours'=>$workinghours,
	
		


				'businessname'=>$businessname,
	
				'description'=>$description,
			'returnpolicy' => $returnpolicy,		  
		
			
			'updatedat'=>$dateposted,
			'location' => $location,		  
		 'updatedby' => $userid,   
		    'aboutus' => $aboutus,   
			  
			    'deliverytitle' => $deliverytitle,  
				'delivery' => $delivery,   
				  
				 'website' => $website, 
				 'privacytitle' => $privacytitle, 
				 'userid' => $userid, 
		'privacy' => $privacy,
		'telegram' => $telegram,
	 	  	  'whyus' => $whyus,
	  	  'termstitle' => $termstitle,

	  	  'business' => $business,

		
								);
						
								$usr_result = $this->usermodel->updatedata($data,'contactdetails','companyid',$companyid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
						
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated  the Company settings..</div>');	
						 redirect('user/ecommerce');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Company settings  was not updated.. Try again</div>');
								
								 redirect('user/ecommerce');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	 	public function viewallcustomer()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewallcustomer');
				
				if($usertype=="admin"){
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','companyid',$companyid,'type',"Customer");

				}else{
							$config['total_rows'] = $this->usermodel->count_allwheredata('followups','userid',$userid,'type',"Customer");

				}
				

				
				
				
				
				
				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		if($usertype=="admin"){
				$data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','companyid',$companyid,'type',"Customer");

				}else{
				  $data["viewallfollowups"] = $this->usermodel->displayalldata($config["per_page"], $page,'followups','userid',$userid,'type',"Customer");


				}

				

        // $this->load->view("template/headerpagemin");
		
		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallfollowups',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
 	public function salesdue()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

    		  $todate = date('Y-m-d 23:59:59');

				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/salesdue');
		
				
if($usertype=="admin"){
		$config['total_rows'] = $this->usermodel->count_allwheredatafive('followups','companyid',$companyid,'status <>','Dont Call','nextdate <',$todate,'type',"Invoice",'completed',"no");

				}else{
		$config['total_rows'] = $this->usermodel->count_allwheredatafive('followups','userid',$userid,'status <>','Dont Call','nextdate <',$todate,'type',"Invoice",'completed',"no");

				}
				
		

				
				
				
				
				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

				

     if($usertype=="admin"){
		        $data["viewallfollowups"] = $this->usermodel->displayalldatafive($config["per_page"], $page,'followups','companyid',$companyid,'status <>','Dont Call','nextdate <',$todate,'type',"Invoice",'completed',"no");

				}else{
		        $data["viewallfollowups"] = $this->usermodel->displayalldatafive($config["per_page"], $page,'followups','userid',$userid,'status <>','Dont Call','nextdate <',$todate,'type',"Invoice",'completed',"no");

				}

		
		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallduefollowups',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
 	public function viewallcustomerdue()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

    		  $todate = date('Y-m-d 23:59:59');

				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewallcustomerdue');
		
				
if($usertype=="admin"){
		$config['total_rows'] = $this->usermodel->count_allwheredatafive('followups','companyid',$companyid,'status <>','Dont Call','nextdate <',$todate,'type',"Customer",'completed',"no");

				}else{
		$config['total_rows'] = $this->usermodel->count_allwheredatafive('followups','userid',$userid,'status <>','Dont Call','nextdate <',$todate,'type',"Customer",'completed',"no");

				}
				
		

				
				
				
				
				
		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

				

     if($usertype=="admin"){
		        $data["viewallfollowups"] = $this->usermodel->displayalldatafive($config["per_page"], $page,'followups','companyid',$companyid,'status <>','Dont Call','nextdate <',$todate,'type',"Customer",'completed',"no");

				}else{
		        $data["viewallfollowups"] = $this->usermodel->displayalldatafive($config["per_page"], $page,'followups','userid',$userid,'status <>','Dont Call','nextdate <',$todate,'type',"Customer",'completed',"no");

				}

		
		
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		
		
		
		
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallduefollowups',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	public function viewmoredealstoday()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

    		  $todate = date('Y-m-d 23:59:59');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

    		  $today = date('Y-m-d');

				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewmoredeals');
				if($usertype=="admin"){
		$config['total_rows'] = $this->usermodel->count_allwheredatathreeDeals('deals','companyid',$companyid,'status','Interested','todate',$today);

				}else{
		$config['total_rows'] = $this->usermodel->count_allwheredatathreeDeals('deals','userid',$userid,'status','Interested','todate',$today);

				}
				
		
		
				
				
				
				
				
				
				
		$config['per_page'] = '1000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		if($usertype=="admin"){
       // $data["viedeals"] = $this->usermodel->displayalldata($config["per_page"], $page,'deals','companyid',$companyid,'todate <',$todate);
		$data["viedeals"] = $this->usermodel->displayalldatathreeDeals($config["per_page"], $page,'deals','companyid',$companyid,'status','Interested','todate',$today);


				}else{
       // $data["viedeals"] = $this->usermodel->displayalldata($config["per_page"], $page,'deals','dealowner',$userid,'todate <',$todate);
		   
		   $data["viedeals"] = $this->usermodel->displayalldatathreeDeals($config["per_page"], $page,'deals','userid',$userid,'status','Interested','todate',$today);

				}
		$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

		 
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		 
		 
		 
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	
	
	public function viewmoredeals()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

    		  $todate = date('Y-m-d 23:59:59');

 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewmoredeals');
				if($usertype=="admin"){
		$config['total_rows'] = $this->usermodel->count_allwheredatathreeDealsDue('deals','companyid',$companyid,'id >',0,'todate <',$todate);

				}else{
		$config['total_rows'] = $this->usermodel->count_allwheredatathreeDealsDue('deals','userid',$userid,'id >',0,'todate <',$todate);

				}
				
		
		
				
				
				
				
				
				
				
		$config['per_page'] = '1000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		if($usertype=="admin"){
       // $data["viedeals"] = $this->usermodel->displayalldata($config["per_page"], $page,'deals','companyid',$companyid,'todate <',$todate);
		        $data["viedeals"] = $this->usermodel->displayalldatathreeDueDeals($config["per_page"], $page,'deals','companyid',$companyid,'id >',0,'todate <',$todate);

				}else{
       // $data["viedeals"] = $this->usermodel->displayalldata($config["per_page"], $page,'deals','dealowner',$userid,'todate <',$todate);
		        $data["viedeals"] = $this->usermodel->displayalldatathreeDueDeals($config["per_page"], $page,'deals','userid',$userid,'id >',0,'todate <',$todate);

				}
		$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

		 
		
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
		 
		 
		 
		 
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	
	
	
	
	
	
 
 	public function viewdocuments()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
							    $viewalldocuments=$this->usermodel->populatuserpermissionsdataarray('documents','viewalldocuments',$userid);

				$config['base_url'] = base_url('Systemusers/viewdocuments');
				if($viewalldocuments==true){
							$config['total_rows'] = $this->usermodel->count_allwhere('documents','companyid',$companyid);

				}else{
							$config['total_rows'] = $this->usermodel->count_allwhere('documents','userid',$userid);

				}
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
			if($viewalldocuments==true){
        $data["viewdocuments"] = $this->usermodel->displayall($config["per_page"], $page,'documents','companyid',$companyid);

				}else{
        $data["viewdocuments"] = $this->usermodel->displayall($config["per_page"], $page,'documents','userid',$userid);

				}
         $this->load->view("template/headerpagemin");
		//$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewdocuments',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
	
	
	
	
	
	
	
	
 
 
 	public function viewtasks()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewtasks');
				
				
							//$config['total_rows'] = $this->usermodel->count_allwherewithor('tasks',$userid);

		$config['total_rows'] = $this->usermodel->count_allwheredata('tasks','companyid',$companyid,'taskowner',$userid);





		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
       // $data["viewtasks"] = $this->usermodel->displayallwithor($config["per_page"], $page,'tasks',$userid);
        //$data["viewtasks"] = $this->usermodel->displayalldata($config["per_page"], $page,'tasks','companyid',$companyid,'taskowner',$userid);

				            $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','companyid',$companyid,'taskowner',$userid,"fromdate","DESC");

		///$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
 		$data["myview"]="Systemusers/viewtasks";

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	public function viewsupervisortasks()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				$data["myview"]="Systemusers/viewsupervisortasks";
				$config['base_url'] = base_url('Systemusers/viewsupervisortasks');
				
						$config['total_rows'] = $this->usermodel->count_allwheredata('tasks','companyid',$companyid,'controller',$userid);



		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
            $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','companyid',$companyid,'controller',$userid,"fromdate","DESC");

 
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
        // $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	public function viewmytasks()
	{ 
		
		   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['randomitemidentifier'];

   	$data['itemid'] = $itemid;
		
		
		
		
	

				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				$data["myview"]="Systemusers/viewsupervisortasks";
				$config['base_url'] = base_url('Systemusers/viewsupervisortasks');
				
						$config['total_rows'] = $this->usermodel->count_allwheredata('tasks','companyid',$companyid,'notification',$itemid);



		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
            $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','companyid',$companyid,'notification',$itemid,"fromdate","DESC");

 
		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
        // $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
	}
	}
 
	
	
	
	
	
	
	
	
	
 	public function pendingtasks()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewtasks');
				
				
							//$config['total_rows'] = $this->usermodel->count_allwherewithor('tasks',$userid);

$config['total_rows'] = $this->usermodel->count_allwheredata('tasks','status <>','Completed','taskowner',$userid);





		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
       // $data["viewtasks"] = $this->usermodel->displayallwithor($config["per_page"], $page,'tasks',$userid);
        //$data["viewtasks"] = $this->usermodel->displayalldata($config["per_page"], $page,'tasks','companyid',$companyid,'taskowner',$userid);

				            $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','status <>','Completed','taskowner',$userid,"fromdate","DESC");

		///$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

		  $data['category'] = $session_data['category'];
	 $category = $data['category'];
	 	 if($category=="reseller"){
			          $this->load->view("template/resellerpage");

		 }else{
			          $this->load->view("template/headerpagemin");

		 }
 		$data["myview"]="Systemusers/viewtasks";

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	
	
	
	
	
	
	public function viewothertasks()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				$data["myview"]="Systemusers/viewothertasks";
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewothertasks');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('tasks','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
    //    $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','companyid',$companyid);
            $data["viewtasks"] = $this->usermodel->displayalldatacustomedorder($config["per_page"], $page,'tasks','companyid',$companyid,'id >',0,'fromdate','DESC');

				
		$data['taskreceiver'] = $this->usermodel->populateall('people', 'companyid',$companyid);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	
	public function viewmydailyupdates()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewmydailyupdates');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('dailytasks','userid',$userid);

			$data["myview"]="Systemusers/viewmydailyupdates";
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["dailytasks"] = $this->usermodel->displayall($config["per_page"], $page,'dailytasks','userid',$userid);

				

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewmydailyupdates',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
	
	public function viewallotherdailyupdates()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				$data["myview"]="Systemusers/viewallotherdailyupdates";
				$config['base_url'] = base_url('Systemusers/viewallotherdailyupdates');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('dailytasks','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["dailytasks"] = $this->usermodel->displayall($config["per_page"], $page,'dailytasks','companyid',$companyid);

				

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewallotherdailyupdates',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
	
	public function viewotherfeedback()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];


				$data["myview"]="Systemusers/viewotherfeedback";
				
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewotherfeedback');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('taskdata','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["mytask"] = $this->usermodel->displayall($config["per_page"], $page,'taskdata','companyid',$companyid);

				        $data["mydocuments"] =false;


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewmoretasks',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
   
  public function resetproducts()
    {
		
			$qty = trim($this->input->get_post('qty', TRUE));

		
			$updatedata=array(		
		'qty'=>$qty,
		
	
								);
 	//$usr_result = $this->usermodel->add($data,'stock');
   							$usr_result = $this->usermodel->updatedata($updatedata,'products','id >',0);

	

							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully reset all products to zero (0)..</div>');	
										
													redirect('user/viewconfiguration');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Products was not updated.Try again</div>');
								
												redirect('user/viewconfiguration');	
	
							}
		
	}
 
 
 
 
 public function updateallaccounts()
    {
		
					$account = trim($this->input->get_post('account', TRUE));

										$accountname = trim($this->input->get_post('accountname', TRUE));

					
					
			$salesaccountdata=array(		
		'salesaccount'=>$account,
		
								);
						$expenseaccountdata=array(		
		'expenseaccount'=>$account,
		
								);	
$assetaccountdata=array(		
		'assetaccount'=>$account,
		
								);

								
								
 if($accountname=="salesaccount"){
	   							$usr_result = $this->usermodel->updatedata($salesaccountdata,'products','id >',0);
 
 }  else  if($accountname=="expenseaccount"){
	    							$usr_result = $this->usermodel->updatedata($expenseaccountdata,'products','id >',0);

 } else  if($accountname=="assetaccount"){
	    							$usr_result = $this->usermodel->updatedata($assetaccountdata,'products','id >',0);

 }

	

							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated all the products</div>');	
										
													redirect('user/viewconfiguration');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Products  was not updated.Try again</div>');
								
												redirect('user/viewconfiguration');	
	
							}
		
	}
 
 
 
 
 
 
 
 
  
   
  public function resetproductlist()
    {
		
					$qty = trim($this->input->get_post('qty', TRUE));
					$branchid = trim($this->input->get_post('branchid', TRUE));

			$updatedata=array(		
		'qty'=>$qty,
		
	
								);
 	//$usr_result = $this->usermodel->add($data,'stock');
	
	
	
	
	
	
	
	
	
	if($branchid=="all"){
		   							$usr_result = $this->usermodel->updatedata($updatedata,'productlist','id >',0);

		
	}else{
		
		   							$usr_result = $this->usermodel->updatedata($updatedata,'productlist','branch',$branchid);

		
	}

	

							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully reset all stocklist to zero (0)..</div>');	
										
													redirect('user/viewconfiguration');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Stocklist was not updated.Try again</div>');
								
												redirect('user/viewconfiguration');	
	
							}
		
	}
 
 
 
 
 
 
 
 
 
   
  public function resetproductlistEtims()
    {
		
					$qty = trim($this->input->get_post('qty', TRUE));
					$branchid = trim($this->input->get_post('branchid', TRUE));
					$stocktype = trim($this->input->get_post('stocktype', TRUE));

			$updatedata=array(		
		'qty'=>$qty,
		
	
								);
	$stocklist  = $this->usermodel->populatethreenoarray('productlist','branch', $branchid,'itemclassification<>',"",'producttype <>', "Service");

		
if(is_array($stocklist)) {

   foreach($stocklist as $row)
   {
	      $code=trim($row->code);
	   if($stocktype=="yes"){
		   		$this->SendStStockMaster($code,$row->qty);   

	   }else{
		   		$this->SendStStockMaster($code,$qty);   

	   }

		

		
   }
		 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully reset all stocklist in the etims..</div>');	
										
													redirect('user/viewconfiguration');	
	
														
   }	
	
	}
 
 
 
 
 
 
	
	
			public function viewcustomers()
	{ 
				$this->load->view("template/headerpagemin");
		
		
	
		$data['viewcustomers'] = $this->usermodel->populateviewcustomers();

				$this->load->view('userdata/viewcustomers',$data);
		$this->load->view("template/footerpage");
	}
	
			public function viewemployees()
	{ 
				$this->load->view("template/headerpagemin");
		
		
	
		$data['viewemployees'] = $this->usermodel->populateviewemployees();

				$this->load->view('userdata/viewemployees',$data);
		$this->load->view("template/footerpage");
	}
	
	

	
	
	
	
		public function viewloyality()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewloyality');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('loyalitycards','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewloyality"] = $this->usermodel->displayall($config["per_page"], $page,'loyalitycards','companyid',$companyid);

		
         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewloyality',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
		
		public function viewvoucher()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				$config['base_url'] = base_url('Systemusers/viewloyality');
				
							$config['total_rows'] = $this->usermodel->count_allwhere('voucher','companyid',$companyid);

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
        $data["viewvoucher"] = $this->usermodel->displayall($config["per_page"], $page,'voucher','companyid',$companyid);

		
         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewvoucher',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
	
	
	
	
				public function setting()
	{ 
				$this->load->view("template/headerpagemin");
		
		
	
		$data['setting'] = $this->usermodel->populateviewsetting();

				$this->load->view('userdata/setting',$data);
		$this->load->view("template/footerpage");
	}
		
 
 public function viewproducts()
	{ 
		
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $mylastrecord=0;
		
			$lastrecord = $this->usermodel->last_productcode($companyid);
			if($lastrecord !=false){
				 $mylastrecord=(int)$lastrecord[0]["code"]+1;
			}else{
				
				 $mylastrecord=(int)$mylastrecord+1;
			}
  $this->load->view("template/headerpagemin");
        $this->load->view("template/tableheader");
				
				$config['base_url'] = base_url('Systemusers/viewproducts');
							$config['total_rows'] = $this->usermodel->count_allwhere('products','companyid',$companyid);
		$config['per_page'] = '40';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
								$data['maincategory']= $this->usermodel->populateall('maincategory','companyid',$companyid);

		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewproducts',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 public function viewassets()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		
				
				
				$config['base_url'] = base_url('Systemusers/viewassets');
							$config['total_rows'] = $this->usermodel->count_allwhere('assets','companyid',$companyid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		
		
		        $data["assets"] = $this->usermodel->displayall($config["per_page"], $page,'assets','companyid',$companyid);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewassets',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 public function viewopeningstock()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	
				$config['base_url'] = base_url('Systemusers/viewopeningstock');
							$config['total_rows'] = $this->usermodel->count_allwhereallstock('stock','closedate',"");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        $data["viewproducts"] = $this->usermodel->displayallstock($config["per_page"], $page,'stock','closedate',"");

				
				
         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewopeningstock',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
	
	   public function downloadsms() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."sent sms.csv";
		
								
							
									
 						
							        $query = "SELECT * FROM sms WHERE userid='$userid' ";
	
														


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
	
	
	 public function downloadpurchsecodes() {
  
		$session_data = $this->session->userdata('logged_in');
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Purchase barcodes.csv";
		     $invoice_number = $_GET['randomitemidentifier'];

								
							
					
 						
							        $query = "SELECT serial, name from serials   WHERE invoice='$invoice_number' ";
	
														


       $result = $this->db->query($query);

       // $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
$data = ltrim(strstr($this->dbutil->csv_from_result($result, ',', "\r\n"), "\r\n"));

        force_download($filename, $data);

		
	
  }
	
	
	
	
	
  
 public function viewtocktaking()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
				
				
	 	 	 $data['branchid'] = $session_data['branchid'];
	 $mybranchid = $data['branchid'];
				$config['base_url'] = base_url('Systemusers/viewtocktaking');
							//$config['total_rows'] = $this->usermodel->count_allwhere('stocktaking','companyid',$companyid);

		$config['total_rows'] = $this->usermodel->count_allwheredataStockTaking('stocktaking','branchid',$branchid,'updatedby',0);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		      //  $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'stocktaking','companyid',$companyid);
		 $data["viewproducts"] = $this->usermodel->displayalldatastocktaking($config["per_page"], $page,'stocktaking','stocktaking.branchid',$branchid,'updatedby',0);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewtocktaking',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 public function viewproductlist()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewproductlist');
									$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'branch',$branchid);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
		$config['per_page'] = '40';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','branch',$branchid);

				
         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewproductlist',$data);
				
		//$this->load->view("template/footerpage");
	
	}
 
 
 
 
 
 
 
 
 public function viewserialnumbers()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewserialnumbers');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('serials','companyid',$companyid,'branch',$branchid);
									$config['total_rows'] = $this->usermodel->count_allwheredata('serials','companyid',$companyid,'id >',0);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;


		$data["viewserials"] = $this->usermodel->displayall($config["per_page"], $page,'serials','companyid',$companyid);

				
         $this->load->view("template/headerpagemin");
				$this->load->view("template/tableheader");

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
							$this->load->view('userdata/viewallcurrentserials',$data);

		$this->load->view("template/footerpage");
	
	}
 
 
 
 public function viewbulklables()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewbulklables');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('serials','companyid',$companyid,'branch',$branchid);
									$config['total_rows'] = $this->usermodel->count_allwheredata('labels','branch',$branchid,'id >',0);

		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;


		$data["viewserials"] = $this->usermodel->displayall($config["per_page"], $page,'labels','branch',$branchid);

				
         $this->load->view("template/headerpagemin");
				$this->load->view("template/tableheader");

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
							$this->load->view('userdata/viewbulklables',$data);

		$this->load->view("template/footerpage");
	
	}
 
 
 
  
 public function viewbudget()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewbudget');
									$config['total_rows'] = $this->usermodel->count_allwheredata('budget','companyid',$companyid,'branch',$branchid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewbudget"] = $this->usermodel->displayalldata($config["per_page"], $page,'budget','companyid',$companyid,'branch',$branchid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewbudget',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 		public function labourreport()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
						$data['viewlabour']= false;

	

				$this->load->view('userdata/labourreport',$data);
		$this->load->view("template/footerpage");
	}
	
 
  public function syncattandence()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewbudget');
									$config['total_rows'] = 0;

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewlabour"] = false;

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/syncattandence',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
  
 public function viewlabour()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

				
				$config['base_url'] = base_url('Systemusers/viewlabour');
									$config['total_rows'] = $this->usermodel->count_allwheredata('labour','companyid',$companyid,'branch',$branchid);

		$config['per_page'] = '500';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["viewlabour"] = $this->usermodel->displayalldata($config["per_page"], $page,'labour','companyid',$companyid,'branch',$branchid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewlabour',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 public function assigntask()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		

$data["myview"]="Systemusers/assigntask";
				
				$config['base_url'] = base_url('Systemusers/assigntask');
									$config['total_rows'] = $this->usermodel->count_allwheredata('assigntask','companyid',$companyid,'id >',0);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["assigntask"] = $this->usermodel->displayalldata($config["per_page"], $page,'assigntask','companyid',$companyid,'id >',0);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/assigntask',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 
 public function myassigedntask()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
$data["myview"]="Systemusers/myassigedntask";
				
				$config['base_url'] = base_url('Systemusers/myassigedntask');
									$config['total_rows'] = $this->usermodel->count_allwheredata('assigntask','companyid',$companyid,'employeeid',$userid);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["assigntask"] = $this->usermodel->displayalldata($config["per_page"], $page,'assigntask','companyid',$companyid,'employeeid',$userid);

         $this->load->view("template/headerpagemin");
		
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/assigntask',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 	public function viewstore()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		
				
				
				$config['base_url'] = base_url('Systemusers/viewstore');
							$config['total_rows'] = $this->usermodel->count_allwhere('store','companyid',$companyid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'store','companyid',$companyid);

         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewstore',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 
 
 
 
 
 
 
	public function updatemyproduct()
	{ 
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
						$stockdate= $this->usermodel->populateall('newstock','companyid',$companyid);

		
						   
		   
						   
if(is_array($stockdate)) {

   foreach($stockdate as $row){

   $item_id=trim($row->item_id);
    $myid=trim($row->id);

	   	$signup = $this->usermodel->populateallarray('products','id', $item_id);
		if($signup!=FALSE){
			
					$code=$signup[0]['code'];


		
 
 	$updatedata=array(		
			'code'=>$code,
		
								);
							$usr_result = $this->usermodel->updatedata($updatedata,'newstock','id',$myid);
   
	
}
}
if ($usr_result ==TRUE) //active user record is present
							{
								
								 
					echo "updated successfully"	;
										
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

								echo "updated successfully"	;

	
							}
} else {
    //echo   "No student";
	
}
						   
						   
					
	
					   
	
	}
	
	
	
	
 
 
 
 
 
 
 
 
 
 
 
 
	public function updatemystore()
	{ 
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
						$stockdate= $this->usermodel->populateall('newstock','companyid',$companyid);

		
						   
		   
						   
if(is_array($stockdate)) {

   foreach($stockdate as $row){

   $item_id=trim($row->item_id);
    $myid=trim($row->id);

	   	$signup = $this->usermodel->populateallarray('store','id', $item_id);
		if($signup!=FALSE){
			
					$code=$signup[0]['code'];


		
 
 	$updatedata=array(		
			'code'=>$code,
		
								);
							$usr_result = $this->usermodel->updatedata($updatedata,'newstock','id',$myid);
   
	
}
}
if ($usr_result ==TRUE) //active user record is present
							{
								
								 
					echo "updated successfully"	;
										
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

								echo "updated successfully"	;

	
							}
} else {
    //echo   "No student";
	
}
						   
						   
					
	
					   
	
	}
	
 
 
 
  



  public function searchalldispatchstockitems()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $mysearchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		$searchterm = trim($this->usermodel->searchterm_handler($mysearchterm,True));
		
		

				
				$config['base_url'] = base_url('Systemusers/searchalldispatchstockitems');
				$config['total_rows'] = $this->usermodel->searchalldispatchstockitems_count($searchterm);

		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
		       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);
		$data['viewincomingstock'] = $this->usermodel->searchallalldispatchstockitems($searchterm,$page);

         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
					$data['searchterm'] = $searchterm;



				//$data['viewexpense'] = $this->usermodel->viewitemexpensereport($fromdate,$todate,$companyid,$supplier,$itemtype,$daterange,$code,$grouping,$branchid);








		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewincomingstock',$data);
				
		//$this->load->view("template/footerpage");
	
	}
 
 
 

















  public function searchallproduct()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $mysearchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		$searchterm = trim($this->usermodel->searchterm_handler($mysearchterm,True));
		
		

				
				$config['base_url'] = base_url('Systemusers/searchallproduct');
				$config['total_rows'] = $this->usermodel->searchallproducts_count($searchterm);

		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
		       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);
		$data['viewproducts'] = $this->usermodel->searchallproducts($searchterm,$page);

         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
					$data['searchterm'] = $searchterm;

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewproducts',$data);
				
		//$this->load->view("template/footerpage");
	
	}
 
 
 
 
 
 
 
  public function searchallproduct2()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $mysearchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		$searchterm = trim($this->usermodel->searchterm_handler($mysearchterm,True));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallproduct';
		$config['total_rows'] = $this->usermodel->searchallproducts_count($searchterm);
		$config['per_page'] = 2;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewproducts'] = $this->usermodel->searchallproducts($searchterm,$limit);
		

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewproducts',$data);
				
		$this->load->view("template/footerpage");
		
	}
	


 
 public function searchallassets()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $searchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		//$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallassets';
				$data['assets'] = $this->usermodel->searchallassets($searchterm,$limit);

		
		$config['total_rows'] =count((array)$data['assets']);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewassets',$data);
				
		$this->load->view("template/footerpage");
		
	}
	

  public function searchforloyalitypoints()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	

		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$type = trim($this->usermodel->searchterm_handler($this->input->get_post('type', TRUE)));

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchforloyalitypoints';
				$data['viewloyality'] = $this->usermodel->searchforloyalitypoints($searchterm,$type,$limit);

		
		$config['total_rows'] =count((array)$data['viewloyality']);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewloyality',$data);
				
		$this->load->view("template/footerpage");
		
	}
	



  public function searchallserials1()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
	 
	 		$status = trim($this->usermodel->searchterm_handler($this->input->get_post('status', TRUE)));

		$branch = trim($this->usermodel->searchterm_handler($this->input->get_post('branch', TRUE)));
		 $suppliers = explode(':=',$this->input->post("supplier"));

 
  $supplier1 = htmlspecialchars(trim($suppliers[0]));
		
		$supplier = trim($this->usermodel->searchterm_handler($supplier1));
		$type = trim($this->usermodel->searchterm_handler($this->input->get_post('type', TRUE)));

	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallproduct';
		$query = $this->usermodel->searchallserials($searchterm,$branch,$status,$limit,$companyid,$supplier,$type);

		$config['total_rows'] = $query['records'];
		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
							$data['viewserials'] = $query['data'];

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			 $this->load->view("template/tableheader");

$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewallcurrentserials',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function searchallopenclosestock()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		///$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				
					 $codes = explode(':=',$this->input->post("searchterm"));

 
  $searchterm = htmlspecialchars(trim($codes[0]));
				
				
				
				
				
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));
			$daterange = trim($this->input->get_post('daterange', TRUE));

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallopenclosestock';
		$config['total_rows'] = $this->usermodel->searchallopenclosestock_count($searchterm,$branchid,$startdate,$closedate, $limit);
		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['viewproducts'] = $this->usermodel->searchallopenclosestock($searchterm,$branchid,$startdate,$closedate,$daterange,$companyid ,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewopeningstock',$data);
				
		$this->load->view("template/footerpage");
		
	}
	





  public function searchallclosingstock()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$department = trim($this->input->get_post('department', TRUE));
			$method = trim($this->input->get_post('method', TRUE));

			
			
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallclosingstock';
		$config['total_rows'] = $this->usermodel->searchallclosingstock_count($searchterm,$branchid,$startdate, $limit);
		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['startdate']=$startdate;
		$data['branchid']=$branchid;
				$data['department']=$department;
								$data['method']=$method;

		$data['viewproducts'] = $this->usermodel->searchallclosingtock($searchterm,$branchid,$startdate, $limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewclosingstock',$data);
				
		$this->load->view("template/footerpage");
		
	}
	

 
 
 
  public function searchalldeals()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		//$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				
				$branchid = trim($this->usermodel->allterms_handler($this->input->get_post('branchid', TRUE),'branchid'));
				$searchterm = trim($this->usermodel->allterms_handler($this->input->get_post('searchterm', TRUE),'searchterm'));
			$dealtype = trim($this->usermodel->allterms_handler($this->input->get_post('dealtype', TRUE),'dealtype'));
				$startdate = trim($this->usermodel->allterms_handler($this->input->get_post('startdate', TRUE),'startdate'));
			$closedate = trim($this->usermodel->allterms_handler($this->input->get_post('closedate', TRUE),'closedate'));
				$action = trim($this->usermodel->allterms_handler($this->input->get_post('action', TRUE),'action'));
			$frotime = trim($this->usermodel->allterms_handler($this->input->get_post('frotime', TRUE),'frotime'));
				$totime = trim($this->usermodel->allterms_handler($this->input->get_post('totime', TRUE),'totime'));
			
			
			
				 

				
				//$branchid = trim($this->input->get_post('branchid', TRUE));

							//$searchterm = trim($this->input->get_post('searchterm', TRUE));

							//$dealtype = trim($this->input->get_post('dealtype', TRUE));
//$startdate = trim($this->input->get_post('startdate', TRUE));
			//$closedate = trim($this->input->get_post('closedate', TRUE));
					//	$action = trim($this->input->get_post('action', TRUE));

			
	//$frotime = trim($this->input->get_post('frotime', TRUE));
			//$totime = trim($this->input->get_post('totime', TRUE));
					

	  
	  
	  $startdate=$startdate." ".$frotime;
	  	  $closedate=$closedate." ".$totime;
			
			
			//

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchalldeals';
		//$config['total_rows'] = $this->usermodel->searchalldeals_count($searchterm,$branchid,$startdate,$closedate, $limit,$dealtype);
		
		
		
			$data['viedeals'] = $this->usermodel->searchalldeals($searchterm,$branchid,$startdate,$closedate, $limit,$dealtype,$action);

				$config['total_rows'] =count((array)$data['viedeals']); 
		
		
		
		
		
		
		
		
		
		
		$config['per_page'] = 1000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		//$data['viedeals'] = $this->usermodel->searchalldeals($searchterm,$branchid,$startdate,$closedate, $limit,$dealtype);
		
		
	
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('userdata/viedeals',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	 public function searchallexpensesplots()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
					$searchterm  = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
	 
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallexpenses';
		$config['total_rows'] = $this->usermodel->search_record_plotsexpense($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewexpenses'] = $this->usermodel->searchallplotsexpense($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		

		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/allexpenditure',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	

  public function searchallexpenses()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
		$download = trim($this->input->get_post('download', TRUE));
		$department = trim($this->input->get_post('department', TRUE));

			$closedate = trim($this->input->get_post('closedate', TRUE));
						$view = trim($this->input->get_post('view', TRUE));

										$bankname = trim($this->input->get_post('bankname', TRUE));

 	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  
	  $finalstartdate=$startdate." ".$frotime;
	  	  $finalclosetdate=$closedate." ".$totime;

	  
	  

			 $this->load->view("template/headerpagemin");

		$data['links'] ="";
				

		//$config['total_rows'] = $this->usermodel->searchallexpense_count($searchterm,$branchid,$finalstartdate,$finalclosetdate, $download);
		
		
		
		
		
		$data['viewexpenses'] = $this->usermodel->searchallexpenses($searchterm,$companyid,$branchid,$finalstartdate,$finalclosetdate, $download,$department,$bankname);
		$data['total_rows'] =count((array)$data['viewexpenses']);
					$this->load->view($view,$data);

				
		$this->load->view("template/footerpage");
		
	}
	
 
 
 
 
 
 
 
 
 
 
 
 
 
  public function searchallbills()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
		$download = trim($this->input->get_post('download', TRUE));

			$closedate = trim($this->input->get_post('closedate', TRUE));
						$view = trim($this->input->get_post('view', TRUE));

			 $frotime="00:00:00";
	  $totime="23:59:59";
	  
	  
	  $finalstartdate=$startdate." ".$frotime;
	  	  $finalclosetdate=$closedate." ".$totime;

	  
	  

			 $this->load->view("template/headerpagemin");

		$data['links'] ="";
				

		
		
		
		
		
		$data['viewexpenses'] = $this->usermodel->viewppendimgbillssearchallexpenses($searchterm,$companyid,$branchid,$finalstartdate,$finalclosetdate, $download);
		
	
		
		$data['total_rows'] =count((array)$data['viewexpenses']);
					$this->load->view($view,$data);

				
		$this->load->view("template/footerpage");
		
	}
	
 
 
 
 
 
 
 
 
  public function searchallrequest()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
			$view = trim($this->input->get_post('view', TRUE));
						$type = trim($this->input->get_post('type', TRUE));



				$branchid = trim($this->input->get_post('branchid', TRUE));
				
				
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));
					
			
	   $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
	  
	  
	  $finalstartdate=$startdate." ".$frotime;
	  	  $finalclosetdate=$closedate." ".$totime;
	  
	  

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallrequest';
		//$config['total_rows'] = $this->usermodel->searchallexpenserequest_count($searchterm,$branchid,$finalstartdate,$finalclosetdate, $limit);
		
		$data['viewexpenses'] = $this->usermodel->searchallexpensesrequest($searchterm,$branchid,$finalstartdate,$finalclosetdate, $type);
				
				
				
				$config['total_rows'] =count((array)$data["viewexpenses"]);


		$config['per_page'] = 100;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
				
		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		 
	  //$finalstartdate=$startdate." ".$frotime;
	  	 // $finalclosetdate=$closedate." ".$totime;

	  
	$data["finalstartdate"]=$startdate;
		$data["finalclosetdate"]=$closedate;


		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view("userdata/viewrequest",$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 
  public function searchallfollowup()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));
			
			$dealtype = trim($this->input->get_post('dealtype', TRUE));
	
						
	$frotime = trim($this->input->get_post('frotime', TRUE));
			$totime = trim($this->input->get_post('totime', TRUE));
				$action = trim($this->input->get_post('action', TRUE));
		

	  
	  
	  $startdate=$startdate." ".$frotime;
	  	  $closedate=$closedate." ".$totime;
			
			
			
			
			
			

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallfollowup';
				$data['viewallfollowups'] = $this->usermodel->searchallfollowps($searchterm,$branchid,$startdate,$closedate, $limit,$dealtype,$action);

				$config['total_rows'] =count((array)$data['viewallfollowups']); 
				//count$this->usermodel->searchallfollowups_count($searchterm,$branchid,$startdate,$closedate, $limit);
//
		//$config['total_rows'] = $this->usermodel->searchallfollowups_count($searchterm,$branchid,$startdate,$closedate, $limit);
		
		$config['per_page'] = 100000;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['reporttype']="</br> DAILY CUSTOMER FOLLOW UP REPORT";
		$data['closedate'] = $closedate;
	$data['startdate'] = $startdate;
			$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewallfollowups',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
  public function searchalltasks()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));
			$status = trim($this->input->get_post('status', TRUE));
			$category = trim($this->input->get_post('category', TRUE));

			$datetype = trim($this->input->get_post('datetype', TRUE));

		$totime = trim($this->input->get_post('totime', TRUE));
			$frotime = trim($this->input->get_post('frotime', TRUE));

	  $startdate=$startdate." ".$frotime;
	  	  $closedate=$closedate." ".$totime;



		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchalltasks';
		//$config['total_rows'] = $this->usermodel->searchalltasks_count($companyid,$searchterm,$branchid,$startdate,$closedate, $status,$limit);
		
		$data['myview'] = "user/searchalltasks";
		
		
			$config['base_url'] = base_url() . 'Systemusers/searchalltasks';
		$query = $this->usermodel->searchalltasks($companyid,$searchterm,$branchid,$startdate,$closedate, $status,$category ,$limit,$datetype);

		$config['total_rows'] = $query['records'];
		$config['per_page'] = 1000;
		
		
		//$config['per_page'] = 100;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		//$data['viewtasks'] = $this->usermodel->searchalltasks($companyid,$searchterm,$branchid,$startdate,$closedate, $status,$limit);
		$data['viewtasks'] = $query['data'];
		
	
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewtasks',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	

 
  public function searchallstocktaking()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
				
				
				 $codes = explode(':=',$this->input->post("searchterm"));

 
  $searchterm = htmlspecialchars(trim($codes[0]));
				
				
				
				
$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));

		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallstocktaking';
		$config['total_rows'] = $this->usermodel->searchallstocktaking_count($searchterm,$branchid,$startdate,$closedate, $limit);
		
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		
		$data['viewproducts'] = $this->usermodel->searchallstocktaking($searchterm,$branchid,$startdate,$closedate, $limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewtocktaking',$data);
				
		$this->load->view("template/footerpage");
		
	}
	


  
   public function addadvancepayment()
    {
		
$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	   $mydate = date('Y-m-d H:i:s');
   						      $myentrydate = date("d/m/Y H:i", strtotime($mydate));

 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:s');
 		//$currentdate =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 
		 			 			   	  $dateposted = $this->input->post("dateposted");


		   	  $description = "Advance Deposited";

		   	  $amount = $this->input->post("amount");
			  
		    		   	  $itemid = $this->input->post("itemid");
		    		   	  $view = $this->input->post("view");

		    		   	  $status = $this->input->post("status");



						$baddebt = $this->input->post("baddebt");

		    		   	  $bankname = $this->input->post("bankname");






		 
						










				
			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewalladvance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addadvancepayment') == "advance")
					   {
						  

									$people = $this->usermodel->populateallarray('people','id',$itemid);
									$supplierbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
								$phone=$people[0]["phone"];
																$firstname=$people[0]["firstname"];

									$transactionid=$people[0]["transactionid"];



if($transactionid !=""){
	
	 $transactionid = $userid.time();
}

	
					
 $invoice=$transactionid;

	/*
	
		 $myamount=$myadvance[0]['amount'];
		  $mypaid=$myadvance[0]['paid'];

		 			   $balance = $mybalance+$amount;
							$finalpaid = $myamount+$amount;
	
								
													

								
						    $productdata=array(		
						'balance'=>$balance,
						'amount'=>$finalpaid,
						'status'=>$status,

						
						);
						   */
						   
						   
						 //  $finalcustomerbalance=$supplierbalance+$amount;
						   
						   
						   
						   	
		 $finalcustomerbalance=(-1* (double)$supplierbalance)+$amount;
 //$finalcustomerbalance= (-1* ($finalcustomerbalance));

		 
						   
						   
						   
						   
						   
						   
						   
						   	   
						   $finalcustomerbalancepeople=(double)$supplierbalance-(double)$amount;
												$data=array(		
			'userid'=>$userid,
			
			'description'=>$description,

		  	'balance'=>$finalcustomerbalance,
			
			'companyid' => $companyid,
				'amount' => $amount,
			'createdat'=>$dateposted,
			'advanceid'=>$itemid,

			
								);
							$usr_result = $this->usermodel->add($data,'advancepayment');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
								 
								 
								

			
								
	
			
				
				
				
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalancepeople,
							'lastbalancedate'=>$dateposted,
						'transactionid'=>$transactionid,
								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
								 
								 
								 
								 
								 
								 
								 		 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "Advance Deposited",'supplier'=>$peopleid);


								$creditdata=array( 'userid'=>$userid,'account'=>$baddebt,'credit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');		 
								 
								 
								 
								
										 	$taskmessage = "Dear ". $firstname  .",You top up of ". $amount ." has been received on ". $myentrydate .".Your current balance is:". $finalcustomerbalance .". Thank you so much ";

								           $this->addallpushedsms($taskmessage,$phone,$view);
										   
										   	  //$this->pushedsmswithview($message,$contact,$myview);
								 //
								 
								 
								 
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added payment on existing one..</div>');	
							redirect($view);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Payment   was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


  
  
  
  
  
  

	
	
  public function searchallstocktakingserial()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
				$branchid = trim($this->input->get_post('branchid', TRUE));
	$startdate = trim($this->input->get_post('startdate', TRUE));
			$closedate = trim($this->input->get_post('closedate', TRUE));


			
			
			
			
			
			

			$viewserials  = $this->usermodel->populatethreenoarray('serials','companyid', $companyid,'serial' ,$searchterm,'branch' ,$branchid);
						
						$confirmserials  = $this->usermodel->populatethreenoarray('serialstocktaking','companyid', $companyid,'serial' ,$searchterm,'startdate',$startdate);

						
						if($confirmserials !=FALSE ){
							 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This serial number has been counted('.$searchterm.').  Stock tacking can only be done once per item per cycle. try again</div>');
								
								 redirect('user/getstocktakingbyserial?startdate='.$startdate.'&closedate='.$closedate.'&branchid='.$branchid.'&companyid='.$companyid);	
								 
								 return false;
							
						}
						
			
			$getproductstock  = $this->usermodel->populatethreenoarray('stocktaking','branchid', $branchid,'code' ,$viewserials[0]['code'],'startdate' ,$startdate);
$open=trim($getproductstock[0]['open']); 
$available=trim($getproductstock[0]['added']); 
$myid=trim($getproductstock[0]['id']); 


$mytotal=$available+1;
	 $balancebalance=$mytotal-$open;
			if($viewserials !=FALSE ){
		        $serial=trim($viewserials[0]['serial']); 

			
			
												$data=array(		
			'userid'=>$userid,
						'startdate'=>$startdate,
						'closedate'=>$startdate,
						'serial'=>$serial,

										'companyid'=>$companyid,

		'code'=>$viewserials[0]['code'],

	'branchid'=>$branchid,
		'sellingprice'=>$viewserials[0]['sellingprice'],
			'buyingprice'=>$viewserials[0]['buyingprice'],
				'added'=>1,
				
			
						'name'=>$viewserials[0]['name'],
			
								);
				$usr_result = $this->usermodel->add($data,'serialstocktaking');
							
			

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
											$newqtyDATA=array(		
						'added'=>$mytotal,
						'balance'=>$balancebalance,
						'updatedby'=>$userid,
						'closedate'=>$startdate,
								);
								 $this->usermodel->updatedata($newqtyDATA,'stocktaking','id',$myid);

						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully added stock taking..</div>');	
							//redirect('user/viewstocktakingreportserial');	
								 redirect('user/getstocktakingbyserial?startdate='.$startdate.'&closedate='.$closedate.'&branchid='.$branchid.'&companyid='.$companyid);	

							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Stock taking  was not saved.. Try again</div>');
								
								 redirect('user/getstocktakingbyserial?startdate='.$startdate.'&closedate='.$closedate.'&branchid='.$branchid.'&companyid='.$companyid);	

								 
							}
			
			
			
			
			
			
			
			
			
			
			
			
			
			}else{
				
				 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>  This serial number ('.$searchterm.')  does not exist. Try again</div>');
								
								 redirect('user/getstocktakingbyserial?startdate='.$startdate.'&closedate='.$closedate.'&branchid='.$branchid.'&companyid='.$companyid);	
								 
								 return false;
			}
			
			
			
								 redirect('user/getstocktakingbyserial?startdate='.$startdate.'&closedate='.$closedate.'&branchid='.$branchid.'&companyid='.$companyid);	
				
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
  public function searchallproductlist2()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	// $viewproductsfromallbranches=false;
	 $codes = explode(':=',$this->input->post("searchterm",TRUE));

 
  $mysearchterm = htmlspecialchars(trim($codes[0]));
	 
	 
		$searchterm = trim($this->usermodel->searchterm_handler($mysearchterm));
		
				  	      $viewproductsfromallbranches=$this->usermodel->populatuserpermissionsdataarray('productlist','viewproductsfromallbranches',$userid);

		
		
		
	
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'Systemusers/searchallproductlist';
		$config['total_rows'] = $this->usermodel->searchallproductlist_count($searchterm,$viewproductsfromallbranches,$branchid);
		$config['per_page'] = 2;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewproducts'] = $this->usermodel->searchallproductlist($searchterm,$limit,$viewproductsfromallbranches,$branchid);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewproductlist',$data);
				
		$this->load->view("template/footerpage");
		
	}
	
 


  public function searchallproductlist()
	{
		

	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	    $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $mysearchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		$searchterm = trim($this->usermodel->searchterm_handler($mysearchterm,True));
		
		
				  	      $viewproductsfromallbranches=$this->usermodel->populatuserpermissionsdataarray('productlist','viewproductsfromallbranches',$userid);

				
				$config['base_url'] = base_url('Systemusers/searchallproductlist');

		$config['per_page'] = '100';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
	
		       // $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'products','companyid',$companyid);
		$data['viewproducts'] = $this->usermodel->searchallproductlist($searchterm,$page,$viewproductsfromallbranches,$branchid);
		$config['total_rows'] =count((array)$data['viewproducts']);
		
		//$this->usermodel->searchallproductlist_count($searchterm,$viewproductsfromallbranches,$branchid);

         $this->load->view("template/headerpagemin");
		 $this->load->view("template/tableheader");
					$data['searchterm'] = $searchterm;

		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewproductlist',$data);
				
		//$this->load->view("template/footerpage");
	
	}
 
 
 
 









 
  public function searchallstore()
	{
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'user/searchallstore';
		$config['total_rows'] = $this->usermodel->searchallstore_count($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
		$data['viewproducts'] = $this->usermodel->searchallstore($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/viewstore',$data);
				
		$this->load->view("template/footerpage");
		
	}
 
 
 public function viewwarningproducts()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		
				
				
				$config['base_url'] = base_url('Systemusers/viewwarningproducts');

							//$config['total_rows'] = $this->usermodel->count_allwherelow('products','companyid',$companyid);
		$config['per_page'] = '20000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);

//
 $config["total_rows"] =count((array)$this->usermodel->lowstock($config["per_page"], $page,'products','companyid',$companyid,'id >',0));
							    $data["viewwarningproducts"] = $this->usermodel->lowstock($config["per_page"], $page,'products','companyid',$companyid,'id',0);
		


         $this->load->view("template/headerpagemin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewwarningproducts',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 
 
 
 
 
 
 public function viewlowstore()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
				
				
				$config['base_url'] = base_url('Systemusers/viewlowstore');
						//	$config['total_rows'] = $this->usermodel->count_allwherelow('productlist','companyid',$companyid);
							

		$config['per_page'] = '20000';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
							   

		$config["total_rows"] =count((array)$this->usermodel->lowstock($config["per_page"], $page,'productlist','companyid',$companyid,'branch',$branchid));

		 $data["viewproducts"] = $this->usermodel->lowstock($config["per_page"], $page,'productlist','companyid',$companyid,'branch',$branchid);

         $this->load->view("template/headerpagemin");
		$this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/viewlowstore',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 
 
 
 
 
		public function downloaddailydeals()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		  $myuserid = $this->input->post("userid");

	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
		  $closedate = $this->input->post("closedate");
	

				$this->load->view("template/headerpagemin");
		
	 $new_date=date("Y-m-d H:i");		

  $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Deal Download.csv";
		
		
		
		
		
		
		
		
	


			
 if($branchid=="all"){
				
if($myuserid=="all"){

      		 $query = "SELECT * FROM  deals WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate' ";
}else{
	      		 $query = "SELECT * FROM  deals WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate' AND userid = '$myuserid' ";

}
        //$query = "SELECT * FROM deals  WHERE sdateposted ='$startdate'  and and  stocktaking.type ='branch'  and  stocktaking.companyid='$companyid'  ORDER BY id desc ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
		
		if($myuserid=="all"){

      		 $query = "SELECT * FROM  deals WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate'  and 	branchid	 = '$branchid' ";
}else{
      		 $query = "SELECT * FROM  deals WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate' AND userid = '$myuserid' and 	branchid	 = '$branchid' ";

}





       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);	
		
		
	}
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
 
		public function downloaddailyfollowups()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	  $branchid = $this->input->post("branchid");
	  $startdate = $this->input->post("startdate");
		  $closedate = $this->input->post("closedate");
	

				$this->load->view("template/headerpagemin");
		
	 $new_date=date("Y-m-d H:i");		

  $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."Followups Download.csv";
		
		
		
		
		
		
		
		
	


			
 if($branchid=="all"){
				


      		 $query = "SELECT * FROM  followups WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate' AND userid = '$userid' ";



       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	}else{
      		 $query = "SELECT * FROM  followups WHERE 	 dateposted BETWEEN  '$startdate'  AND  '$closedate' AND userid = '$userid' and 	branchid	 = '$branchid' ";


       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);	
		
		
	}
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	

 
 
 
 
 
 
 public function adddeals()
    {
		
			$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   //$data['branchid'] = $session_data['branchid'];
	 //$branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		  $branchid = $this->input->post("branchid");

 $finalsalesid = $this->input->post("finalsalesid");

 $owner = $this->input->post("owner");
$title = $this->input->post("title");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		

	  $action = $this->input->post("action");		  


	  
	  
	  $mycontact = explode(':=',$this->input->post("contact"));

 
  $contact = htmlspecialchars(trim($mycontact[0]));		  
		 $type = $this->input->post("type");   
		     
			 $comments = $this->input->post("comments");   
			      $allsteps = $this->input->post("allsteps");   
			   
				 $contactname = $this->input->post("contactname");  
					$amount = $this->input->post("amount"); 
						$probability = $this->input->post("probability"); 
					$expectedrevenue	 = $this->input->post("expectedrevenue"); 
					$stage	 = $this->input->post("stage"); 
										$dealowner	 = $this->input->post("dealowner"); 
																				$starttime	 = $this->input->post("starttime"); 



			  		  $this->form_validation->set_rules("dealowner", "Deal owner", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdeals', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_adddeal') == "deal")
					   {
						  $fromdate=$fromdate." ".$currenttime;
						   $todate= $todate." ".$starttime.":00";
					
						  
						
								 
									 $finalsalesid = $userid.time();
  $CORRECTDATA= explode("-",$owner);
								  $FINALBUSINESS = ($CORRECTDATA[0]);
								   $mycontactname = trim($CORRECTDATA[1]);
								   
								   
								     $BUSINESSfeeback= explode("-",$allsteps);
									  $myallsteps = trim($BUSINESSfeeback[0]);

									  $mycomments = trim($BUSINESSfeeback[1]);
						  
						  
						  
						  
						  
						  
						  
						  
						  
						   
						   $allcontact=$this->usermodel->populateallarray('deals','contact', $contact);


			

					if($allcontact!=FALSE ){	   
						   
						  $mydateposted=$allcontact[0]['dateposted'];	
						   			$myid=$allcontact[0]['userid'];	
															   $alluser=$this->usermodel->populateallarray('people','id', $myid);
$myuser=$alluser[0]['firstname']. " ".$alluser[0]['surname'];		
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not add this deal because it already exist in the system . This contct('.$contact.')  was adeded on ('.$mydateposted.') by  ('.$myuser.').Try again.</div>');	
																			redirect('user/viedeals');	
					return false;

					}
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'owner'=>$FINALBUSINESS,
			'title'=>$title,
		  	'fromdate'=>$fromdate,
								  	'nextstep'=>$finalsalesid,

					  	'branchid'=>$branchid,

			'dateposted'=>$dateposted,
			'todate' => $todate,
			
			'type' => $type,			
		  'contact' => $contact,    
		   'dealowner' => $dealowner,   
		   
		   
			 'comments' => $mycomments,   
			  			 'companyid' => $companyid,   

			   
			   			   'allsteps' => $myallsteps,  

			   'contactname' => $mycontactname,  
				'amount' => $amount, 
				'probability' => $probability,
					'expectedrevenue' => $expectedrevenue,
						'stage' => $stage,
				'status' => $action,
								);
							$usr_result = $this->usermodel->add($data,'deals');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							$followup=$this->usermodel->populateallarray('deals','nextstep', $finalsalesid);


			$followupid=$followup[0]['id'];	
					$folloupdata=array(		
					'followupid'=>$followupid,
					  	'level'=>"First Call",
					  	'feedback'=>$allsteps,
											  	'companyid'=>$companyid,
											  	'branchid'=>$branchid,
											  	'finalid'=>$finalsalesid,
												'status'=>$action,
			'date'=>$fromdate,


		  	'nextdate'=>$todate,
			'userid'=>$userid,
			'dateposted'=>$dateposted,
						'recommendation'=>$comments,

									'challanges'=>$amount,

								);
								
			
						$this->usermodel->add($folloupdata,'followups');

								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  Deal..</div>');	
							redirect('user/viedeals');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Deal  was not added.. Try again</div>');
								
								 redirect('user/viedeals');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 public function viewbalance() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['invoice'];

   	$data['itemid'] = $itemid;
			  
			  $data['allsales']= $this->usermodel->populateall('sales','invoice',$itemid);

		   $data['allcollections']= $this->usermodel->populateall('collection','invoice',$itemid);

			  $data['allsalesmain']= $this->usermodel->populateallarray('sales','invoice',$itemid);

	  
	  
	  
    //

		
		 $this->load->view('userdata/viewbalance',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
 
  public function addpayment()
    {
		$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
		  $receiveoverpayment=$this->usermodel->populatuserpermissionsdataarray('income','receiveoverpayment',$userid);
		  $receivedublicatecodes=$this->usermodel->populatuserpermissionsdataarray('income','receivedublicatecodes',$userid);
	$entermpesacode=$this->usermodel->populatuserpermissionsdataarray('sales','entermpesacode',$userid);

	$dontreceivepartialpayment=$this->usermodel->populatuserpermissionsdataarray('income','dontreceivepartialpayment',$userid);









		 $bankname="";
 	 			$amount = $this->input->post("amount"); 
 $remarks = $this->input->post("remarks");
$invoice = $this->input->post("itemid");
	
$method = $this->input->post("method");
$transactioncode = trim($this->input->post("transactioncode"));


$mybank = $this->input->post("bankname");
$paiddate = $this->input->post("paiddate");
$name = $this->input->post("name");
$baddebt = $this->input->post("baddebt");
$sendsms = $this->input->post("sendsms");
$smsdescription = $this->input->post("smsdescription");


if($bankname!=""){
		 $bankname=$mybank;
} else if($baddebt!=""){
$bankname=$baddebt;

	
}else{
 $bankname=$mybank;

}
								 	$myinvoice =  $userid.time().$this->createRandomPasswordForsales();






			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbalance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_payment') == "payment")
					   {
						   //
						   
						   
						   
						   
						   
						   
						   	if(($transactioncode !="") && ($method=="mpesa") && ($entermpesacode !=true)){
	
//
						   		$mpesaresult = $this->usermodel->populateallarray('sms_in','code', $transactioncode);
		
		
		
			if($mpesaresult==false){
								
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That code does not exist.Try again</div>');
								
		redirect('user/viewbalance?invoice='.$invoice);	
								
							return false;
							}
							
		
						   				$amount=$mpesaresult[0]['amount'];

						   
							}   
						   
						   
						   
						   
						   
						   if($receivedublicatecodes == true){
	
	
}else{
	
						   
						   
						if($transactioncode !=""){
						 $confimcode = $this->usermodel->populateallarray('collection','transactioncode', $transactioncode);

if($confimcode !=false){
	   	$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 <strong>Payment  was not posted!</strong> This transaction / Ref No/ Cheque Number has been used.:('.$transactioncode.'). Try again.</div>');

						  
		redirect('user/viewbalance?invoice='.$invoice);	
						  return false;
	
}
					}   
						   
						   
						   
}			   


					
						   
						   
									$viewsales = $this->usermodel->populateallarray('sales', 'invoice',$invoice);
									 $mainbalance=$viewsales[0]['balance'];
									  $maintotal=$viewsales[0]['total'];
									  $maincash=$viewsales[0][$method];
									   $maincredit=$viewsales[0]['credit'];
									     $mycustomer=$viewsales[0]['customer'];
										 $mybranchid=$viewsales[0]['branch'];
										 		 $oldcashier=$viewsales[0]['cashier'];


										 
										 
										 $finalcustomerbalance=0;
										 	$people = $this->usermodel->populateallarray('people','id',$mycustomer);
									$customerbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
									
	
										 
										 
										 
										 
										 
     $finalcash=(double)$maincash+(double)$amount; 
 $mycollectionbalance=(((double)$amount+(double)$mainbalance)*-1);
  $mybalance=(((double)$amount+(double)$mainbalance));
			 $finalcredit=(double)$maincredit-(double)$amount;
			 
			 
			 
			 			
if($dontreceivepartialpayment == true){
	
	

			 
			    if( (-$amount)> ($mainbalance)){
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 sile
							<strong>Warning!</strong> You can not receive  less amount / Partial payment of  ('.$amount.') than the balance  ('.(-1 *$mainbalance) .').Try again or ask for that right.</div>');	
						redirect('user/viewbalance?invoice='.$invoice);	
						return false;
							 }
			 
			 
			 
}	 
			 
			 
			 
			 
			 
			 
			
if($receiveoverpayment == true){
	
	
}else{
			  
						   if( (-$amount)< ($mainbalance)){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not pay  more amount ('.$amount.') than the balance  ('.(-1 *$mainbalance) .').Try again.</div>');	
																			redirect('user/viewbalance?invoice='.$invoice);	
																			return false;
																			   }
						  
}
												
												$data=array(		
			'userid'=>$userid,
			
			
						'invoice'=>$invoice,
						'balance'=>$mycollectionbalance,
			'createdate'=>$dateposted,
			   			'paiddate'=>$paiddate,
			   			'name'=>$name,

		   
			// 'remarks' => $remarks,   
			 			  			 'transactioncode' => $transactioncode,   

			  			 'companyid' => $companyid,
'remarks' => $method,						 
			  			 'paymentmethodes' => $bankname,   
'supplier' => $mycustomer, 
'branchid' => $mybranchid,
				'amount' => $amount, 
			
			
								);
							$usr_result = $this->usermodel->add($data,'collection');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									
						
								
								
								
								
								if(trim($transactioncode)!=""){
														$paymentdata2=array(		
			
				'used'=>1,
		
						   
					  	);	
						   
					 $this->usermodel->updatedata($paymentdata2,'sms_in','code',$transactioncode);
									 
						 if(trim($oldcashier) !=""){
										 $transactioncode=$oldcashier.",".$transactioncode;
									 }else{
							$transactioncode=$transactioncode;
	 
										 
									 }										$updatedata=array(	
								'credit'=>$finalcredit,
								'cashier'=>$transactioncode,

						'balance'=>$mybalance,
						$method=>$finalcash,
								);
								

									
								}else{
									
									$updatedata=array(	
								'credit'=>$finalcredit,

						'balance'=>$mybalance,
						$method=>$finalcash,
								);	
								}
							
							$usr_result = $this->usermodel->updatedata($updatedata,'sales','invoice',$invoice);
						

							
	
								 
								 
								 if($amount>0){

										$finalcustomerbalance=$customerbalance-$amount;
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
						'lastbalancedate'=>$paiddate,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
									
								
									 
								 }
								 
								 
								 
								 

								 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid,'transactioncode'=>$transactioncode,'supplier'=>$mycustomer,'mode'=>$myinvoice);


$creditdata=array( 'userid'=>$userid,'account'=>1100,'credit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid,'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							
						   						   		$mpesaresult = $this->usermodel->populatependingmypayment($transactioncode);

							if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
				$finalamount=$mpesaresult[0]['amount'];
						   							$paymentdata=array(		
			'id'=>$mpesaid,
			
				'used'=>1,
		
						   
					  	);	

								 $this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

	


						$data=array(		
			'userid'=>$userid,
			
				'code'=>$transactioncode,
			
		  	'branch'=>$branchid,
				 'companyid'=>$companyid,
				'type'=>"credit paid",
				 	'amount'=>$finalamount,
			'dateposted'=>$paiddate,
				'paymentstatus'=>"Cleared",
			
								);
							 $this->usermodel->add($data,'mpesasales');
		}
							
							
							
							
					if($sendsms=="yes"){
	
		

			 $contact=$people[0]['phone'];
			 if($people[0]['firstname'] !=""){
							$firstname=$people[0]['firstname'];
 
			 }else{
				 
							$firstname=$people[0]['company'];
 
			 }
			
		
			
			

								
								
	$correctime = date("d/m/Y H:i", strtotime($dateposted));

  			$message="Dear ".$firstname.",We have received your payment of Ksh. ". $this->MyformatMoney($amount, true) ." on  ". $correctime ." and your balance is Ksh. ".  $this->MyformatMoney($finalcustomerbalance, true).".  ".$smsdescription;					



$myview="user/viewbalance?invoice=".$invoice;				  
		  $this->addallpushedsms($message,$contact,$myview);	
						
							}
							
							
							
							
							
							
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  payment..</div>');	
																			redirect('user/viewbalance?invoice='.$invoice);	
															
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment  was not added.. Try again</div>');
								
																			redirect('user/viewbalance?invoice='.$invoice);	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 
 
  public function cancelpayment()
    {
		$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $bankname="";
 	 			$amount = $this->input->post("amount"); 
 $remarks = $this->input->post("remarks");
$invoice = $this->input->post("itemid");
	
$method = $this->input->post("method");

$mybank = $this->input->post("bankname");
$paiddate = $this->input->post("paiddate");
$name = $this->input->post("name");
$baddebt = $this->input->post("baddebt");



 $bankname=$mybank;






			  		  $this->form_validation->set_rules("amount", "Amount", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewbalance ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_cancelpayment') == "payment")
					   {
						   
						   
						   
						   	
		
						   
						   
						   
									$viewsales = $this->usermodel->populateallarray('sales', 'invoice',$invoice);
									 $mainbalance=$viewsales[0]['balance'];
									  $mybranch=$viewsales[0]['branch'];

									  $maintotal=$viewsales[0]['total'];
									  $maincash=$viewsales[0][$method];
									   $maincredit=$viewsales[0]['credit'];
									   									     $mycustomer=$viewsales[0]['customer'];

     $finalcash=$maincash-$amount; 
 $mybalance=$mainbalance -  $amount;
  $mycollectionbalance=$mainbalance +  $amount;
 //$mybalance=(($amount+$mainbalance)*-1);
 


			 $finalcredit=$maincredit+$amount;
			
/*
			  
						   if( ($amount)>($maintotal)){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not reverse  more money ('.$amount.') than the original amount  ('.$maintotal.').Try again.</div>');	
																			redirect('user/viewbalance?invoice='.$invoice);	
																			return false;
																			   }
						   
						   
							*/
							
												
												$data=array(		
			'userid'=>$userid,
			
			
						'invoice'=>$invoice,
						'balance'=>$mycollectionbalance,
			'createdate'=>$dateposted,
			   			'paiddate'=>$paiddate,
									   			'branchid'=>$mybranch,

			   			'name'=>$name,

		   
			 'remarks' => $remarks,   
			  			 'companyid' => $companyid,   
			  			 'paymentmethodes' => $bankname,   

				'amount' => -$amount, 
			
			
								);
							$usr_result = $this->usermodel->add($data,'collection');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								$updatedata=array(	
								'credit'=>$finalcredit,

						'balance'=>$mybalance,
						$method=>$finalcash,
								);
							$usr_result = $this->usermodel->updatedata($updatedata,'sales','invoice',$invoice);
					
								
							
								 
								 
								 
										
								 
								 
								 $creditdata =array( 'userid'=>$userid,'account'=>$bankname,'credit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$mycustomer);


$debitdata=array( 'userid'=>$userid,'account'=>1100,'debit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'balance'=> 0,'supplier'=>$mycustomer);

							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  payment..</div>');	
																			redirect('user/viewbalance?invoice='.$invoice);	
															
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Payment  was not added.. Try again</div>');
								
																			redirect('user/viewbalance?invoice='.$invoice);	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
 
 
 
 
 
 
 
  public function updatetdeals()
    {
		
			$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 
 	 		 $dealid = $this->input->post("dealid");

 $owner = $this->input->post("owner");
$title = $this->input->post("title");
	  $fromdate = $this->input->post("fromdate");
	  $todate = $this->input->post("todate");		  
		  $contact = $this->input->post("contact");    
		 $type = $this->input->post("type");   
		  $nextstep = $this->input->post("nextstep");   
		     
			 $comments = $this->input->post("comments");   
			      $allsteps = $this->input->post("allsteps");   
			   
				 $contactname = $this->input->post("contactname");  
					$amount = $this->input->post("amount"); 
						$probability = $this->input->post("probability"); 
					$expectedrevenue	 = $this->input->post("expectedrevenue"); 
					$stage	 = $this->input->post("stage"); 
										$dealowner	 = $this->input->post("dealowner"); 


			  		  $this->form_validation->set_rules("owner", "Task owner", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpagemin");

		
		 $this->load->view('userdata/viewdeals ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatedeal') == "deal")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'owner'=>$owner,
			'title'=>$title,
		  	'fromdate'=>$fromdate,
			
			
			'dateposted'=>$dateposted,
			'todate' => $todate,
			'fromdate' => $fromdate,
			'type' => $type,			
		  'contact' => $contact,    
		   'dealowner' => $dealowner,   
		   
		  'nextstep' => $nextstep,   
		   
			 'comments' => $comments,   
			  			 'companyid' => $companyid,   

			   
			   			   'allsteps' => $allsteps,  

			   'contactname' => $contactname,  
				'amount' => $amount, 
				'probability' => $probability,
					'expectedrevenue' => $expectedrevenue,
						'stage' => $stage,
			
								);
							$usr_result = $this->usermodel->updatedata($data,'deals','id',$dealid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully update the deal..</div>');	
							redirect('user/viedeals');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Deal  was not updated.. Try again</div>');
								
								 redirect('user/viedeals');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
  public function studentbio() {


	$session_data = $this->session->userdata('logged_in');

     $data['username'] = $session_data['username'];
 	$data['id'] = $session_data['id'];
 		$data['firstname'] = $session_data['firstname'];
 			$data['surname'] = $session_data['surname'];
 		
 			
 	$surname= $data['surname'] ;
	$id= $data['id'] ;
	$studentid= $data['id'] ;

$data['province'] = $this->provincemodel->populateprovince();
	
	$data['district'] = $this->districtmodel->populatedistrict();
	$data['county'] = $this->countymodel->populatecounty();
	$data['nation'] = $this->nationmodel->populatenation();



	
	$biodata['student']= $this->studentcontactmodel->populatestudent($studentid);
	$biodata['bio']= $this->systemusermodel->populatebiodata($studentid);

	$this->load->view("template/headerpagemin");
	
		
		 $this->load->view('userdata/biodata', $biodata,$data);
		$this->load->view("template/footerpage");


     
    }


	
		  public function studentsport() {
	$session_data = $this->session->userdata('logged_in');

     $data['surname'] = $session_data['surname'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
		
		
		$this->load->view('userdata/sportclubdata', $data);
		$this->load->view("template/footerpage");
     
    }
	 
     public function document() {
	 
	$session_data = $this->session->userdata('logged_in');

     $data['surname'] = $session_data['username'];
 	$data['id'] = $session_data['id'];
	$id=$data['id'];
	 	$this->load->view("template/headerpagemin");
		$data['documets'] = $this->systemusermodel->populatedocumets($id);
		
		$this->load->view('userdata/document', $data);
		$this->load->view("template/footerpage");
     
    }
	
	  public function adddocument1() {
	$session_data = $this->session->userdata('logged_in');

     $data['username'] = $session_data['username'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
	
		
		$this->load->view('userdata/schoolbackground', $data);
		$this->load->view("template/footerpage");
     
    }
	
	public function adddocument(){

$session_data = $this->session->userdata('logged_in');
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
     $data['surname'] = $session_data['surname'];
 	$data['id'] = $session_data['id'];
//$session_user=$_SESSION['id'];
$currentdate = date('Y:m:d H:i:s');
$new_date=date('Ymd');
$user="user";   
    if(!empty($_FILES['document']['tmp_name']))
    {
        $filepath="";
				
        for($i=0; $i<count($_FILES['document']['name']); $i++) 
        {
               $tmpFilePath = $_FILES['document']['tmp_name'][$i]; 
			 $documentname = $this->input->post("documentname");					  

               if ($tmpFilePath ==true)
               {  

					$image_size= getimagesize($_FILES['document']['tmp_name'][$i]);
				
					if(($tmpFilePath)==true)
					{			   
						   $path = "studentdocs/"; // create folder 
						   $name = $_FILES['document']['name'][$i];
						  $size = $_FILES['document']['size'][$i];
                        
							$ext = explode("/", strtolower($name));
						  $ext = strtolower(end($ext));
				
						  $filename = rand(100, 9900) . '_' . time()  . $ext;
						 
										   
						   
						   
						   if(move_uploaded_file($_FILES['document']['tmp_name'][$i], $path.$filename)) 
						   { $studentid1 = $this->input->post("studentid");
						//var_dump ($documentname);
				    				$filepath = $path . $filename;
											  			  	//var_dump ($filepath);
								$data = array(
	    'document' =>$filename,
	   'documentname' =>$documentname[$i],
	'companyid'=>$companyid,
		'studentid'=>$studentid1,
		'createddate'=>$new_date,
		
		
             );
									$usr_result = $this->systemusermodel->uploaddstudentocument($data);
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
												 			  $statusdata=array(
		'step6'=>'complete',
		
							);
								 $this->systemusermodel->updatestudentstatus($statusdata,$studentid1); 
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Uploaded your documents .but make sure all admission documents are uploaded..!</div>');
								
								 redirect('student/documents');
							}
							else
							{     

						 $this->session->set_flashdata('msg1', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You have not been able to upload your documents. try again</div>');
								
								 redirect('student/documents');
							}
								
							
							}
									 
					}else	
						{
								echo "that is not an image...Select correct image";
						} 
					 
					 
				}
		 
		}
if(($tmpFilePath)==false)
										{
					echo "please select an image first";
										}
		
    }
	
	}
	
	
	

	
	
	
	
	function sendEmail22($from,$email,$message,$subject)
{
	
	

		//$message = 'Dear '. $surname .',<br /> Your have a new task assigned to you which is due on ';
		
    //
$configuration = $this->usermodel->populateallarray('email_accounts','email',$from);

      $smtp_port=$configuration[0]["smtp_port"];
      $smtp_host=$configuration[0]["smtp_host"];

	 $smtp_user=$configuration[0]["email"];
	$smtp_pass=$configuration[0]["password"];
		$mycomnpany=$configuration[0]["name"];
				 $document='';

		 $myfile='document';
                $myfile2="";

  $this->load->helper('path');
  
    $this->load->library('email'); // load email library
	 	$config['protocol'] = 'smtp';

	//$config['protocol'] = 'mail';
    $config['smtp_host'] = $smtp_host; //change this
    $config['smtp_port'] = $smtp_port;
    $config['smtp_user'] = $smtp_user; //change this
    $config['smtp_pass'] = $smtp_pass; //change this
    $config['mailtype'] = 'html';
    $config['charset'] = 'iso-8859-1';
    $config['wordwrap'] = TRUE;
    $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
	 $this->email->initialize($config);

	 
	$this->email->from($from, $mycomnpany);
    $this->email->to($email);
	$bcc="";
	$cc="";
	$myfile2="";
   if($cc!=""){
	    $this->email->cc($cc); 
  
   }
    if($bcc!=""){
	   	    //$this->email->bcc($bcc); 
$this->email->bcc(array($bcc));
   }
    $this->email->subject($subject);
    $this->email->message($message);
     //$sending_mail = $this->email->send();
  if($myfile2!=""){
	   	    //$this->email->bcc($bcc); 
             $this->email->attach('uploads/'.$myfile2);
   }

 


                 $sending_mail = $this->email->send();

	 
				if ($sending_mail) {
					
					 if($myfile2!=""){
	   	   $mypath = 'uploads/'.$myfile2;
						unlink($mypath);
						}

								
						return true;		
							
								
                } else {
                                       return false;

                }
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
   
}
	
	
	

		function sendTasktoEmail($from,$toemail,$surname,$duedate,$sendersurname,$subject,$comments,$cc,$emailtype)
{
	

if($emailtype=="Newtask"){
		 	$message = '<P>Dear '. $surname .',</P><P> Your have a new task assigned to you regarding  '. $subject .' which is due on  '. $duedate .'. </P><P> The details of the task are: </P><P> '. $comments .' </P><P>  Kindly login and view more about the task through:  http://erp.robisearch.com/.<br />  Kind Regards,</P><P> '. $sendersurname .'.</P><P> This email is automatically generated whenever anew task is assigned to you from ROBISEARCH ERP system </P>';

}else if($emailtype=="TaskFeedback"){
		 	$message = '<P>Dear '. $surname .',</P><P> Your have a new task feedback sent to you regarding  '. $subject .' which was due on  '. $duedate .'. </P><P> The details of the task  feedback are: </P><P> '. $comments .' </P><P>  Kindly login and view more about the task through:  http://erp.robisearch.com/.<br /> Kind Regards,</P><P> '. $sendersurname .'.</P><P> This email is automatically generated whenever anew task  feedback is replied to. From ROBISEARCH ERP system </P>';

}else{
		 	$message = '<P>Dear '. $surname .',</P><P> Your have a new task assigned to you regarding  '. $subject .' which is due on  '. $duedate .'. </P><P> The details of the task are: </P><P> '. $comments .' </P><P>  Kindly login and view more about the task through:  http://erp.robisearch.com/.<br />  Kind Regards,</P><P> '. $sendersurname .'.</P><P> This email is automatically generated whenever anew task is assigned to you from ROBISEARCH ERP system </P>';

	
}
	

		
$configuration = $this->usermodel->populateallarray('email_accounts','email',$from);

      $smtp_port=$configuration[0]["smtp_port"];
      $smtp_host=$configuration[0]["smtp_host"];
      $protocol=$configuration[0]["protocol"];

	 $smtp_user=$configuration[0]["email"];
	$smtp_pass=$configuration[0]["password"];
		 $mycomnpany=$configuration[0]["name"];
		

		 $myfile='document';
                //$myfile2=$this->upload_file($myfile);
$bcc="";
  $this->load->helper('path');
  
    $this->load->library('email'); // load email library
	 	//$config['protocol'] = 'smtp';

	$config['protocol'] = $protocol;
    $config['smtp_host'] = $smtp_host; //change this
    $config['smtp_port'] = $smtp_port;
    $config['smtp_user'] = $smtp_user; //change this
    $config['smtp_pass'] = $smtp_pass; //change this
    $config['mailtype'] = 'html';
  //  $config['charset'] = 'iso-8859-1';
	$config['charset']  = 'utf-8';
    $config['wordwrap'] = TRUE;
	 $config['smtp_timeout'] = 30;
	$config['crlf'] = '\r\n';
    $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
	 $this->email->initialize($config);

	 
	$this->email->from($from, $mycomnpany);
    $this->email->to($toemail);
   if($cc!=""){
	    $this->email->cc($cc); 
  
   }
    if($bcc!=""){
	   	    //$this->email->bcc($bcc); 
$this->email->bcc(array($bcc));
   }
    $this->email->subject($subject);
    $this->email->message($message);
     //$sending_mail = $this->email->send();
	 

 



                 $sending_mail = $this->email->send();


	 
				if ($sending_mail) {
	

								
						return true;		
							
								
                } else {
						  echo $this->email->print_debugger();

                                       return false;

                }
	 
	 						//  echo $this->email->print_debugger();



	 
	 
	 
	 
	 
	 
	 
	 
	 
   
}
	
	
	
	
		
 
	
	  public function logout() {
		  	$session_data = $this->session->userdata('logged_in');
		
$userid = $session_data['id'];
 $data = ['id', 'email'];
        $this->session->set_userdata('logged_in');
		session_destroy();
			 $UPDATE = $this->usermodel->populatedataloggs($userid);
	    
   $myid=$UPDATE[0]['id'];		

		   

$timeout = Date('Y-m-d H:i:s') ;
	$this->db->where('id', $myid);
  $this->db->set('timeout', $timeout);
  $this->db->update('loggs');
  
  
  $dir='qrcodes/';
	

  //$dir = "cache/"; /** define the directory **/

/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {
//foreach (glob($dir.'*.*') as $file){
	//echo $file;

/*** if file is 24 hours (86400 seconds) old then delete it ***/
if (filemtime($file) < time() - 604800) {
	// 1 hour
	//echo $file;
   unlink($file);
    }
}


  		 redirect('login', 'refresh');
       
    }
	 
      public function logout1() {
	
        $data = ['id', 'email'];
        $this->session->unset_userdata('logged_in');
		session_destroy();

  		 redirect('login', 'refresh');
       
    }
}
 