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

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

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

$total = SyncToJurnal::getTotalSyncDataTransaction();
?>
<div class="import-transaksi-index">
    <h1><?= Html::encode($this->title) ?></h1>

    <?php
    if (SyncConfig::isEmpty()) {
    ?>
    	<div>Please fill the configuration before starting the sync process.</div>
    <?php
    } elseif (!SyncToJurnal::canSalesSync()) {
    ?>
    	<div>Please do master sync before starting the sales sync process.</div>
    <?php
    } else {
    ?>
	    <div class="row">
	    	<div class="col-md-6 form-group">
			    <label>From Date</label>
	    		<?php
				echo DatePicker::widget([
				    'id' => 'date_start',
				    'name' => 'date_start',
				    'pluginOptions' => [
				        'autoclose' => true,
				        'format' => 'dd-M-yyyy'
				    ]
				]);
				?>
	    	</div>
	    	<div class="col-md-6 form-group">
			    <label>To Date</label>
	    		<?php
				echo DatePicker::widget([
				    'id' => 'date_end',
				    'name' => 'date_end',
				    'pluginOptions' => [
				        'autoclose' => true,
				        'format' => 'dd-M-yyyy'
				    ]
				]);
				?>
	    	</div>
	    </div>

		<?php
	    echo Progress::widget([
		    'percent' => 0,
		    'barOptions' => ['class' => 'progress-bar-success'],
	    	'options' => ['class' => 'active progress-striped']
		]);
		?>
		<div>
			<span class="sync-icon"><i id ="iconTransaction" class="fa fa-square-o"></i></span> Sync Sales (<span id="countTransaction">0</span> / <span id="totalTransaction"><?= number_format($total['transaction'], 0, ',', '.') ?></span>)
		</div>
		<div>
			<span class="sync-icon"><i id ="iconPayment" class="fa fa-square-o"></i></span> Sync Payment (<span id="countPayment">0</span> / <span id="totalPayment"><?= number_format($total['payment'], 0, ',', '.') ?></span>)
		</div>
		<div>
			<span class="sync-icon"><i id ="iconSalesReturn" class="fa fa-square-o"></i></span> Sync Sales Return (<span id="countSalesReturn">0</span> / <span id="totalSalesReturn"><?= number_format($total['salesReturn'], 0, ',', '.') ?></span>)
		</div>

		<?php
		Modal::begin([
			// 'header' => '<h2>Hello world</h2>',
			'footer' => '<button class="btn btn-primary btn-close">OK</button>',
			'clientEvents' => [
				'hide.bs.modal' => "function(e) {
					$('.progress-bar').css('width', '0%').attr('aria-valuenow', 0);
					$('.sync-icon i').removeClass('fa-check-square-o');
					$('.sync-icon i').addClass('fa-square-o');
				}"
			],
	    ]);
	    echo 'Sync done!';
	    Modal::end();
	    ?>

	    <button class="btn btn-primary start-import">Mulai Sync</button>
	    <button class="btn btn-danger stop-import">Stop Sync</button>
	<?php
    }
    ?>
</div>

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

	var totalTransaction = <?= $total['transaction'] ?>;
	var totalPayment = <?= $total['payment'] ?>;
	var totalSalesReturn = <?= $total['salesReturn'] ?>;
	var countTransaction = 0;
	var countPayment = 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;
				totalSalesReturn = result.salesReturn;

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

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

		if (!$('#iconSalesReturn').hasClass('fa-spinner')) {
			$('#iconSalesReturn').removeClass('fa-square-o');
			$('#iconSalesReturn').addClass('fa-spinner fa-pulse');
		}

		$.ajax({
			url: '<?= Url::to(['sales-return/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd},
			method: 'POST',
			success: function(result) {
				if (result == 'ret_tran') {
					progress = 100;
					$('#iconSalesReturn').removeClass('fa-spinner fa-pulse');
					$('#iconSalesReturn').addClass('fa-check-square-o');
					$('#countSalesReturn').html(totalSalesReturn.toLocaleString('id'));
				} else {
					countSalesReturn += parseInt(result);
					progress = Math.round(countSalesReturn / totalSalesReturn * 100 / 3) + 66;
					$('#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
						$('.modal').modal('show');
				}
			}
		});
	}

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

		if (!$('#iconPayment').hasClass('fa-spinner')) {
			$('#iconPayment').removeClass('fa-square-o');
			$('#iconPayment').addClass('fa-spinner fa-pulse');
		}

		$.ajax({
			url: '<?= Url::to(['import-payment/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd},
			method: 'POST',
			success: function(result) {
				if (result == 'pay') {
					progress = 66;
					$('#iconPayment').removeClass('fa-spinner fa-pulse');
					$('#iconPayment').addClass('fa-check-square-o');
					$('#countPayment').html(totalPayment.toLocaleString('id'));
				} else {
					countPayment += parseInt(result);
					progress = Math.round(countPayment / totalPayment * 100 / 3) + 33;
					$('#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
						importDataSalesReturn();
				}
			}
		});
	}

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

		if (!$('#iconTransaction').hasClass('fa-spinner')) {
			$('#iconTransaction').removeClass('fa-square-o');
			$('#iconTransaction').addClass('fa-spinner fa-pulse');
		}

		$.ajax({
			url: '<?= Url::to(['import-transaction/index']); ?>',
			data: {date_start: dateStart, date_end: dateEnd},
			method: 'POST',
			success: function(result) {
				if (result == 'tran') {
					progress = 33;
					$('#iconTransaction').removeClass('fa-spinner fa-pulse');
					$('#iconTransaction').addClass('fa-check-square-o');
					$('#countTransaction').html(totalTransaction.toLocaleString('id'));
				} else {
					countTransaction += parseInt(result);
					progress = Math.round(countTransaction / totalTransaction * 100 / 3);
					$('#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();
				}
			}
		});
	}

	$('.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;
		importDataTransaction();
	});

	$('.stop-import').click(function() {
		continueSync = false;
		$('.fa-spinner.fa-pulse').removeClass('fa-spinner fa-pulse').addClass('fa-square-o');
		$('.sync-icon i').removeClass('fa-check-square-o');
		$('.sync-icon i').addClass('fa-square-o');
	});

	$('.btn-close').click(function() {
		continueSync = true;
		$('.modal').modal('hide');
	});

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

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