<?php
use yii\helpers\Html;
use yii\helpers\Url;

use yii\bootstrap\Progress;
use yii\bootstrap\Modal;
use myresto\models\SyncToJurnal;
use myresto\models\SyncConfig;
use kartik\date\DatePicker;

$this->title = 'Live Sync Transaction';
$this->params['breadcrumbs'][] = $this->title;

$total = SyncToJurnal::getTotalSyncDataTransaction();
$lastSync = SyncToJurnal::getLastSync('transaksi', 'otomatis');
?>
<div class="content-page livesync">
    <div class="content-page-header updacc-header">
        <a href="<?= Url::to(['import-data-transaction/index']) ?>">Sync Transaction</a>
        <span><?= Html::encode($this->title) ?></span>
    </div>
    <div class="content-page-content syncmast-content container-fluid">

	    <?php
	    if (SyncConfig::isEmpty()) {
	    ?>
	    	<div>Please fill the configuration before starting the live sync process.</div>
	    <?php
	    } else {
	    ?>

		    <div class="livesync-content-warning">
		    	<i class="livesync-content-warning-icon material-icons">error_outline</i>
		        <div class="livesync-content-warning-desc">
		        	<b>Mohon tidak muat ulang halaman ini atau pindah dari halaman ini</b> saat Proses Live Sync Transaction sedang berjalan. Jika ingin pindah halaman gunakan <b>new tab</b> dan jika ingin menyelesaikan Live Sync Transaction silakan tekan tombol <b>"Stop Live Sync"</b>. 
		        </div>
		    </div>

		    <div class="text-center">
		    	<i class="livesync-content-icon material-icons">sync</i>
		    	<div class="livesync-content-lastsync row">
		    		<div class="livesync-content-lastsync-date col-md-9 text-left">
		    			<div>Last Sync</div>
		    			<div class="livesync-content-lastsync-date-value" id="last-sync"><?= $lastSync ? date("l, M d, Y, H:i:s", strtotime($lastSync['date'])) : '-' ?></div>
		    		</div>
		    		<div class="livesync-content-lastsync-status col-md-3 text-left">
		    			<div>Status</div>
		    			<div class="livesync-content-lastsync-status-value" id="status-sync"><?= $lastSync ? $lastSync['status'] : '-' ?></div>
		    		</div>
		    	</div>

		    	<div class="livesync-content-running hidden">Live Sync is Running ...</div>
		    	<div class="livesync-content-progress row hidden">
		    		<div class="livesync-content-progress-title col-md-9 text-left">
		    			Sync Sales
		    		</div>
		    		<div class="livesync-content-progress-count col-md-3 text-right" id="countTransaction">
		    			0
		    		</div>
		    		<div class="livesync-content-progress-title col-md-9 text-left">
		    			Sync Payment
		    		</div>
		    		<div class="livesync-content-progress-count col-md-3 text-right" id="countPayment">
		    			0
		    		</div>
		    		<div class="livesync-content-progress-title col-md-9 text-left">
		    			Sync Deposit
		    		</div>
		    		<div class="livesync-content-progress-count col-md-3 text-right" id="countDeposit">
		    			0
		    		</div>
		    		<div class="livesync-content-progress-title col-md-9 text-left">
		    			Sync Sales Return
		    		</div>
		    		<div class="livesync-content-progress-count col-md-3 text-right" id="countSalesReturn">
		    			0
		    		</div>
		    	</div>

		    	<button class="btn btn-primary start-import">LIVE SYNC NOW</button>
		    	<button class="btn btn-danger stop-import hidden">STOP LIVE SYNC</button>
		    </div>
		    
		<?php
	    }
	    ?>
	</div>
</div>

<?php
if (!SyncConfig::isEmpty()) {
?>
	<script type="text/javascript">
		var continueSync = false;
		var idHeaderLog = 0;

		var countTransaction = 0;
		var countPayment = 0;
		var countDeposit = 0;
		var countSalesReturn = 0;

		function updateCount() {
			$('#countTransaction').html(countTransaction);
			$('#countPayment').html(countPayment);
			$('#countDeposit').html(countDeposit);
			$('#countSalesReturn').html(countSalesReturn);
		}

		function checkLog() {
		$.ajax({
			url: '<?= Url::to(['sync-to-jurnal/check-log']); ?>',
			data: {idHeaderLog: idHeaderLog, type_con: 'resto'},
			method: 'post',
			success: function(result) {
				result = JSON.parse(result);
				var temp = new Date(result.header.date_created);
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false };
				$('.livesync-content-lastsync-date-value#last-sync').html(temp.toLocaleDateString("en-US", options));
				if (result.detail.length == 0) {
					$('.livesync-content-lastsync-status-value#status-sync').html('Success');
				} else {
					$('.livesync-content-lastsync-status-value#status-sync').html('Fail');
				}
				console.log(result);

				importDataTransaction();
			}
		});
		
	}

		function importDataSalesReturn() {
			console.log('begin import sales return');
			var data = '';

			$.ajax({
				url: '<?= Url::to(['sales-return/index']); ?>',
				data: {idHeaderLog: idHeaderLog},
				method: 'POST',
				success: function(result) {
					if (result == 'ret_tran') {
					} else {
						countSalesReturn += parseInt(result);
						updateCount();
					}

					data = result;
					console.log(data);
				},
				complete: function() {
					if (continueSync) {
						if (data != 'ret_tran')
							importDataSalesReturn();
						else
							checkLog();
					}
				}
			});
		}

		function importDataDeposit() {
			console.log('begin import deposit');
			var data = '';

			$.ajax({
				url: '<?= Url::to(['import-deposit/index']); ?>',
				data: {idHeaderLog: idHeaderLog},
				method: 'POST',
				success: function(result) {
					if (result == 'depo') {
					} else {
						countDeposit += parseInt(result);
						updateCount();
					}

					data = result;
					console.log(data);
				},
				complete: function() {
					if (continueSync) {
						if (data != 'depo')
							importDataDeposit();
						else
							importDataSalesReturn();
					}
				}
			});
		}

		function importDataPayment() {
			console.log('begin import payment');
			var data = '';

			$.ajax({
				url: '<?= Url::to(['import-payment/index']); ?>',
				data: {idHeaderLog: idHeaderLog},
				method: 'POST',
				success: function(result) {
					if (result == 'pay') {
					} else {
						countPayment += parseInt(result);
						updateCount();
					}

					data = result;
					console.log(data);
				},
				complete: function() {
					if (continueSync) {
						if (data != 'pay')
							importDataPayment();
						else
							importDataDeposit();
					}
				}
			});
		}

		function importDataTransaction() {
			console.log('begin import transaction');
			var data = '';

			$.ajax({
				url: '<?= Url::to(['import-transaction/index']); ?>',
				data: {idHeaderLog: idHeaderLog},
				method: 'POST',
				success: function(result) {
					if (result == 'tran') {
					} else {
						countTransaction += parseInt(result);
						updateCount();
					}

					data = result;
					console.log(data);
				},
				complete: function() {
					if (continueSync) {
						if (data != 'tran')
							importDataTransaction();
						else
							importDataPayment();
					}
				}
			});
		}

		function insertHeaderLog() {
			console.log('begin insert header log');

			$.ajax({
				url: '<?= Url::to(['sync-to-jurnal/insert-header-log']); ?>',
				data: {jenis_sinkron: 'otomatis', jenis_data: 'transaksi', type_con: 'resto'},
				method: 'post',
				success: function(result) {
					idHeaderLog = result;
					console.log(idHeaderLog);
				},
				complete: function() {
					if (continueSync) {
						importDataTransaction();
					}
				}
			});
		}

		$('.start-import').click(function() {
			continueSync = true;
			$('.start-import').addClass('hidden');
			$('.stop-import').removeClass('hidden');
			$('.livesync-content-lastsync').addClass('hidden');
			$('.livesync-content-icon').addClass('fa-spin');
			$('.livesync-content-running').removeClass('hidden');
			$('.livesync-content-progress').removeClass('hidden');
			if (idHeaderLog == 0)
				insertHeaderLog();
			else
				importDataTransaction();
		});

		$('.stop-import').click(function() {
			continueSync = false;
			$('.start-import').removeClass('hidden');
			$('.stop-import').addClass('hidden');
			$('.livesync-content-lastsync').removeClass('hidden');
			$('.livesync-content-icon').removeClass('fa-spin');
			$('.livesync-content-running').addClass('hidden');
			$('.livesync-content-progress').addClass('hidden');
		});
	</script>
<?php
}
?>