<?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;

$this->title = 'Sync Master Data';
$this->params['breadcrumbs'][] = $this->title;

$total = SyncToJurnal::getTotalSyncDataMaster();
$lastSync = SyncToJurnal::getLastSync('master', 'manual');
?>
<div class="content-page syncmast">
    <div class="content-page-header"><?= Html::encode($this->title) ?></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
	    } else {
	    ?>
	    	<div class="row">
	    		<div class="col-sm-3">
	    			<?= Html::img('@web/images/sync-master.svg', ['alt' => 'Sync Master']) ?>
	    		</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="syncmast-content-right-desc">
	    				* Pastikan sinkron data master benar-benar berhasil seluruhnya, sebagai syarat untuk melanjutkan proses sinkron transaksi
	    			</div>
	    			<div>
	    				<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 class="syncmast-content-syncing invisible">Syncing Master 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 ="iconProduct" class="material-icons">check_box_outline_blank</i></span> Sync Product (<span id="countProduct">0</span> / <?= number_format($total['product'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconModifier" class="material-icons">check_box_outline_blank</i></span> Sync Modifier (<span id="countModifier">0</span> / <?= number_format($total['modifier'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconCustomer" class="material-icons">check_box_outline_blank</i></span> Sync Customer (<span id="countCustomer">0</span> / <?= number_format($total['customer'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconSupplier" class="material-icons">check_box_outline_blank</i></span> Sync Supplier (<span id="countSupplier">0</span> / <?= number_format($total['supplier'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconUpdateProduct" class="material-icons">check_box_outline_blank</i></span> Sync Update Product (<span id="countUpdateProduct">0</span> / <?= number_format($total['updateProduct'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconUpdateCustomer" class="material-icons">check_box_outline_blank</i></span> Sync Update Customer (<span id="countUpdateCustomer">0</span> / <?= number_format($total['updateCustomer'], 0, ',', '.') ?>)
			</div>
			<div class="syncmast-content-syncitem">
				<span class="sync-icon"><i id ="iconUpdateSupplier" class="material-icons">check_box_outline_blank</i></span> Sync Update Supplier (<span id="countUpdateSupplier">0</span> / <?= number_format($total['updateSupplier'], 0, ',', '.') ?>)
			</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 Master 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 Master 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="#product">Product (<span id="count-rst_menu">0</span>)</a></li>
						<li><a data-toggle="tab" href="#modifier">Modifier (<span id="count-rst_menu_notes2">0</span>)</a></li>
						<li><a data-toggle="tab" href="#customer">Customer (<span id="count-bp_customer">0</span>)</a></li>
						<li><a data-toggle="tab" href="#supplier">Supplier (<span id="count-bp_supplier">0</span>)</a></li>
					</ul>

					<div class="tab-content">
						<div id="product" class="tab-pane fade in active">
							<table class="table" id="rst_menu">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID PRODUCT</th>
										<th>PRODUCT NAME</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="modifier" class="tab-pane fade">
							<table class="table" id="rst_menu_notes2">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID MODIFIER</th>
										<th>MODIFIER CODE</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="customer" class="tab-pane fade">
							<table class="table" id="bp_customer">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID CUSTOMER</th>
										<th>CUSTOMER NAME</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>

						<div id="supplier" class="tab-pane fade">
							<table class="table" id="bp_supplier">
				    			<thead>
									<tr>
										<th>NO</th>
										<th>ID SUPPLIER</th>
										<th>SUPPLIER NAME</th>
										<th>ERROR NOTE</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>

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

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

	var totalProduct = <?= $total['product'] ?>;
	var totalModifier = <?= $total['modifier'] ?>;
	var totalCustomer = <?= $total['customer'] ?>;
	var totalSupplier = <?= $total['supplier'] ?>;
	var countProduct = 0;
	var countModifier = 0;
	var countCustomer = 0;
	var countSupplier = 0;

	var totalUpdateProduct = <?= $total['updateProduct'] ?>;
	var totalUpdateCustomer = <?= $total['updateCustomer'] ?>;
	var totalUpdateSupplier = <?= $total['updateSupplier'] ?>;
	var countUpdateProduct = 0;
	var countUpdateCustomer = 0;
	var countUpdateSupplier = 0;

	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_menu: 0,
						rst_menu_notes2: 0,
						bp_customer: 0,
						bp_supplier: 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 updateDataSupplier() {
		console.log('begin update supplier');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['update-supplier/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'upsupp') {
					progress = 100;
					$('#iconUpdateSupplier').removeClass('fa-spin');
					$('#iconUpdateSupplier').html('check_box');
					$('#countUpdateSupplier').html(totalUpdateSupplier.toLocaleString('id'));
				} else {
					countUpdateSupplier += parseInt(result);
					progress = Math.round(countUpdateSupplier / totalUpdateSupplier * 100 / 7) + 85;
					$('#countUpdateSupplier').html(countUpdateSupplier.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

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

	function updateDataCustomer() {
		console.log('begin update customer');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['update-customer/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'upcust') {
					progress = 85;
					$('#iconUpdateCustomer').removeClass('fa-spin');
					$('#iconUpdateCustomer').html('check_box');
					$('#countUpdateCustomer').html(totalUpdateCustomer.toLocaleString('id'));
				} else {
					countUpdateCustomer += parseInt(result);
					progress = Math.round(countUpdateCustomer / totalUpdateCustomer * 100 / 7) + 71;
					$('#countUpdateCustomer').html(countUpdateCustomer.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'upcust')
						updateDataCustomer();
					else
						updateDataSupplier();
				}
			}
		});
	}

	function updateDataProduct() {
		console.log('begin update product');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['update-product/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'upprod') {
					progress = 71;
					$('#iconUpdateProduct').removeClass('fa-spin');
					$('#iconUpdateProduct').html('check_box');
					$('#countUpdateProduct').html(totalUpdateProduct.toLocaleString('id'));
				} else {
					countUpdateProduct += parseInt(result);
					progress = Math.round(countUpdateProduct / totalUpdateProduct * 100 / 7) + 57;
					$('#countUpdateProduct').html(countUpdateProduct.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'upprod')
						updateDataProduct();
					else
						updateDataCustomer();
				}
			}
		});
	}

	function importDataSupplier() {
		console.log('begin import supplier');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['import-supplier/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'supp') {
					progress = 57;
					$('#iconSupplier').removeClass('fa-spin');
					$('#iconSupplier').html('check_box');
					$('#countSupplier').html(totalSupplier.toLocaleString('id'));
				} else {
					countSupplier += parseInt(result);
					progress = Math.round(countSupplier / totalSupplier * 100 / 7) + 43;
					$('#countSupplier').html(countSupplier.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'supp')
						importDataSupplier();
					else {
						updateDataProduct();
					}
				}
			}
		});
	}

	function importDataCustomer() {
		console.log('begin import customer');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['import-customer/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'cust') {
					progress = 43;
					$('#iconCustomer').removeClass('fa-spin');
					$('#iconCustomer').html('check_box');
					$('#countCustomer').html(totalCustomer.toLocaleString('id'));
				} else {
					countCustomer += parseInt(result);
					progress = Math.round(countCustomer / totalCustomer * 100 / 7) + 29;
					$('#countCustomer').html(countCustomer.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'cust')
						importDataCustomer();
					else
						importDataSupplier();
				}
			}
		});
	}

	function importDataModifier() {
		console.log('begin import modifier');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['import-modifier/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'mod') {
					progress = 29;
					$('#iconModifier').removeClass('fa-spin');
					$('#iconModifier').html('check_box');
					$('#countModifier').html(totalModifier.toLocaleString('id'));
				} else {
					countModifier += parseInt(result);
					progress = Math.round(countModifier / totalModifier * 100 / 7) + 14;
					$('#countModifier').html(countModifier.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'mod')
						importDataModifier();
					else
						importDataCustomer();
				}
			}
		});
	}

	function importDataProduct() {
		console.log('begin import product');
		var data = '';

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

		$.ajax({
			url: '<?= Url::to(['import-product/index']); ?>',
			data: {idHeaderLog: idHeaderLog},
			method: 'post',
			success: function(result) {
				if (result == 'prod') {
					progress = 14;
					$('#iconProduct').removeClass('fa-spin');
					$('#iconProduct').html('check_box');
					$('#countProduct').html(totalProduct.toLocaleString('id'));
				} else {
					countProduct += parseInt(result);
					progress = Math.round(countProduct / totalProduct * 100 / 7);
					$('#countProduct').html(countProduct.toLocaleString('id'));
				}
				$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

				data = result;
				console.log(data);
			},
			complete: function() {
				if (continueSync) {
					if (data != 'prod')
						importDataProduct();
					else
						importDataModifier();
				}
			}
		});
	}

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

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

	$('.start-import').click(function() {
		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');
	});
</script>