<?php
// codv = custom order data verwerking
require_once 'class.stdModule.php';

define('LINE_TERM',chr(10));
define('LINE_FORMAT','% -15s% -25s% -11s% -40s% -20s');			// OD format

class codv0100 extends stdModule {

	function codv0100() {
		$this->stdModule('codv0100');
	}

	function processOrders($order_type = null) {
		//print_r($this->_settings);
		$fpLog = fopen($this->_settings->paths->orderLogFile . "process.log",'a');
		fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Start order processing'.chr(10));	
		
		$data_file = ($order_type == 'VTW') ? 'orders.vtw' : 'orders.dat';
		
		switch ($order_type) {
		
			case 'VTW':				
				// Check voor order file
				//if ($this->_checkFile($data_file)) {
				if (!file_exists($this->_settings->paths->orderDataFile . $data_file)) {
					
					// Check for new orders in DB
					$new_orders = $this->_checkForUnprocessedOrders($order_type);
					if ( $new_orders > 0 ) {
						
						fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Found '.$new_orders.' new orders'.chr(10));	
						
						$orders = $this->_getUnprocessedOrders($order_type);
						$fp = fopen($this->_settings->paths->orderDataFile . $data_file,'a');

						$data = $this->_getOrders($orders);

						foreach ($data as $lines) {
							
							foreach ($lines['rows'] as $row) {
								fwrite($fp,sprintf(LINE_FORMAT
									, $lines['user_id']
									, $row['prd_code']
									, str_pad($row['amount'], 11, "0", STR_PAD_LEFT)
					                , ''
					                , $lines['orderref']). LINE_TERM
					            );
							}
							
							if ($lines['comment'] != '') {
								// format new lines en return								
								$comments_array = $this->_fixRN($lines['comment']);
								
								$i = 0;
								foreach ($comments_array as $comment) {	
									if (is_array($comment)) {
											
										foreach ($comment as $com) {
											fwrite($fp,sprintf(LINE_FORMAT
												, $lines['user_id']
												, 'TEKST'.str_pad($i, 2, "0", STR_PAD_LEFT)
												, ''
								                , $com
								                , $lines['orderref']) . LINE_TERM
				                			);
				                			$i++;
										}
									}
								}	
								
							}
						}
						
						fclose($fp);
						
						$this->_updateTblExport($orders, $order_type);
												
						fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Processed '.count($data).' products'.chr(10));	
						
					
					} else {
						fwrite($fpLog, date('Ymd H:i:s') . ' ['.$order_type .'] : No new '.$order_type.' orders found.'.chr(10));
					}
				
				} else {
					fwrite($fpLog, date('Ymd H:i:s') . ' ['.$order_type .'] : Found '.$file.' file. Aborting.'.chr(10));
				}
			
			break;
			
			
			case 'MEM':
				// Check voor order file
				if (!file_exists($this->_settings->paths->orderDataFile . $data_file)) {
					
					// Check for new orders in DB
					$new_orders = $this->_checkForUnprocessedOrders($order_type);
					if ( $new_orders > 0 ) {
						
						fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Found '.$new_orders.' new orders'.chr(10));	
						
						$orders = $this->_getUnprocessedOrders($order_type);
								
						$fp = fopen($this->_settings->paths->orderDataFile . $data_file,'a');

						$data = $this->_getOrders($orders);
						
						foreach ($data as $lines) {
							
							foreach ($lines['rows'] as $row) {
								fwrite($fp,sprintf(LINE_FORMAT
									, $lines['user_id']
									, $row['prd_code']
									, str_pad($row['amount'], 11, "0", STR_PAD_LEFT)
					                , ''
					                , $lines['orderref']). LINE_TERM
					            );
							}
						}
						
						fclose($fp);
						
						$this->_updateTblExport($orders, $order_type);
												
						fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Processed '.count($data).' products'.chr(10));	
						
					
					} else {
						fwrite($fpLog, date('Ymd H:i:s') . ' ['.$order_type .'] : No new '.$order_type.' orders found.'.chr(10));
					}
				
				} else {
					fwrite($fpLog, date('Ymd H:i:s') . ' ['.$order_type .'] : Found '.$file.' file. Aborting.'.chr(10));
				}
				
			break;
			
			default:
				fwrite($fpLog, date('Ymd H:i:s') . ' ['.$order_type .'] : No user type specified. Aborting.'.chr(10));
			break;	
		}
		
		fwrite($fpLog,date('Ymd H:i:s') . ' ['.$order_type .'] : Finished order processing'.chr(10).chr(10));
  		fclose($fpLog);

		
	}
	
	function writeOrders($order_type) {
		
		$orders = $this->_getUnprocessedOrders($order_type);
		
		foreach ($orders as $ord_id) {
			$data = $this->_getOrders($ord_id);
			
			foreach ($data as $d) {
				$this->_writeLine($order_type, $d);
			}
		}
	
	}
	
	function _fixRN($string) {

		$arr = explode("\r\n",$string);

		$new_array = array();

		foreach ($arr as $ak=>$av) {
			$new_array[$ak] = $this->_str_split($av, 40);
		}

		return $new_array;
	}
	
	function _checkFile($file_name) {
		
		print $this->paths->orderDataFile;
		if (file_exists($file_name)) return false;
		return true;		
	}
	
	function _checkForUnprocessedOrders($order_type) {
		$sql ="select count(ord_id) as count 
				from tbl_ohc_export 
				where usr_type ='$order_type' 
				and export_date is NULL";
		$rs = $this->_db->Query($sql);
		$count = $rs->Row('count');
		
		$rs->Close();
		
		return $count;
	}
	
	function _getUnprocessedOrders($order_type) {
		$sql ="select ord_id from tbl_ohc_export where usr_type = '".$order_type."' and export_date is NULL";
		$rs = $this->_db->Query($sql);
		
		$orders = array();
		while ($r = $rs->Row()) {
			$orders[] = $r['ord_id'];
			$rs->moveNext();
		}
		
		$rs->Close();
		
		return $orders;
	}
	
	function _writeLine($fp, $data) {
		
		fwrite($fp,sprintf(LINE_FORMAT,$data['user_id'],
                         $data['artikelcode'],
                         $data['hoeveelheid'],
                         $data['artikelnaam'],
                         $data['orderref'])."\n"
                       );
        return true;
	}

	
	function _getOrders($ord_ids) {

		if (!is_array($ord_ids) || count($ord_ids) == 0) return false;
			
		$sql = "select ord_number 		as orderref
					, ord_id			as ord_id
					, ord_usr_id 		as user_id
					, ord_comment		as comment
				from tbl_ord_orders as too
				where ord_id IN (".implode(',', $ord_ids).")";
				
		$rs = $this->_db->Query($sql);
		$orders = array();
		
		while ($r = $rs->Row()) {
			$orders[$r['ord_id']] = array(
				'order_id' => $r['ord_id'],
				'user_id' 	=> strtoupper($this->_getUserName($r['user_id'])),
				'orderref'	=> $r['orderref'],
				'comment'	=> $r['comment'],
				'rows'		=> array()				
			);
			
			$qry = "select opd_amount as amount
						 , opd_prd_name as prd_name
						 , prd_code as prd_code 
						 from tbl_ord_products 
					left join tbl_ctl_products on opd_prd_number = prd_id	 
					where opd_ord_id = ".$r['ord_id'];
			$rs_rows = $this->_db->Query($qry);
			while ($rr = $rs_rows->Row()) {
				$orders[$r['ord_id']]['rows'][] = $rr;	
				$rs_rows->moveNext();
			}
			$rs_rows->Close();
			
			$rs->moveNext();
		}
		
		$rs->Close();	
		
		return $orders;
	}
	
	function _getUserName($usr_id) {
		if (!is_numeric($usr_id)) return false;
		global $g_obj_ti3a0365;
		
		$g_obj_ti3a0365->getUsers($users, array(array('USR_ID','='.$usr_id), 'USR_USERNAME'), false);
		return $users[0]['USR_USERNAME'];
	}
	
	function _getArticleName($prd_id) {
		if (!is_numeric($prd_id)) return false;
		
		$sql = "select l1.lbl_label as artikel_naam
				from tbl_ctl_products
				left join tbl_ctl_labels as l1 ON l1.lbl_itm_tbl = 'tbl_ctl_products' 
				and l1.lbl_itm_col = 'prd_name' and l1.lbl_lng_id =1 and l1.lbl_itm_id = prd_id
				where prd_id = '".$prd_id."'";
				
		$rs = $this->_db->Query($sql);
		$art_naam = $rs->Row('artikel_naam');
		
		$rs->Close();
		
		return $art_naam;
	}
	
	function _updateTblExport($ord_ids, $ord_type) {
		$sql = "update tbl_ohc_export 
				set export_date =  now() 
				where usr_type = '".$ord_type."'
				and ord_id IN (".implode(',', $ord_ids).")";;
		$rs = $this->_db->Execute($sql);

	}
	
	function _str_split($string, $split_length=1) {
	    $array = array();
	    $len = strlen($string);
	    do
	    {
	        $part = '';
	        for ($j = 0; $j < $split_length; $j++)
	        {
	            $part .= $string{$i};
	            $i++;
	        }
	        $array[] = $part;
	    }
	    while ($i < $len);
	    return $array;
	}
}
?>