<?php
$path_to_root="../../";
include($path_to_root.'/application/config/config.php');

$ip = LIVE_SERVER_IP;
exec("ping -n 1 $ip", $output, $status);

$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

$api_data = array();
$api_data['api_user'] = API_USER;
$api_data['api_password'] = API_PASSWORD;
$api_data['location_code'] =LOCATION_CODE;

$upto=date('Y-m-d',(strtotime ( '-30 days' , strtotime ( date('Y-m-d')) ) ));
$api_data['execution_id'] =$upto;

$api_data_final = json_encode($api_data);
$result = $client->__soapCall('regularSyncLiveServerPermissionDataStock', array('data' => $api_data_final));

$error_found=json_decode($result)->error_found;
$message=json_decode($result)->message;

if($error_found==1){
	return 4;///Un-authorized Access.
}else{
	$json_data=json_decode($result)->data;
}
$insert_data_array=array();
if(count($json_data->stock_reference_no_array)){
	foreach ($json_data->stock_reference_no_array as $key => $value) {
		$insert_data="DELETE FROM stock_moves WHERE reference='$value' ;";
		$insert_data_array[]=$insert_data;
	}

	foreach ($json_data->stock_all_array as $key => $value) {
		$insert_data="INSERT INTO stock_moves(trans_no,stock_id,type,loc_code,tran_date,person_id,price,reference,qty,discount_percent,standard_cost,visible,lot_no) VALUES('".$value->trans_no."','".$value->stock_id."','".$value->type."','".$value->loc_code."','".$value->tran_date."','".$value->person_id."','".$value->price."','".$value->reference."','".$value->qty."','".$value->discount_percent."','".$value->standard_cost."','".$value->visible."','".$value->lot_no."') ;";
		$insert_data_array[]=$insert_data;
	}

	if(count($insert_data_array)){

		define("BASEPATH",'../../');
		require_once (BASEPATH.'application/config/database.php');

		define("SERVICE_HOST",$db['default']['hostname']);
		define("SERVICE_USER",$db['default']['username']);
		define("SERVICE_PASSWORD",$db['default']['password']);
		define("SERVICE_DB",$db['default']['database']);


		$db_config = mysql_connect(SERVICE_HOST, SERVICE_USER, SERVICE_PASSWORD);
		mysql_select_db(SERVICE_DB, $db_config);


		foreach ($insert_data_array as $key => $value) {
			mysql_query($value, $db_config);
		}

		echo '<table style="text-align:center; width:100%;">
					<tr style="text-align:center;padding:8px;">
					<td style="text-align:center;padding:8px;">
					<font style="color:#97FF00;font-weight:bold;background-color: #008148; padding:16px;font-size: 20px;">Local Stock Update server data updated successfully of date from : '.date("dS-M-Y",strtotime($upto)).'</font>
					</td>
					</tr>
					</table>';

	}

}
?>