<?php

$baseDir = __DIR__ . DIRECTORY_SEPARATOR;

$inputPath = isset($_GET['path']) ? $_GET['path'] : '';

$cleanPath = str_replace(['..', '\\', ':'], '', $inputPath);
$cleanPath = trim($cleanPath, '/') . '/';

$imagePath = $baseDir . $cleanPath;


if (!is_dir($imagePath)) {

    $cleanPath = '';
    $imagePath = $baseDir . $cleanPath;
}

function getAllImages($fullPath) {
    $files = glob($fullPath . "*.{jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF}", GLOB_BRACE);
    return $files ? array_map('basename', $files) : [];
}

function serveImage($filename, $fullPath) {
    $filename = basename($filename);
    $targetFile = $fullPath . $filename;
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExtensions) || !file_exists($targetFile)) {
        header("HTTP/1.0 404 Not Found");
        exit("File not found.");
    }

    $mime = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'];
    header("Content-Type: " . ($mime[$ext] ?? 'application/octet-stream'));
    header("Cache-Control: public, max-age=31536000");
    readfile($targetFile);
    exit;
}

if (isset($_GET['img'])) {
    serveImage($_GET['img'], $imagePath);
}

if (isset($_GET['getImages'])) {
    header("Content-Type: application/json");
    echo json_encode(getAllImages($imagePath));
    exit;
}


$timer = isset($_GET['timer']) ? $_GET['timer'] : null;
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Gallery</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
html, body { margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden; }
.image-container { position: relative; height: 100%; width: 100%; overflow: hidden; }
img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); min-width: 100%; min-height: 100%; width: auto; height: auto; object-fit: cover; opacity: 1; }
#timer { position: absolute; top: 20px; right: 20px; color: white; font-size: 96px; z-index: 1000; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
</style>
</head>
<body>
<div class="image-container">
<img src="" id="randomImage">
</div>
<div id="timer"></div>


<script>


const urlParams = new URLSearchParams(window.location.search);
const currentPath = urlParams.get('path') || '';
let showTimer = true; 

const state = { 
    images: [], 
    currentIndex: 0 
};


function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}


async function fetchAndShuffleImages() {
    try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 5000);
        
        const apiUrl = window.location.pathname + '?getImages=true&path=' + encodeURIComponent(currentPath);
        
        const response = await fetch(apiUrl, { 
            signal: controller.signal, 
            cache: 'no-cache' 
        });
        
        clearTimeout(timeoutId);
        
        if (!response.ok) { 
            throw new Error(`HTTP error! status: ${response.status}`); 
        }
        
        const newImages = await response.json();
        
        if (newImages && newImages.length > 0) {
            state.images = shuffleArray(newImages);
            state.currentIndex = 0;
            refreshImage();
        } else {
            console.error('No images found in the directory or path is invalid.');
        }
    } catch (error) {
        if (error.name !== 'AbortError') { 
            console.error('Error loading image.', error); 
        }
    }
}


function getNextImage() {
    if (state.images.length === 0) return '';
    const image = state.images[state.currentIndex];
    state.currentIndex = (state.currentIndex + 1) % state.images.length;
    return image;
}


function refreshImage() {
    const img = document.getElementById('randomImage');
    const nextImgName = getNextImage();
    
    if (!nextImgName) return;


    const newSrc = window.location.pathname + '?img=' + encodeURIComponent(nextImgName) + '&path=' + encodeURIComponent(currentPath);
    
    if (img.src !== newSrc) {
        img.onload = function() {
            const imgRatio = img.naturalWidth / img.naturalHeight;
            const screenRatio = window.innerWidth / window.innerHeight;
            const widthRatio = window.innerWidth / img.naturalWidth;
            const heightRatio = window.innerHeight / img.naturalHeight;
            const zoomFactor = Math.min(widthRatio, heightRatio);
            
            if (imgRatio > screenRatio) {
                img.style.width = `${img.naturalWidth * zoomFactor}px`;
                img.style.height = 'auto';
            } else {
                img.style.width = 'auto';
                img.style.height = `${img.naturalHeight * zoomFactor}px`;
            }
        };
        img.src = newSrc;
    }
}

function getStartTime() {
    const timeParam = "<?php echo $timer; ?>";
    if (timeParam) {
        const cleanTimeParam = timeParam.replace(/[^0-9:]/g, '');
        const match = cleanTimeParam.match(/^([01]\d|2[0-3])[:.]?([0-5]\d)$/);
        if (match) {
            const [, hours, minutes] = match;
            const now = new Date();
            const startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes);
            if (startTime <= now) { startTime.setDate(startTime.getDate() + 1); }
            return startTime;
        }
    }
    return null;
}

function updateTimer() {
    const startTime = getStartTime();
    const timerElement = document.getElementById('timer');

    if (!showTimer) {
        timerElement.style.display = 'none';
        return;
    } else {
        timerElement.style.display = 'block';
    }

    if (startTime) {
        let remainingSeconds = Math.floor((startTime - new Date()) / 1000);
        let timerInterval;

        function tick() {
            if (remainingSeconds <= 0) {
                clearInterval(timerInterval);
                timerElement.textContent = "00:00:00";
                return;
            }
            const hours = Math.floor(remainingSeconds / 3600);
            const minutes = Math.floor((remainingSeconds % 3600) / 60);
            const seconds = remainingSeconds % 60;
            timerElement.textContent =
                `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            remainingSeconds--;
        }

        function correctTime() {
            const actualRemainingSeconds = Math.floor((startTime - new Date()) / 1000);
            if (Math.abs(actualRemainingSeconds - remainingSeconds) > 1) { remainingSeconds = actualRemainingSeconds; }
        }

        timerInterval = setInterval(tick, 1000);
        tick();
        setInterval(correctTime, 60000);
    } else {
        function showCurrentTime() {
            const now = new Date();
            const hours = now.getHours().toString().padStart(2, '0');
            const minutes = now.getMinutes().toString().padStart(2, '0');
            const seconds = now.getSeconds().toString().padStart(2, '0');
            timerElement.textContent = `${hours}:${minutes}:${seconds}`;
        }
        showCurrentTime();
        setInterval(showCurrentTime, 1000);
    }
}


document.addEventListener('DOMContentLoaded', function() {
    fetchAndShuffleImages();
    setInterval(refreshImage, 4000);
    updateTimer();
});


window.addEventListener('resize', refreshImage);

</script>
</body>
</html>
