<?php
require __DIR__ . '/config.php';
requireAuth();
cleanupOldFiles(__DIR__ . "/uploads");

// We will use tokens as folder names
global $ALLOWED_UPLOAD_TOKENS;

// Build reverse lookup: employee -> token
$employeeToToken = $ALLOWED_UPLOAD_TOKENS;
$tokenToEmployee = array_flip($ALLOWED_UPLOAD_TOKENS);

$employeeParam = $_GET['employee'] ?? '';
$dateParam = $_GET['date'] ?? date("Y-m-d");
$dashboardMode = isset($_GET['dashboard']);

function getLatestScreenshot($token, $date) {
    $dirPath = __DIR__ . '/uploads/' . $token . '/' . $date;
    if (is_dir($dirPath)) {
        $images = glob($dirPath . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
        rsort($images);
        return $images[0] ?? null;
    }
    return null;
}

// Dashboard mode
if ($dashboardMode) {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Live Dashboard</title>
        <meta http-equiv="refresh" content="<?php echo REFRESH_INTERVAL; ?>">
        <style>
            body { font-family: Arial; margin: 20px; }
            h1 { margin-bottom: 20px; }
            .grid { display: flex; flex-wrap: wrap; gap: 20px; }
            .card { border: 1px solid #ccc; padding: 10px; width: 300px; text-align: center; background: #f9f9f9; }
            .card img { width: 100%; cursor: pointer; }
            .timestamp { font-size: 0.9em; color: #555; margin-top: 5px; }
            .stale { color: red; font-weight: bold; }
        </style>
    </head>
    <body>
        <h1>Live Dashboard (Refreshes every <?php echo REFRESH_INTERVAL; ?>s)</h1>
        <div class="grid">
            <?php foreach ($employeeToToken as $emp => $token): ?>
                <?php $latest = getLatestScreenshot($token, date("Y-m-d")); ?>
                <div class="card">
                    <h3><?php echo htmlspecialchars($emp); ?></h3>
                    <?php if ($latest): ?>
                        <a href="?employee=<?php echo urlencode($emp); ?>">
                            <img src="uploads/<?php echo $token . '/' . date("Y-m-d") . '/' . basename($latest); ?>">
                        </a>
                        <?php 
                            $fileTime = getScreenshotTime($latest);
                            $isStale = (time() - $fileTime) > (REFRESH_INTERVAL * 3);
                        ?>
                        <div class="timestamp <?php echo $isStale ? 'stale' : ''; ?>">
                            <?php echo date("Y-m-d H:i:s", $fileTime); ?>
                        </div>
                    <?php else: ?>
                        <p>No screenshot today</p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Single employee mode
$images = [];
$latestImage = null;

if ($employeeParam && isset($employeeToToken[$employeeParam])) {
    $token = $employeeToToken[$employeeParam];
    $dirPath = __DIR__ . '/uploads/' . $token . '/' . $dateParam;

    if (is_dir($dirPath)) {
        $images = glob($dirPath . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
        rsort($images);
        if (!empty($images)) {
            $latestImage = $images[0];
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Screenshot Viewer</title>
    <?php if ($employeeParam): ?>
        <meta http-equiv="refresh" content="<?php echo REFRESH_INTERVAL; ?>">
    <?php endif; ?>
    <style>
        body { font-family: Arial; margin: 20px; }
        .employee-list { margin-bottom: 20px; }
        .employee-list a { margin-right: 10px; text-decoration: none; color: blue; }
        .latest { margin-bottom: 30px; }
        .latest img { width: 400px; border: 2px solid green; cursor: pointer; }
        .gallery{display:flex;flex-wrap:wrap;gap:10px}
        .gallery>div{display:flex;flex-direction:column;align-items:center;margin:5px}
        .gallery img{width:200px;border:1px solid #ccc;cursor:pointer;border-radius:4px}
        .timestamp{font-size:.85em;color:#555;margin-top:4px;text-align:center}
        .stale{color:red;font-weight:700}
        .modal{ display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.9); justify-content:center; align-items:center; z-index:9999}
        .modal img{ width:auto; height:auto; max-width:90%; max-height:90%; border:3px solid #fff; box-shadow:0 0 20px rgba(255,255,255,.5)}
        .nav-btn{ position:absolute; top:50%; transform:translateY(-50%); background:rgba(255,255,255,.3); border:none; color:#fff; font-size:40px; padding:10px; cursor:pointer; z-index:10000; border-radius:5px}
        .nav-btn:hover{ background:rgba(255,255,255,.6)}
        .nav-btn.left{ left:20px}
        .nav-btn.right{right:20px}
        form { margin-bottom: 20px; }
    </style>
</head>
<body>
    <h1>Screenshot Viewer</h1>
    <p><a href="?dashboard=1">View Live Dashboard</a></p>

    <!-- Employee list -->
    <div class="employee-list">
        <strong>Select Employee:</strong>
        <?php foreach ($employeeToToken as $emp => $tok): ?>
            <a href="?employee=<?php echo urlencode($emp); ?>"><?php echo htmlspecialchars($emp); ?></a>
        <?php endforeach; ?>
    </div>

    <!-- Date filter -->
    <?php if ($employeeParam): ?>
        <form method="get">
            <input type="hidden" name="employee" value="<?php echo htmlspecialchars($employeeParam); ?>">
            <label for="date">Select Date:</label>
            <input type="date" name="date" value="<?php echo htmlspecialchars($dateParam); ?>">
            <button type="submit">View</button>
        </form>
    <?php endif; ?>

    <!-- Latest Screenshot -->
    <?php if ($latestImage): ?>
        <?php 
            $fileTime = getScreenshotTime($latestImage);
            $isStale = (time() - $fileTime) > (REFRESH_INTERVAL * 3);
        ?>
        <div class="latest">
            <h2>Latest Screenshot (<?php echo htmlspecialchars($dateParam); ?>)</h2>
            <img src="uploads/<?php echo $employeeToToken[$employeeParam] . '/' . $dateParam . '/' . basename($latestImage); ?>"
                 onclick="openModal(this.src, 0)">
            <div class="timestamp <?php echo $isStale ? 'stale' : ''; ?>">
                <?php echo date("Y-m-d H:i:s", $fileTime); ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- All Screenshots -->
    <?php if (!empty($images)): ?>
        <h3>All Screenshots</h3>
        <div class="gallery">
            <?php foreach ($images as $i => $img): ?>
                <?php 
                    $fileTime = getScreenshotTime($img);
                    $isStale = (time() - $fileTime) > (REFRESH_INTERVAL * 3);
                ?>
                <div>
                    <img src="uploads/<?php echo $employeeToToken[$employeeParam] . '/' . $dateParam . '/' . basename($img); ?>" 
                         onclick="openModal(this.src, <?php echo $i; ?>)">
                    <div class="timestamp <?php echo $isStale ? 'stale' : ''; ?>">
                        <?php echo date("Y-m-d H:i:s", $fileTime); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php elseif ($employeeParam): ?>
        <p>No screenshots found for <?php echo htmlspecialchars($employeeParam); ?> on <?php echo htmlspecialchars($dateParam); ?>.</p>
    <?php endif; ?>

    <!-- Modal -->
    <div class="modal" id="modal" onclick="closeModal()">
        <button class="nav-btn left" onclick="event.stopPropagation(); showImage(currentIndex - 1)">&#10094;</button>
        <img id="modal-img" onclick="event.stopPropagation()">
        <button class="nav-btn right" onclick="event.stopPropagation(); showImage(currentIndex + 1)">&#10095;</button>
    </div>

    <script>
        let currentIndex = 0;
        let galleryImages = [];

        function openModal(src, index) {
            let thumbs = document.querySelectorAll(".gallery img");
            galleryImages = Array.from(thumbs).map(img => img.src);

            let latest = document.querySelector(".latest img");
            if (latest && !galleryImages.includes(latest.src)) {
                galleryImages.unshift(latest.src);
            }

            currentIndex = index;
            document.getElementById("modal-img").src = src + '?t=' + new Date().getTime();
            document.getElementById("modal").style.display = "flex";
        }

        function closeModal() {
            document.getElementById("modal").style.display = "none";
        }

        function showImage(index) {
            if (index >= 0 && index < galleryImages.length) {
                currentIndex = index;
                document.getElementById("modal-img").src = galleryImages[currentIndex] + '?t=' + new Date().getTime();
            }
        }

        document.addEventListener("keydown", function(e) {
            if (document.getElementById("modal").style.display === "flex") {
                if (e.key === "ArrowRight") {
                    showImage(currentIndex + 1);
                } else if (e.key === "ArrowLeft") {
                    showImage(currentIndex - 1);
                } else if (e.key === "Escape") {
                    closeModal();
                }
            }
        });
    </script>
</body>
</html>
