<?php 

/*-----------------------------------------------------------------------------------*/
# PWA
/*-----------------------------------------------------------------------------------*/
add_action('csf_kanews_options_save_after', function ($data) {

	$data = json_decode(json_encode($data, true), true);

	if( ! $data['pwa-status'] )
	return;

	$response = [
		'name' 				     => $data['pwa-name'] ? $data['pwa-name'] : KAN_THEME_NAME,
		'short_name'  		 => $data['pwa-short-name'] ? $data['pwa-short-name'] : KAN_THEME_NAME,
		'description'  		 => $data['pwa-description'] ?? $data['pwa-description'],
		'background_color' => $data['pwa-bg-color'] ? $data['pwa-bg-color'] : '#e50914',
		'theme_color'			 => $data['pwa-theme-color'] ? $data['pwa-theme-color'] : '#e50914',
		'display' 			   => $data['pwa-display'] ? $data['pwa-display'] : 'fullscreen',
		'orientation' 		 => 'portrait',
		'start_url'  			 => $data['pwa-starturl'] ? $data['pwa-starturl'] : home_url( '/?utm_source=homescreen&utm_medium=shortcut'),
		'scope'   				 => home_url( '/'),
	];

	$icons = [
		'pwa-icon-48',
		'pwa-icon-72',
		'pwa-icon-96',
		'pwa-icon-128',
		'pwa-icon-192',
		'pwa-icon-512',
	];

	foreach ( $icons as $icon ) {
		$size = explode('-', $icon)[2];
		$icon = $data[$icon];
		if(!empty($icon)) {
			$response['icons'][] = [
				'src'   => $icon,
				'sizes' => $size.'x'.$size,
				'type'  => 'image/png'
			];
		}
	}

	if($data['pwa-shortcut']) {
		$response['shortcuts'] = array();
		$shortcuts = $data['pwa-shortcuts'];
		if(is_array($shortcuts) && ! empty( $shortcuts )) {
			foreach( $shortcuts as $shortcut ) {
				if(!empty($shortcut['icon']) && !empty($shortcut['title']) && !empty($shortcut['url'])) {
					// preg_match("/[^\/]+$/", $shortcut['url'], $matches);
					$response['shortcuts'][] = [
						'name' => $shortcut['title'] ? $shortcut['title'] : 'Kanews',
						'url' => $shortcut['url'].'?utm_source=jumplist&utm_medium=shortcut',
						'icons' => [
							[
								'src'   => $shortcut['icon'],
								'type'  => 'image/png',
								'sizes' => '192x192'
							]
						]
					];
				}
			}
		}
	}

	if($data['pwa-screenshot']) {
		$response['screenshots'] = array();
		$screenshots = $data['pwa-screenshots'];
		if(is_array($screenshots) && ! empty( $screenshots )) {
			foreach( $screenshots as $screenshot ) {
				if(!empty($screenshot['image']) && !empty($screenshot['size'])) {
					$response['screenshots'][] = [
						'src'   => $screenshot['image'],
						'sizes' => $screenshot['size'],
						'type'  => 'image/png'
					];
				}
			}
		}
	}

	$responseData = json_encode($response, JSON_PRETTY_PRINT);

	file_put_contents(ABSPATH.'/manifest.json', $responseData);

	ob_start(); ?>
	/**
	 * Auto-generated by Kanews Wordpress Theme.
	 */

	'use strict';

	const cacheName = '<?php echo parse_url( home_url('/'), PHP_URL_HOST ) . '-kanews-' . KAN_THEME_VER; ?>'
	const startPage = '<?php echo home_url( '/' ); ?>';
	const offlinePage = '<?php echo home_url( '/' ); ?>';
	const filesToCache = [startPage, offlinePage];
	const neverCacheUrls = [/\/wp-admin/,/\/wp-login/,/preview=true/];

	// Install
	self.addEventListener('install', function(e) {
		console.log('Kanews service worker installation');
		e.waitUntil(
			caches.open(cacheName).then(function(cache) {
				console.log('Kanews service worker caching dependencies');
				filesToCache.map(function(url) {
					return cache.add(url).catch(function (reason) {
						return console.log('Kanews: ' + String(reason) + ' ' + url);
					});
				});
			})
		);
	});

	// Activate
	self.addEventListener('activate', function(e) {
		console.log('Kanews service worker activation');
		e.waitUntil(
			caches.keys().then(function(keyList) {
				return Promise.all(keyList.map(function(key) {
					if ( key !== cacheName ) {
						console.log('Kanews old cache removed', key);
						return caches.delete(key);
					}
				}));
			})
		);
		return self.clients.claim();
	});

	// Fetch
	self.addEventListener('fetch', function(e) {
		
		// Return if the current request url is in the never cache list
		if ( ! neverCacheUrls.every(checkNeverCacheList, e.request.url) ) {
			console.log( 'Kanews: Current request is excluded from cache.' );
			return;
		}
		
		// Return if request url protocal isn't http or https
		if ( ! e.request.url.match(/^(http|https):\/\//i) )
			return;
		
		// Return if request url is from an external domain.
		if ( new URL(e.request.url).origin !== location.origin )
			return;
		
		// For POST requests, do not use the cache. Serve offline page if offline.
		if ( e.request.method !== 'GET' ) {
			e.respondWith(
				fetch(e.request).catch( function() {
					return caches.match(offlinePage);
				})
			);
			return;
		}
		
		// Revving strategy
		if ( e.request.mode === 'navigate' && navigator.onLine ) {
			e.respondWith(
				fetch(e.request).then(function(response) {
					return caches.open(cacheName).then(function(cache) {
						cache.put(e.request, response.clone());
						return response;
					});  
				})
			);
			return;
		}

		e.respondWith(
			caches.match(e.request).then(function(response) {
				return response || fetch(e.request).then(function(response) {
					return caches.open(cacheName).then(function(cache) {
						cache.put(e.request, response.clone());
						return response;
					});  
				});
			}).catch(function() {
				return caches.match(offlinePage);
			})
		);
	});

	// Check if current url is in the neverCacheUrls list
	function checkNeverCacheList(url) {
		if ( this.match(url) ) {
			return false;
		}
		return true;
	}
	<?php $jsData = ob_get_clean();

	file_put_contents(ABSPATH.'/service-worker.js', $jsData);

}, 10, 1);

function kanews_pwa_sources() {

	if( ! kanews_get_option('pwa-status') )
	return;

	echo '<link rel="manifest" href="'.home_url('/').'/manifest.json">';
	echo '<link rel="prefetch" href="'.home_url('/').'/manifest.json">';

	echo '<meta name="apple-mobile-web-app-statubar" content="'.kanews_get_option('pwa-theme-color', '#e50914').'">';

	$icons = [
		'pwa-icon-96',
		'pwa-icon-128',
		'pwa-icon-192',
		'pwa-icon-512',
		'pwa-icon-48',
		'pwa-icon-72',
	];

	foreach ( $icons as $icon ) {
		$icon = kanews_get_option($icon);
		if(!empty($icon)) {
			echo '<link rel="apple-touch-icon" href="'.$icon.'">';
			break;
		}
	}
	
	ob_start(); ?>
	<script>
		if ('serviceWorker' in navigator) {
			window.addEventListener('load', function () {
				navigator.serviceWorker.register('<?php echo home_url('/'); ?>service-worker.js').then(function (registration) {
						console.log('ServiceWorker registration successful with scope: ', registration.scope);
				}, function (err) {
						console.log('ServiceWorker registration failed: ', err);
				});
			});
		}
	</script>
	<?php $jsData = ob_get_clean();
	echo kan_minify_js($jsData);
}
add_action( 'wp_head', 'kanews_pwa_sources' );

add_action('kanews_footer', function () {
	if( ! kanews_get_option('pwa-status') || ! kanews_get_option('pwa-btn') )
	return;

	$delay = kanews_get_option('pwa-popup-delay', 2);
	$expired = kanews_get_option('pwa-popup-expired', 1);
	?>
<div id="kanews-install-app" data-delay="<?php echo $delay*1000; ?>" data-expired="<?php echo $expired; ?>"  class="kanews-modal kanews-modal-popup align-items-center">
		<div data-toggle="kanews-install-app" class="kanews-modal-close"></div>
		<div class="kanews-modal-content">
			<div class="kanews-modal-title"><?php esc_html_e( 'Uygulamayı Yükle', 'kanews' ); ?></div>
			<div data-toggle="kanews-modal-popup" class="kanews-modal-close-btn"><i class="icon-close"></i></div>
			<div class="kanews-modal-content-inner">
				<p><?php echo kanews_translate('pwa-install-app-text', esc_html__( 'Uygulamamızı yükleyerek içeriklerimize daha hızlı ve kolay erişim sağlayabilirsiniz.', 'kanews' )); ?></p>
				<div class="kanews-btn-group">
					
					<button id="install-app" class="kanews-btn"><?php esc_html_e( 'Uygulamayı Yükle', 'kanews' ); ?></button>
					<button data-toggle="kanews-install-app" class="kanews-btn bg-dark"><?php esc_html_e( 'Devam Et', 'kanews' ); ?></button>
				</div>
			</div>
		</div>
	</div>
	<?php
});