<?php

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$domain = $_SERVER['HTTP_HOST'] ?? 'localhost';
$baseUrl = $protocol . '://' . $domain;

$pro_id = $_GET['id'] ?? '';
$xysection = $_GET['xy'] ?? '';
$storysection = $_GET['storytext'] ?? '';

// Back URL first — used by early exits when id/data is missing.
$refURL = $_SERVER['HTTP_REFERER'] ?? '';
if (!$refURL) {
	// Direct links have no referer — go to site homepage (not /dagworld, which 404s on production).
	$backUrl = rtrim($baseUrl, '/') . '/';
} else {
	if ($xysection !== '' && $xysection !== '0') {
		$backUrl = $refURL . '?#online-story-' . $xysection;
	} else {
		$backUrl = $refURL . '?#artfocus';
	}
}

if ($pro_id === '' || !is_numeric($pro_id) || (int)$pro_id <= 0) {
	http_response_code(404);
	echo '<script>window.location.href=' . json_encode($backUrl) . ';</script>';
	exit;
}

$xysection = ($xysection === '' || !is_numeric($xysection)) ? 0 : (int)$xysection;
$storysection = ($storysection === '' || !is_numeric($storysection)) ? 0 : (int)$storysection;
$pro_id = (int)$pro_id;

if ($baseUrl === 'https://bit.dagworld.com') {
	$ch = curl_init('http://127.0.0.1/dagworld/index.php/rest/V1/storypage/' . $pro_id . '/' . $storysection . '/' . $storysection);
} else {
	$ch = curl_init($baseUrl . '/rest/V1/storypage/' . $pro_id . '/' . $xysection . '/' . $storysection);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);
curl_close($ch);

$result = is_string($result) ? json_decode($result, true) : null;
if (!is_array($result) || empty($result['data']) || !is_array($result['data'])) {
	echo '<script>window.location.href=' . json_encode($backUrl) . ';</script>';
	exit;
}

$storyData = $result['data'];
$artStoryText = is_array($storyData['art_storytext'] ?? null) ? $storyData['art_storytext'] : [];
$artXyCoords = is_array($storyData['art_xycoords'] ?? null) ? $storyData['art_xycoords'] : [];

$storytext = [];
$author = [];
foreach ($artStoryText as $row) {
	if (!is_array($row)) {
		continue;
	}
	$storytext[] = (string)($row['storytext'] ?? '');
	$author[] = (string)($row['storytextauthor'] ?? '');
}
if ($storytext === []) {
	$storytext[] = '';
}
if ($author === []) {
	$author[] = '';
}

$xcoords = [];
$ycoords = [];
foreach ($artXyCoords as $row) {
	if (!is_array($row)) {
		continue;
	}
	$xcoords[] = (string)($row['xcoord'] ?? '0');
	$ycoords[] = (string)($row['ycoord'] ?? '0');
}
array_unshift($xcoords, '0');
array_unshift($ycoords, '0');

$artTextOne = (string)($storyData['art_textOne'] ?? '');
$artArtistName = (string)($storyData['art_artistName'] ?? '');
$artName = (string)($storyData['art_Name'] ?? '');
$artMedium = (string)($storyData['art_Medium'] ?? '');
$artSize = (string)($storyData['art_Size'] ?? '');
$artImage = (string)($storyData['image'] ?? '');

?>

<!doctype html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>DAG World</title>
	
	<link rel="stylesheet" type="text/css" href="css/dag-owl-wow-bootstrap-photoswipe.css" />
	<link rel="stylesheet" type="text/css" href="css/dag-06-01-22-1.css" />
	<link rel="stylesheet" type="text/css" href="css/dag-picStory.css" />
</head>
<body>
    <div class="container-fluid darkBackground picStory-mainCont p-0">
		<div class="row pictureStoryInfo-mainCont m-0">
		    <div class="col-4 startCont">
			    <table style="width:100%;height:100%;"><tr><td class="align-middle" style="width:100%;height:100%;">
				    <button class="link1" onclick="allClear()">Back to start</button>
				</td></tr></table>
			</div>
		    <div class="col-4">
			    <table style="width:100%;height:100%;"><tr><td class="align-middle" style="width:100%;height:100%;">
				    <div class="progress-bar-mainCont">
					    <div id="progressBar" class="progressBar"></div>
					</div>
				</td></tr></table>
			</div>
		    <div class="col-4 closeCont justify-content-end">
			    <a href="<?php echo $backUrl; ?>" class="link1">Close</a>
			</div>
		</div>
        <div class="pictureStoryFlex">
    	    <div class="col-md-4 pictureStoryTextPart" class="col-md-4 pictureStoryTextPart">
    		    <div class="row1">
    			    <table style="width:100%;height:100%;"><tr><td class="align-middle" style="width:100%;height:100%;">
    				    <p id="heading" class="heading2 mb-0"><?php echo $artTextOne; ?></p>
    					<p id="artist" class="text1 goldenColor marginBtm_50"><?php echo $artArtistName; ?></p>
    					<p id="description" class="text1 text-white"><?php echo $storytext[0]; ?></p>
						<p id="author" class="text1 goldenColor marginTop_16 ">
							<?php if ($author[0] !== '') { ?>
								Written By <?php echo $author[0]; ?>
							<?php } ?>
						</p>
    				</tr></td></table>
    			</div>
    			<div class="row2 text-white">
    			    <table style="width:100%;height:100%;"><tr><td class="align-bottom" style="width:100%;height:100%;">
    				    <p class="text1 bold mb-0"><?php echo $artArtistName; ?></p>
    					<p class="text1 italic mb-0"><?php echo $artName; ?></p>
    					<p class="text1 mb-0"><?php echo $artMedium; ?></p>
    					<p class="text1"><?php echo $artSize; ?></p>
    				</tr></td></table>
    			</div>
    		</div>
    	    <div class="col-md-8 p-0 pictureStoryImgPart">
    		    <div id="pictureStoryImgBox" class="pictureStoryImgBox" style="background-image:url('<?php echo $artImage; ?>');">
				    <img class="pictureStoryImg" src="<?php echo $artImage; ?>" />

					<?php $i = 1;
					foreach ($artXyCoords as $xycoords) {
						if (!is_array($xycoords)) {
							continue;
						}
						$dotX = (string)($xycoords['xcoord'] ?? '0');
						$dotY = (string)($xycoords['ycoord'] ?? '0');
					?>
						<button id="dot<?php echo $i; ?>" class="btn focusBtn" onclick="polkadot('<?php echo $dotX; ?>','<?php echo $dotY; ?>','<?php echo $i; ?>')" style="top:<?php echo $dotY; ?>%;left:<?php echo $dotX; ?>%;"></button>
					<?php
						$i++;
					} ?>

				</div>
				<button id="clearBtn" class="clearBtn" onclick="allClear()"><i class="fas fa-times-circle"></i></button>
    		</div>
    	</div>
    	<button id="prevBtn" class="btn picStory-prev" onclick="previous()"></button>
    	<button id="nextBtn" class="btn picStory-next" onclick="next()"></button>

		<div id="dotInfoBtn" class="navPart dotInfoBtn">
		    <p class="text1 text1Heading blackColor mb-0">Click on the points to navigate throughout the story</p>
		</div>
		<div id="prevInfoBtn" class="navPart prevInfoBtn">
		    <p class="text1 text1Heading blackColor mb-0">Use the left button to view the previous point</p>
		</div>
		<div id="nextInfoBtn" class="navPart nextInfoBtn">
		    <p class="text1 text1Heading blackColor mb-0">Use the right button to view the next point</p>
		</div>

    </div>
	
	<script type="text/javascript" src="js/dag-jQuery-bootstrap-wow-owl.js"></script>
	<script type="text/javascript" src="js/mousewheel.js"></script>
	<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
	
	<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
	
<script>
    var pictureStoryImgPart = $(".pictureStoryImgPart");
    var pictureStoryImgBox = $(".pictureStoryImgBox");
	var widthGapPercent = 0;
	var heightGapPercent = 0;
	var highlightedNo = 0;
	
	const xCoords = <?php echo json_encode($xcoords); ?>;
	const yCoords = <?php echo json_encode($ycoords); ?>;
	const descriptions = <?php echo json_encode($storytext); ?>;
	const storyAuthor = <?php echo json_encode($author); ?>;
	
	$(document).ready(function () {
		document.getElementById("prevBtn").disabled = true;
		
		$('img').load(function(){
			var widthGap = (pictureStoryImgPart.innerWidth() - pictureStoryImgBox.innerWidth()) / 2;
		    widthGapPercent = (widthGap * 100) / pictureStoryImgPart.innerWidth();
		    
		    var heightGap = (pictureStoryImgPart.innerHeight() - pictureStoryImgBox.innerHeight()) / 2;
		    heightGapPercent = (heightGap * 100) / pictureStoryImgPart.innerHeight();
		    
		    setTimeout(function () {
		    	document.getElementById("dotInfoBtn").style.display = "flex";
		    }, 300);
		    setTimeout(function () {
		    	document.getElementById("dotInfoBtn").style.display = "none";
		    }, 2800);
		    setTimeout(function () {
		    	document.getElementById("nextInfoBtn").style.display = "flex";
		    }, 3100);
		    setTimeout(function () {
		    	document.getElementById("nextInfoBtn").style.display = "none";
		    }, 4900);
		    setTimeout(function () {
		    	document.getElementById("prevInfoBtn").style.display = "flex";
		    }, 5200);
		    setTimeout(function () {
		    	document.getElementById("prevInfoBtn").style.display = "none";
		    }, 7000);
		});
	});
	
    var Zoomed = "No";
	var polkadotStatus = "Open";
	var pictureStoryImgBox1 = document.getElementById("pictureStoryImgBox");
	var progressBar1 = document.getElementById("progressBar");
	var heading1 = document.getElementById("heading");
	var artist1 = document.getElementById("artist");
	var description1 = document.getElementById("description");
	var author1 = document.getElementById("author");
	var clearBtn1 = document.getElementById("clearBtn");
	var activeBtnNum = 0;
	
	function polkadot(x,y,z){
		if(hasClass(pictureStoryImgBox1, "zoomIn")){
			
		}else{
			activeBtnNum = z;
		}
		
		if(activeBtnNum == z){
		    var btnId = "dot"+z.toString();
		    if(polkadotStatus == "Open"){
		        highlightedNo = z;
		        document.getElementById(btnId).classList.add("active");
		        
		        if(Zoomed != "Yes"){
		    	    if(hasClass(pictureStoryImgBox1, "zoomOut")){
		            	removeClass(pictureStoryImgBox1, "zoomOut");
		            }
		            origin(x, y);
		            addClass(pictureStoryImgBox1, "zoomIn");
		            Zoomed = "Yes";
		    	    polkadotStatus = "Closed";
		    	}
		    	else{
		    		if(hasClass(pictureStoryImgBox1, "zoomIn")){
		            	removeClass(pictureStoryImgBox1, "zoomIn");
		            }
		            origin(x, y);
		            addClass(pictureStoryImgBox1, "zoomOut");
		    		setTimeout(function () {
		    			removeClass(pictureStoryImgBox1, "zoomOut");
		    			pictureStoryImgBox1.style.transition = "none";
		    		}, 1500);
		            Zoomed = "No";
		    	    polkadotStatus = "Open";
		    		highlightedNo = 0;
		    	}
		    }
		    else{
		    	highlightedNo = 0;
		    	document.getElementById(btnId).classList.remove("active");
		    	
		    	removeClass(pictureStoryImgBox1, "zoomIn");
		    	pictureStoryImgBox1.style.transition = "none";
		    	addClass(pictureStoryImgBox1, "zoomOut");
		    	setTimeout(function () {
		    		removeClass(pictureStoryImgBox1, "zoomOut");
		        }, 1500);
		    	Zoomed = "No";
		    	polkadotStatus = "Open";
		    }
		}
		else{
			removeActivePolkadots();
			highlightedNo = z;
			showActiveDot(highlightedNo);
			pictureStoryImgBox1.style.transition = "all 3s";
			origin(xCoords[highlightedNo], yCoords[highlightedNo]);
		}

		if(highlightedNo == 0){
			document.getElementById("prevBtn").disabled = true;
		}
		else{
			document.getElementById("prevBtn").disabled = false;
		}
		if(highlightedNo == (xCoords.length - 1)){
			document.getElementById("nextBtn").disabled = true;
		}
		else{
			document.getElementById("nextBtn").disabled = false;
		}
		
		updateDescription(highlightedNo);
		updateProgressBar(highlightedNo);
	}
	
	function previous(){
		removeActivePolkadots();
		highlightedNo--;
		if(highlightedNo > 0){
		    showActiveDot(highlightedNo);
			if(Zoomed == "Yes"){
		    	pictureStoryImgBox1.style.transition = "all 3s";
				origin(xCoords[highlightedNo], yCoords[highlightedNo]);
		    }else{
		    	origin(xCoords[highlightedNo], yCoords[highlightedNo]);
		    	addClass(pictureStoryImgBox1, "zoomIn");
		    	Zoomed = "Yes";
		    }
		}
		
		if(highlightedNo == 0){
			Zoomed = "No";
			document.getElementById("prevBtn").disabled = true;
			removeClass(pictureStoryImgBox1, "zoomIn");
			pictureStoryImgBox1.style.transition = "none";
			addClass(pictureStoryImgBox1, "zoomOut");
			setTimeout(function () {
				removeClass(pictureStoryImgBox1, "zoomOut");
		    }, 1500);
			polkadotStatus = "Open";
		}else{
			document.getElementById("nextBtn").disabled = false;
		}
		
		updateDescription(highlightedNo);
		updateProgressBar(highlightedNo);
		document.getElementById("pictureStoryTextPart").scrollTop = -10;
	}
	function next(){
		removeActivePolkadots();
		highlightedNo++;
		showActiveDot(highlightedNo);
		if(Zoomed == "Yes"){
			pictureStoryImgBox1.style.transition = "all 3s";
			origin(xCoords[highlightedNo], yCoords[highlightedNo]);
		}else{
			origin(xCoords[highlightedNo], yCoords[highlightedNo]);
			addClass(pictureStoryImgBox1, "zoomIn");
			Zoomed = "Yes";
		}
		
		if(highlightedNo == (xCoords.length - 1)){
			document.getElementById("nextBtn").disabled = true;
		}else{
			document.getElementById("prevBtn").disabled = false;
		}
		
		updateDescription(highlightedNo);
		updateProgressBar(highlightedNo);

		document.getElementById("pictureStoryTextPart").scrollTop = -10;
	}
	
	function origin(xOrigin,yOrigin){
		if(widthGapPercent > 0){
		    if(xOrigin <= (widthGapPercent * 1.5)){
		    	xOrigin = widthGapPercent * 1.5;
		    }
		    else if(xOrigin >= (100 - (widthGapPercent * 1.5))){
		    	xOrigin = 100 - (widthGapPercent * 1.5);
		    }
		    else{}
		}
		else{
			if(xOrigin <= 10){
		    	xOrigin = 0;
		    }
		    else if(xOrigin >= 90){
		    	xOrigin = 100;
		    }
		    else{}
		}
		
		if(heightGapPercent > 0){
			if(yOrigin <= (heightGapPercent * 1.5)){
		    	yOrigin = heightGapPercent * 1.5;
		    }
		    else if(yOrigin >= (100 - (heightGapPercent * 1.5))){
		    	yOrigin = 100 - (heightGapPercent * 1.5);
		    }
		    else{}
		}
		else{
			if(yOrigin <= 10){
		    	yOrigin = 0;
		    }
		    else if(yOrigin >= 90){
		    	yOrigin = 100;
		    }
		    else{}
		}
		pictureStoryImgBox1.style.transformOrigin = xOrigin+"% "+yOrigin+"%";
	}
	
	function updateDescription(pointNo){
		if(pointNo != 0){
			heading1.style.display = "none";
			artist1.style.display = "none";
			clearBtn1.style.display = "block";
		}else{
			heading1.style.display = "block";
			artist1.style.display = "block";
			clearBtn1.style.display = "none";
		}
		description1.innerHTML = descriptions[pointNo];
		if(storyAuthor[pointNo]) {
			author1.innerHTML = "Written By "+storyAuthor[pointNo];
		} else{
			author1.innerHTML = '';
		}
		activeBtnNum = pointNo;
	}
	
	function removeActivePolkadots(){
		for(var i = 1; i < xCoords.length; i++){
			var btnId = "dot"+i.toString();
			document.getElementById(btnId).classList.remove("active");
		}
	}
	
	function showActiveDot(i){
		var btnId = "dot"+i.toString();
		document.getElementById(btnId).classList.add("active");
	}
	
	function updateProgressBar(pointNo){
		var avgProgress = 100 / (xCoords.length - 1);
		var currentProgress = avgProgress * pointNo;
		currentProgress = currentProgress+"%";
		progressBar1.style.width = currentProgress;
	}
	
	function allClear(){
		if(hasClass(pictureStoryImgBox1, "zoomIn")){
			removeClass(pictureStoryImgBox1, "zoomIn");
		
		    pictureStoryImgBox1.style.transition = "none";
		    removeActivePolkadots();
			
		    addClass(pictureStoryImgBox1, "zoomOut");
		    setTimeout(function () {
		    	removeClass(pictureStoryImgBox1, "zoomOut");
		    }, 1500);
		}
		
		highlightedNo = 0;
		Zoomed = "No";
		polkadotStatus = "Open";
		updateProgressBar(highlightedNo);
		updateDescription(highlightedNo);
		document.getElementById("prevBtn").disabled = true;
		document.getElementById("nextBtn").disabled = false;
	}
	
    function hasClass(el, className)
    {
        if (el.classList)
            return el.classList.contains(className);
        return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
    }
    function addClass(el, className)
    {
        if (el.classList)
            el.classList.add(className)
        else if (!hasClass(el, className))
            el.className += " " + className;
    }
    function removeClass(el, className)
    {
        if (el.classList)
            el.classList.remove(className)
        else if (hasClass(el, className))
        {
            var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
            el.className = el.className.replace(reg, ' ');
        }
    }
</script>
</body>