<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Progress;
use yii\bootstrap\Modal;

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

$session = Yii::$app->session;

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://interactive.co.id/myconnection/restapi/api.php",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => "version=1.0.0&myconnectionType=myresto"
));
$response = json_decode(curl_exec($curl), true);
curl_close($curl);

$data = array();
if ($response['dataCount'] > 0)
    $data = $response['data'];

$currentVersion = Yii::$app->params['appVersion'];

Modal::begin([
	'header' => '<div>Update History</div>',
    'footer' => '<button class="btn btn-primary btn-close-modal">CLOSE</button>',
	'id' => 'modal-history'
]);
?>
<div class="update-modal-header row">
    <div class="col-xs-6">VERSION NAME</div>
    <div class="col-xs-6">RELEASE UDPATE</div>
</div>
<?php
$data = array_reverse($data);
foreach ($data as $item) {
	?>
	<div class="update-modal-item row">
	    <div class="col-xs-6">
			<?= $item['version'] ?>
	    </div>
	    <div class="col-xs-6">
			<?= date("j F Y", strtotime($item['release_date'])) ?>
		</div>
	</div>
	<?php
}
Modal::end();
?>
<div class="content-page update">
    <div class="content-page-header"><?= Html::encode($this->title) ?></div>
    <div class="content-page-content update-content container-fluid">
        <div class="row">
            <div class="update-content-left col-md-3">
                <?= Html::img('@web/images/logo-my-connection.png', ['alt' => 'InterActive MyConnection']) ?>
            </div>
            <div class="update-content-right col-md-9">
                <div class="update-orange">
                    Current Version
                </div>
                <div class="update-content-right-version"><?= $currentVersion ?></div>
            </div>
        </div>
        <div class="update-content-status update-orange">Status Update</div>

        <?php
		if (isset($session['dataUpdate'])) {
			$dataUpdate = $session['dataUpdate'];
			$infoUpdate = array_reverse($dataUpdate);
			$latestVersion = end($dataUpdate)['version'];
			?>

			<div class="update-content-desc">A new version of InterActive MyConnection <b>version <?= $latestVersion ?></b> is available</div>

			<div class="update-orange update-content-changelog">
	        	<a href="javascript:;">View update information</a>
	        </div>

	        <button class="update-content-button btn btn-primary start-update">UPDATE NOW</button>

	        <div class="update-process hidden">
	        	<div class="update-process-updating">Updating....</div>
				<?php
				echo Progress::widget([
				    'percent' => 0,
				    'barOptions' => ['class' => 'progress-bar-success'],
			    	'options' => ['class' => 'active progress-striped']
				]);
				?>
			</div>

			<?php
			foreach ($dataUpdate as $key => $data) {
				unset($data['changelog']);
				unset($data['changed_files']);
				$dataUpdate[$key] = $data;
			}

			Modal::begin([
				'header' => '<div>Update Success</div>',
			    'footer' => '<button class="btn btn-primary btn-close-modal">CLOSE</button>',
				'id' => 'modal-notice'
		    ]);
		    echo '<div class="update-data">Your application has been updated to the latest version.</div>';
		    Modal::end();

			Modal::begin([
				'header' => '<div>View update information</div>',
			    'footer' => '<button class="btn btn-primary btn-close-modal">CLOSE</button>',
				'id' => 'modal-changelog'
			]);
			foreach ($infoUpdate as $data) {
			?>
				<div class="update-data">
					<div class="update-data-header">Update version <?= $data['version'] ?></div>
					<div class="update-data-desc"><?= nl2br($data['changelog']) ?></div>
				</div>
			<?php
			}
			Modal::end();
		    ?>

		    

		<?php
		} else {
		?>
			<div class="update-content-desc">Your InterActive MyConnection version is <b>up to date</b></div>
			<button class="update-content-button btn btn-primary disabled">UPDATE NOW</button>
			
		<?php
		}
		?>
        
        <div class="update-orange update-content-history">
        	<a href="javascript:;">Update History</a>
        </div>
    </div>
	
</div>

<?php
if (isset($session['dataUpdate'])) {
?>
	<script type="text/javascript">
		var progress = 0;
		var counter = 0;
		var processing = false;
		var dataUpdate = JSON.parse('<?= json_encode($dataUpdate) ?>');
		var totalData = dataUpdate.length;

		function processUpdate(data) {
			console.log('begin update to version '+data.version);

			$.ajax({
				url: '<?= Url::to(['update/update']); ?>',
				data: {data: data},
				method: 'POST',
				success: function(result) {
					if (result == 'success') {
						progress += 100 / totalData;
					} else {
						console.log(result);
					}
					if (counter == totalData)
						progress = 100;
					$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

					console.log(result);
				},
				complete: function() {
					if (counter < totalData) {
						counter++;
						processUpdate(dataUpdate[counter-1]);
					} else {
						$('#modal-notice').modal('show');
					}
				}
			});
		}

		$('.start-update').click(function() {
			if (!processing) {
				processing = true;
				$('.update-process').removeClass('hidden');
				$('.start-update').addClass('hidden');
				if (counter < totalData) {
					counter++;
					processUpdate(dataUpdate[counter-1]);
				}
			}
		});
	</script>
<?php
}
?>