<?php
use yii\helpers\Html;
use myresto\models\SyncConfig;
use myresto\models\SyncToJurnal;
use myresto\models\SyncToJurnalHeader;
use yii\helpers\Url;
use kartik\daterange\DateRangePicker;
/* @var $this yii\web\View */

$this->title = 'Home';
$emptySyncConfig = SyncConfig::isEmpty();
$canSalesSync = SyncToJurnal::canSalesSync();

$config = SyncConfig::find()->where(['type_con' => 'resto'])->one();
$branchCode = $config->branch_code;

$lastSyncMaster = SyncToJurnal::getLastSync('master', 'manual');
$lastSyncTransaction = SyncToJurnal::getLastSync('transaksi', 'manual');
$lastSyncLive = SyncToJurnal::getLastSync('transaksi', 'otomatis');

$errorData = SyncToJurnalHeader::getErrorData();
?>
<div class="home container-fluid">
	<div class="home-steps row text-center">
		<div class="home-title home-steps-title text-left hidden">Getting Started</div>
		<div class="home-steps-step col-md-4">
			<div class="home-steps-step-number" id="step-1"><span>1</span></div>
			<div class="home-steps-step-title">Configuration</div>
			<div class="home-steps-step-desc">Silakan Anda mengatur konfigurasi yang meliputi atur akun, payment metode, dll agar data InterActive MyResto Anda terhubung dengan Jurnal.</div>
			<a href="<?= Url::to(['sync-config/update', 'id' => $branchCode]) ?>" class="home-steps-step-button btn">Config Now</a>
		</div>
		<div class="home-steps-step col-md-4">
			<div class="home-steps-step-number" id="step-2"><span>2</span></div>
			<div class="home-steps-step-title">Sync Master Data</div>
			<div class="home-steps-step-desc">Sinkron data master meliputi produk, modifier, pelanggan, suplier. Sebelum sinkron data master berhasil, Anda tidak dapat sinkron transaksi.</div>
			<a href="<?= Url::to(['import-master/index']) ?>" class="home-steps-step-button btn <?= $emptySyncConfig ? 'disabled' : '' ?>">Sync Now</a>
		</div>
		<div class="home-steps-step col-md-4">
			<div class="home-steps-step-number" id="step-3"><span>3</span></div>
			<div class="home-steps-step-title">Sync Transaction</div>
			<div class="home-steps-step-desc">Sinkron transaksi meliputi penjualan, pembayaran, setoran, pengembalian penjualan. Sinkron dengan manual berdasarkan periode atau live sync.</div>
			<a href="<?= Url::to(['import-data-transaction/index']) ?>" class="home-steps-step-button btn <?= ($emptySyncConfig || !$canSalesSync) ? 'disabled' : '' ?>">Manual Sync</a>
			<a href="<?= Url::to(['auto-sync/index']) ?>" class="home-steps-step-button btn <?= ($emptySyncConfig || !$canSalesSync) ? 'disabled' : '' ?>">Live Sync</a>
		</div>
		<i class="home-steps-toggle material-icons">keyboard_arrow_up</i>
	</div>

	<div class="home-error row">
		<div class="home-title">Error Sync</div>
		<div class="home-error-chart col-md-8">
			<canvas id="home-chart"></canvas>
		</div>
		<div class="home-error-filter form-group">
			<?php
			date_default_timezone_set("Asia/Jakarta");
			$dateStart = date('d M Y', strtotime('-6 days'));
            $dateEnd = date('d M Y');
			echo DateRangePicker::widget([
			    'name' => 'home-error-filter-select',
			    'presetDropdown' => true,
    			'hideInput' => true,
			    'value' => "$dateStart - $dateEnd",
			    'convertFormat' => true,
			    'useWithAddon' => true,
			    'pluginOptions' => [
			        'locale' => [
			            'format' => 'd M Y',
			            'separator' => ' - ',
			        ],
			        'opens' => 'left'
			    ],
			    'options' => [
			        'class' => 'home-error-filter-select'
			    ]
			]);
			?>
        </div>
		<div class="home-error-data col-md-4">
			<div class="home-error-data-total">
				Total Error Sync
				<div><span><?= $errorData['total']['total'] ?></span> Error</div>
			</div>
			<div class="row">
				<div class="col-md-6">
					<div class="home-error-data-col">
						<div class="home-error-data-col-title">Master Data</div>
						<div class="home-error-data-col-count"><?= $errorData['total']['master'] ?></div>
						<div class="home-error-data-col-error">Error</div>
						<div class="home-error-data-col-status"><?= $lastSyncMaster ? $lastSyncMaster['status'] == 'Fail' ? 'Unsolved' : 'Solved' : '-' ?></div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="home-error-data-col">
						<div class="home-error-data-col-title">Transaction</div>
						<div class="home-error-data-col-count"><?= $errorData['total']['transaksi'] ?></div>
						<div class="home-error-data-col-error">Error</div>
						<div class="home-error-data-col-status"><?= $lastSyncTransaction ? $lastSyncTransaction['status'] == 'Fail' ? 'Unsolved' : 'Solved' : '-' ?></div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="home-row">
		<div class="col-md-4">
			<div class="home-last">
				<div class="home-title">Last Synced</div>
				<div class="row">
					<div class="col-md-3"><?= Html::img('@web/images/sync-master.svg', ['alt' => 'Sync Master']) ?></div>
					<div class="col-md-9">
						<div class="home-last-type">Master Data</div>
						<div class="home-last-date"><?= $lastSyncMaster ? date("l, d M Y, H:i", strtotime($lastSyncMaster['date'])) : '-' ?></div>
						<div class="home-last-status"><?= $lastSyncMaster ? $lastSyncMaster['status'] : '-' ?></div>
					</div>
				</div>
				<div class="row">
					<div class="col-md-3"><?= Html::img('@web/images/sync-transaction.svg', ['alt' => 'Sync Transaction']) ?></div>
					<div class="col-md-9">
						<div class="home-last-type">Transaction</div>
						<div class="home-last-date"><?= $lastSyncTransaction ? date("l, d M Y, H:i", strtotime($lastSyncTransaction['date'])) : '-' ?></div>
						<div class="home-last-status"><?= $lastSyncTransaction ? $lastSyncTransaction['status'] : '-' ?></div>
					</div>
				</div>
				<div class="row">
					<div class="col-md-3"></div>
					<div class="col-md-9">
						<div class="home-last-type">Live Sync Transaction</div>
						<div class="home-last-date"><?= $lastSyncLive ? date("l, d M Y, H:i", strtotime($lastSyncLive['date'])) : '-' ?></div>
						<div class="home-last-status home-last-status-last"><?= $lastSyncLive ? $lastSyncLive['status'] : '-' ?></div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-4">
			<div class="home-user">
				<div class="home-title">User</div>
				<a href="<?= Url::to(['admin/user']) ?>" class="home-user-link">See All</a>
				<table class="table" id="rst_fc_trans_header">
	    			<thead>
						<tr>
							<th>TYPE ROLE</th>
							<th>TOTAL</th>
						</tr>
					</thead>
					<tbody>
						<?php
						$roles = \Yii::$app->authManager->getRoles();
						foreach ($roles as $key => $value) {
							$users = \Yii::$app->authManager->getUserIdsByRole($value->name);
							?>
							<tr>
								<td><?= $value->name ?></td>
								<td><?= count($users) ?> user</td>
							</tr>
							<?php
						}
						?>
					</tbody>
				</table>
			</div>
		</div>
		<div class="col-md-4">
			<div class="home-help">
				<div class="home-title">Help</div>
				<a href="<?= Url::to(['site/help']) ?>">
					<div class="home-help-title">Knowledge Base</div>
					<div class="home-help-desc">The fastest way to get support is finding the answer throught Knowledge Base system</div>
					<div class="home-help-title">Ticket Support</div>
					<div class="home-help-desc">You can also easily access the ticket support to answer about InterActive MyConnection</div>
				</a>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
	var stepsHidden = false;
	var myChart = '';
	var dateStart = '<?= $dateStart ?>';
	var dateEnd = '<?= $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('-');
	}
	console.log(formatDate(dateStart));

	$('.home-steps-toggle').click(function() {
		if (stepsHidden) {
			$('.home-steps-step').removeClass('hidden');
			$('.home-steps-title').addClass('hidden');
			$('.home-steps-toggle').html('keyboard_arrow_up');
			stepsHidden = false;
		} else {
			$('.home-steps-step').addClass('hidden');
			$('.home-steps-title').removeClass('hidden');
			$('.home-steps-toggle').html('keyboard_arrow_down');
			stepsHidden = true;
		}
	});

	function updateChart(dateStart, dateEnd) {
		$.ajax({
			url: '<?= Url::to(['sync-to-jurnal-header/get-error-data']); ?>',
			data: {dateStart: dateStart, dateEnd: dateEnd},
			method: 'get',
			success: function(result) {
				result = JSON.parse(result);
				console.log(result);
				myChart.data = {
		            labels: result.resultChart.labels,
		            datasets: [{
		                label: 'Error Count',
		                data: result.resultChart.data
		            }]
		        };
        		myChart.update();
			},
			complete: function() {
			}
		});
	}

	$(document).ready(function() {
		var ctx = document.getElementById('home-chart').getContext('2d');
	    myChart = new Chart(ctx, {
	        type: 'line',
	        data: {},
	        options: {
	            backgroundColor: 'rgba(255, 99, 132, 0.2)',
	            scales: {
	                yAxes: [{
	                    ticks: {
	                        beginAtZero: true
	                    }
	                }]
	            }
	        }
	    });

		updateChart('', '');
	});
	
</script>