<?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 = 'Sync Transaction';
$this->params['breadcrumbs'][] = $this->title;

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

	    <?php
	    if (SyncConfig::isEmpty()) {
	    ?>
	    	<div>Please fill the configuration before starting the sync process.</div>
	    <?php
	    } elseif (!SyncToJurnal::canSalesSync()) {
	    ?>
	    	<div>Please sync master data before starting the transaction sync process.</div>
	    <?php
	    } else {
	    ?>
	    	<div class="row">
	    		<div class="col-sm-3">
	    			<?= Html::img('@web/images/sync-transaction.svg', ['alt' => 'Sync Transaction']) ?>
	    		</div>
	    		<div class="syncmast-content-right col-sm-9">
	    			<div class="row">
	    				<div class="col-sm-5">
	    					<div class="syncmast-content-right-title">Last Synced</div>
	    					<div class="syncmast-content-right-subtitle" id="last-sync"><?= $lastSync ? date("l, M d, Y, H:i:s", strtotime($lastSync['date'])) : '-' ?></div>
	    				</div>
	    				<div class="col-sm-5">
	    					<div class="syncmast-content-right-title">Status</div>
	    					<div class="syncmast-content-right-subtitle" id="status-sync"><?= $lastSync ? $lastSync['status'] : '-' ?></div>
	    				</div>
	    			</div>
	    			<div class="row synctran-content-right-date">
	    				<div class="col-md-4 form-group">
						    <label>Start date <em>(optional)</em></label>
				    		<?php
							echo DatePicker::widget([
							    'id' => 'date_start',
							    'name' => 'date_start',
							    'pluginOptions' => [
							        'autoclose' => true,
							        'format' => 'dd-M-yyyy'
							    ]
							]);
							?>
				    	</div>
				    	<div class="col-md-4 form-group">
						    <label>End date <em>(optional)</em></label>
				    		<?php
							echo DatePicker::widget([
							    'id' => 'date_end',
							    'name' => 'date_end',
							    'pluginOptions' => [
							        'autoclose' => true,
							        'format' => 'dd-M-yyyy'
							    ]
							]);
							?>
				    	</div>
				    	<div class="col-md-4 synctran-content-right-sync">
		    				<button class="btn btn-primary start-import">SYNC NOW</button>
			    			<button class="btn btn-danger stop-import hidden">STOP SYNC</button>
			    		</div>
	    			</div>
	    		</div>
	    	</div>

	    	<div class="syncmast-content-syncing invisible">Syncing Transaction Data ...</div>
			<?php
		    echo Progress::widget([
			    'percent' => 0,
			    'barOptions' => ['class' => 'progress-bar-success'],
		    	'options' => ['class' => 'active progress-striped invisible']
			]);
			?>

			<div class="syncmast-content-list">List Sync</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconTransaction" class="material-icons">check_box_outline_blank</i></span> Sync Sales (<span id="countTransaction">0</span> / <span id="totalTransaction"><?= number_format($total['transaction'], 0, ',', '.') ?></span>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconPayment" class="material-icons">check_box_outline_blank</i></span> Sync Payment (<span id="countPayment">0</span> / <span id="totalPayment"><?= number_format($total['payment'], 0, ',', '.') ?></span>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconDeposit" class="material-icons">check_box_outline_blank</i></span> Sync Deposit (<span id="countDeposit">0</span> / <span id="totalDeposit"><?= number_format($total['deposit'], 0, ',', '.') ?></span>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconSalesReturn" class="material-icons">check_box_outline_blank</i></span> Sync Sales Return (<span id="countSalesReturn">0</span> / <span id="totalSalesReturn"><?= number_format($total['salesReturn'], 0, ',', '.') ?></span>)
			</div>

			<?php
			Modal::begin([
			    'footer' => '<a href="'.Url::to(['sync-to-jurnal/index']).'" class="btn btn-close-modal">View Log</a> <button class="btn btn-primary btn-submit-modal btn-close-modal">Done</button>',
			    'footerOptions' => ['class' => 'syncmast-popup-footer'],
			    'id' => 'modal-success'
		    ]);
		    ?>
		    	<div class="syncmast-popup-content text-center">
		    		<i class="syncmast-popup-content-icon material-icons">check_circle_outline</i>
		    		<div class="syncmast-popup-content-title">Sync Transaction data is done</div>
		    		<div>All data are successfully synchronized</div>
		    	</div>
		    <?php
		    Modal::end();

		    Modal::begin([
			    'footer' => '<button class="btn btn-primary btn-show-log">View Error Log</button>',
			    'footerOptions' => ['class' => 'syncmast-popup-footer'],
			    'id' => 'modal-fail'
		    ]);
		    ?>
		    	<div class="syncmast-popup-content text-center">
		    		<i class="syncmast-popup-content-icon material-icons">error_outline</i>
		    		<div class="syncmast-popup-content-title">Sync Transaction data failed</div>
		    		<div><span class="syncmast-popup-content-failcount">6</span> data are incorrect. Please fix them and sync again</div>
		    	</div>
		    <?php
		    Modal::end();

		    Modal::begin([
		    	'header' => '<div>Error Log</div>',
			    'footer' => '<button class="btn btn-primary btn-close-modal">Close</button>',
			    'size' => 'modal-lg',
			    'id' => 'modal-log'
		    ]);
		    ?>
		    	<div class="syncmast-popup-content">
		    		<div>Data Synced</div>
		    		<div class="syncmast-popup-content-date">Wednesday, 24 Apr 2019, 13:41</div>

		    		<ul class="nav nav-tabs nav-justified">
						<li class="active"><a data-toggle="tab" href="#transaction">Sales (<span id="count-rst_fc_trans_header">0</span>)</a></li>
						<li><a data-toggle="tab" href="#payment">Payment (<span id="count-rst_fc_payment">0</span>)</a></li>
						<li><a data-toggle="tab" href="#deposit">Deposit (<span id="count-bp_customer_deposit">0</span>)</a></li>
						<li><a data-toggle="tab" href="#salesreturn">Sales Return (<span id="count-sales_return">0</span>)</a></li>
					</ul>

					<div class="tab-content">
						<div id="transaction" class="tab-pane fade in active">
							<table class="table" id="rst_fc_trans_header">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID SALES</th>
										<th>SALES CODE</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="payment" class="tab-pane fade">
							<table class="table" id="rst_fc_payment">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID PAYMENT</th>
										<th>PAYMENT DATE</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="deposit" class="tab-pane fade">
							<table class="table" id="bp_customer_deposit">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID DEPOSIT</th>
										<th>DEPOSIT DATE</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="salesreturn" class="tab-pane fade">
							<table class="table" id="sales_return">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID RETURN</th>
										<th>RETURN CODE</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>

		    	</div>
		    <?php
		    Modal::end();
		    ?>
		<?php
	    }
	    ?>
	</div>
</div>

<script type="text/javascript">
	var progress = 0;
	var continueSync = true;
	var idHeaderLog = 0;

	var totalTransaction = <?= $total['transaction'] ?>;
	var totalPayment = <?= $total['payment'] ?>;
	var totalDeposit = <?= $total['deposit'] ?>;
	var totalSalesReturn = <?= $total['salesReturn'] ?>;
	var countTransaction = 0;
	var countPayment = 0;
	var countDeposit = 0;
	var countSalesReturn = 0;
	var dateStart = '';
	var dateEnd = '';

	function formatDate(date) {
	    var d = new Date(date),
	        month = '' + (d.getMonth() + 1),
	        day = '' + d.getDate(),
	        year = d.getFullYear();

	    if (month.length < 2) month = '0' + month;
	    if (day.length < 2) day = '0' + day;

	    return [year, month, day].join('-');
	}

	function updateTotal() {
		dateStart = $('#date_start').val();
		dateEnd = $('#date_end').val();
		if (dateStart)
			dateStart = formatDate(dateStart);
		else
			dateStart = '';
		if (dateEnd)
			dateEnd = formatDate(dateEnd);
		else
			dateEnd = '';

		$.ajax({
			url: '<?= Url::to(['sync-to-jurnal/get-total-sync-data-transaction']); ?>',
			data: {json: true, start: dateStart, end: dateEnd},
			success: function(result) {
				result = JSON.parse(result);

				totalTransaction = result.transaction;
				totalPayment = result.payment;
				totalDeposit = result.deposit;
				totalSalesReturn = result.salesReturn;

				$('#totalTransaction').html(totalTransaction);
				$('#totalPayment').html(totalPayment);
				$('#totalDeposit').html(totalDeposit);
				$('#totalSalesReturn').html(totalSalesReturn);
			}
		});
	}

	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);
				if (result.detail.length == 0) {
					$('#modal-success').modal('show');

					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 };
					$('.syncmast-content-right-subtitle#last-sync').html(temp.toLocaleDateString("en-US", options));
					$('.syncmast-content-right-subtitle#status-sync').html('Success');
				} else {
					$('.syncmast-popup-content-failcount').html(result.detail.length);
					$('#modal-fail').modal('show');

					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 };
					$('.syncmast-popup-content-date').html(temp.toLocaleDateString("en-US", options));
					$('.syncmast-content-right-subtitle#last-sync').html(temp.toLocaleDateString("en-US", options));
					$('.syncmast-content-right-subtitle#status-sync').html('Fail');

					var count = {
						rst_fc_trans_header: 0,
						rst_fc_payment: 0,
						bp_customer_deposit: 0,
						sales_return: 0
					};
					result.detail.forEach(function(entry) {
						count[entry.tipe_tabel]++;
					    $('table#'+entry.tipe_tabel+' tbody').append(
					    	'<tr>'+
					    		'<td>'+count[entry.tipe_tabel]+'</td>'+
					    		'<td>'+entry.id_record+'</td>'+
					    		'<td>'+entry.fname+'</td>'+
					    		'<td>'+entry.keterangan+'</td>'+
					    	'</tr>'
					    );
					});
					for (var key in count) {
					    if (count.hasOwnProperty(key)) {
					    	$('#count-'+key).html(count[key]);
					    }
					}
				}

				console.log(result);
			}
		});
		
	}

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

		if (!$('#iconSalesReturn').hasClass('fa-spin')) {
			$('#iconSalesReturn').html('sync');
			$('#iconSalesReturn').addClass('fa-spin');
		}

		$.ajax({
			url: '<?= Url::to(['sales-return/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd, idHeaderLog: idHeaderLog},
			method: 'POST',
			success: function(result) {
				if (result == 'ret_tran') {
					progress = 100;
					$('#iconSalesReturn').removeClass('fa-spin');
					$('#iconSalesReturn').html('check_box');
					$('#countSalesReturn').html(totalSalesReturn.toLocaleString('id'));
				} else {
					countSalesReturn += parseInt(result);
					progress = Math.round(countSalesReturn / totalSalesReturn * 100 / 4) + 75;
					$('#countSalesReturn').html(countSalesReturn.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				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 = '';

		if (!$('#iconDeposit').hasClass('fa-spin')) {
			$('#iconDeposit').html('sync');
			$('#iconDeposit').addClass('fa-spin');
		}

		$.ajax({
			url: '<?= Url::to(['import-deposit/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd, idHeaderLog: idHeaderLog},
			method: 'POST',
			success: function(result) {
				if (result == 'depo') {
					progress = 75;
					$('#iconDeposit').removeClass('fa-spin');
					$('#iconDeposit').html('check_box');
					$('#countDeposit').html(totalDeposit.toLocaleString('id'));
				} else {
					countDeposit += parseInt(result);
					progress = Math.round(countDeposit / totalDeposit * 100 / 4) + 50;
					$('#countDeposit').html(countDeposit.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

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

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

		if (!$('#iconPayment').hasClass('fa-spin')) {
			$('#iconPayment').html('sync');
			$('#iconPayment').addClass('fa-spin');
		}

		$.ajax({
			url: '<?= Url::to(['import-payment/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd, idHeaderLog: idHeaderLog},
			method: 'POST',
			success: function(result) {
				if (result == 'pay') {
					progress = 50;
					$('#iconPayment').removeClass('fa-spin');
					$('#iconPayment').html('check_box');
					$('#countPayment').html(totalPayment.toLocaleString('id'));
				} else {
					countPayment += parseInt(result);
					progress = Math.round(countPayment / totalPayment * 100 / 4) + 25;
					$('#countPayment').html(countPayment.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

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

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

		if (!$('#iconTransaction').hasClass('fa-spin')) {
			$('#iconTransaction').html('sync');
			$('#iconTransaction').addClass('fa-spin');
		}

		$.ajax({
			url: '<?= Url::to(['import-transaction/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd, idHeaderLog: idHeaderLog},
			method: 'POST',
			success: function(result) {
				if (result == 'tran') {
					progress = 25;
					$('#iconTransaction').removeClass('fa-spin');
					$('#iconTransaction').html('check_box');
					$('#countTransaction').html(totalTransaction.toLocaleString('id'));
				} else {
					countTransaction += parseInt(result);
					progress = Math.round(countTransaction / totalTransaction * 100 / 4);
					$('#countTransaction').html(countTransaction.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				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: 'manual', 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() {
		dateStart = $('#date_start').val();
		dateEnd = $('#date_end').val();
		if (dateStart)
			dateStart = formatDate(dateStart);
		else
			dateStart = '0000-00-00';
		if (dateEnd)
			dateEnd = formatDate(dateEnd);
		else
			dateEnd = '0000-00-00';

		continueSync = true;
		$('.start-import').addClass('hidden');
		$('.stop-import').removeClass('hidden');
		$('.syncmast-content-syncing').removeClass('invisible');
		$('.progress-striped').removeClass('invisible');
		insertHeaderLog();
	});

	$('.stop-import').click(function() {
		continueSync = false;
		$('.start-import').removeClass('hidden');
		$('.stop-import').addClass('hidden');
		$('.fa-spin').removeClass('fa-spin');
		$('.sync-icon i').html('check_box_outline_blank');
		$('.syncmast-content-syncing').addClass('invisible');
		$('.progress-striped').addClass('invisible');
	});

	$('.btn-close').click(function() {
		continueSync = true;
		$('.start-import').removeClass('hidden');
		$('.stop-import').addClass('hidden');
		$('.modal').modal('hide');
	});

	$('.btn-show-log').click(function() {
		$('#modal-fail').modal('hide');
		$('#modal-log').modal('show');
	});

	$('#date_start').change(function() {
		updateTotal();
	});

	$('#date_end').change(function() {
		updateTotal();
	});
</script>