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

$sync_id = unserialize(base64_decode($_REQUEST['id']));
$sync_date = unserialize(base64_decode($_REQUEST['date']));

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']);


$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;
$api_data['execution_id'] =$sync_id;


$api_data_final = json_encode($api_data);
$result = $client->__soapCall('regularSyncLiveServerPermissionData', 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->sale_id_all_array)){

	$sale_id_all_array=array();
	foreach ($json_data->sale_id_all_array as $key => $value) {
		$sale_id_all_array[$key]=(array)$value;
	}

	$details_sales=array();
	foreach ($json_data->details_sales as $key => $value) {
		$details_sales[$key]=(array)$value;
	}


	$sale_id_receipt_no=array();
	foreach ($json_data->sale_id_receipt_no as $key => $value) {
		$sale_id_receipt_no[$key]=$value;
	}

	$details_payment=array();
	foreach ($json_data->details_payment as $key => $value) {
		$details_payment[$key]=(array)$value;
	}
	foreach ($sale_id_all_array as $key => $value) {


		///////////////HAS SALES INFO////////////////

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

		$sql = "SELECT * FROM  ospos_sales WHERE receipt_no='".$value['receipt_no']."'";

		$result = mysql_query($sql, $db_config);
		$has_sale_id=0;
		
		while ($row = mysql_fetch_object($result)) {
			$has_sale_id=1;
		}
		if($has_sale_id==0){

			$insert_sql = "INSERT INTO ospos_sales(
			sale_time,
			customer_id,
			employee_id,
			payment_type,
			location,
			is_sync,
			receipt_no,
			acc_location,
			is_permission,
			clr_sync
			
			) VALUES('".$value['sale_time']."',
			'".$value['customer_id']."',
			'".$value['employee_id']."',
			'".$value['payment_type']."',
			'".$value['location']."',
			'1',
			'".$value['receipt_no']."',
			'".$value['acc_location']."',
			'1',
			'1')";
			mysql_query($insert_sql, $db_config);

		}else{
			$insert_data=" UPDATE ospos_sales SET customer_id='".$value['customer_id']."' WHERE receipt_no='".$value['receipt_no']."' ; ";
			$insert_data_array[]=$insert_data;
		}
	}
	mysql_close($db_config);


	foreach ($sale_id_receipt_no as $key => $value) {

		$insert_data="DELETE FROM ospos_sales_items WHERE sale_id=(SELECT sale_id FROM ospos_sales WHERE receipt_no='".$value."');";
		$insert_data_array[]=$insert_data;
	}



	foreach ($details_sales as $key => $value) {

		$insert_data="INSERT INTO ospos_sales_items (sale_id, stock_id, description, lot_no, line, quantity_purchased, item_cost_price, item_unit_price, discount_percent, total_discount, total_sale_amount, vat_enable_price, vat_percentage, vat_amount, sales_employee_code, vat_enable_price_after_discount, pcr_lot_no)
				VALUES((SELECT sale_id FROM ospos_sales WHERE receipt_no='".$sale_id_receipt_no[$value['sale_id']]."'),'".$value['stock_id']."','".$value['description']."','".$value['lot_no']."','".$value['line']."','".$value['quantity_purchased']."','".$value['item_cost_price']."','".$value['item_unit_price']."','".$value['discount_percent']."','".$value['total_discount']."','".$value['total_sale_amount']."','".$value['vat_enable_price']."','".$value['vat_percentage']."','".$value['vat_amount']."','".$value['sales_employee_code']."','".$value['vat_enable_price_after_discount']."','".$value['pcr_lot_no']."');";

		$insert_data_array[]=$insert_data;
	}

	foreach ($sale_id_receipt_no as $key => $value) {

		$insert_data="DELETE FROM ospos_sales_payments WHERE sale_id=(SELECT sale_id FROM ospos_sales WHERE receipt_no='".$value."');";
		$insert_data_array[]=$insert_data;

	}


	foreach ($details_payment as $key => $value) {
		$insert_data="INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount) VALUES((SELECT sale_id FROM ospos_sales WHERE receipt_no='".$sale_id_receipt_no[$value['sale_id']]."'),'".$value['payment_type']."','".$value['payment_amount']."');";
		$insert_data_array[]=$insert_data;
	}

	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)){

		$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);
		}



		$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;
		$api_data['execution_id'] =$sync_id;


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

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

		if($error_found==1){
			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:#2CFF00;font-weight:bold;background-color: #FF0000; padding:16px;font-size: 20px;">Error occour/internet problem during the data process of date : '.date("dS-M-Y",strtotime($sync_date)).'</font>
					</td>
					</tr>
					</table>';
		}else{
			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 server data updated successfully of date : '.date("dS-M-Y",strtotime($sync_date)).'</font>
					</td>
					</tr>
					</table>';

		}

	}else{
		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:#2CFF00;font-weight:bold;background-color: #FF0000; padding:16px;font-size: 20px;">Error occour/internet problem during the data process of date : '.date("dS-M-Y",strtotime($sync_date)).'</font>
					</td>
					</tr>
					</table>';
	}

}
?>