<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$baseDir = __DIR__ . "/assets";
$currentPath = $baseDir;

if (isset($_GET['path'])) {
    $path = realpath($baseDir . "/" . $_GET['path']);
    if ($path && str_starts_with($path, $baseDir)) {
        $currentPath = $path;
    }
}

function relativePath($fullPath, $baseDir)
{
    return str_replace("\\", "/", substr($fullPath, strlen($baseDir) + 1));
}

function folderStats($path)
{
    $stats = ['size' => 0, 'images' => 0, 'videos' => 0, 'folders' => 0];
    $items = scandir($path);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..')
            continue;
        $full = $path . "/" . $item;
        if (is_dir($full)) {
            $stats['folders']++;
            $subStats = folderStats($full);
            foreach ($subStats as $k => $v)
                $stats[$k] += $v;
        } else {
            $stats['size'] += filesize($full);
            $ext = strtolower(pathinfo($full, PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif']))
                $stats['images']++;
            if (in_array($ext, ['mp4', 'webm', 'ogg']))
                $stats['videos']++;
        }
    }
    return $stats;
}

function deleteRecursive($path)
{
    if (is_dir($path)) {
        $items = scandir($path);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..')
                continue;
            deleteRecursive("$path/$item");
        }
        rmdir($path);
    } else {
        unlink($path);
    }
}

// Bulk delete
if (isset($_POST['bulk_delete']) && isset($_POST['files'])) {
    foreach ($_POST['files'] as $f) {
        $deletePath = realpath($baseDir . "/" . $f);
        if ($deletePath && str_starts_with($deletePath, $baseDir)) {
            deleteRecursive($deletePath);
        }
    }
    header("Location: admin.php?path=" . urlencode(relativePath($currentPath, $baseDir)));
    exit;
}

// Bulk download
if (isset($_POST['bulk_download']) && isset($_POST['files'])) {
    $zip = new ZipArchive();
    $zipName = "download_" . time() . ".zip";
    $zipPath = sys_get_temp_dir() . "/" . $zipName;

    if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
        foreach ($_POST['files'] as $f) {
            $fullPath = realpath($baseDir . "/" . $f);
            if ($fullPath && str_starts_with($fullPath, $baseDir)) {
                if (is_dir($fullPath)) {
                    $files = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($fullPath),
                        RecursiveIteratorIterator::LEAVES_ONLY
                    );
                    foreach ($files as $file) {
                        if (!$file->isDir()) {
                            $filePath = $file->getRealPath();
                            $relative = substr($filePath, strlen($baseDir) + 1);
                            $zip->addFile($filePath, $relative);
                        }
                    }
                } else {
                    $zip->addFile($fullPath, $f);
                }
            }
        }
        $zip->close();

        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipName . '"');
        header('Content-Length: ' . filesize($zipPath));
        readfile($zipPath);
        unlink($zipPath);
        exit;
    }
}

// Delete single file/folder
if (isset($_GET['delete'])) {
    $deletePath = realpath($baseDir . "/" . $_GET['delete']);
    if ($deletePath && str_starts_with($deletePath, $baseDir)) {
        deleteRecursive($deletePath);
        header("Location: admin.php?path=" . urlencode(dirname($_GET['delete'])));
        exit;
    }
}

$stats = folderStats($currentPath);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        .card:hover { transform: translateY(-5px); transition: all 0.2s; }
        .scrollbar { scrollbar-width: thin; scrollbar-color: #a0aec0 transparent; }
        .scrollbar::-webkit-scrollbar { width: 8px; }
        .scrollbar::-webkit-scrollbar-thumb { background-color: #a0aec0; border-radius: 4px; }
    </style>
</head>

<body class="bg-gray-50">
<div class="max-w-7xl mx-auto py-8 px-4">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-3xl font-bold text-gray-800">Media Admin Panel</h1>
        <a href="logout.php" class="bg-black text-white px-5 py-2 rounded-md hover:bg-gray-800 shadow">Logout</a>
    </div>
    <hr><br><hr><br>

    <!-- Folder Navigation -->
    <div class="mb-6 text-gray-700">
        <p class="mb-1 text-sm">Current Folder: <span class="font-semibold"><?= relativePath($currentPath, $baseDir) ?: "/" ?></span></p>
        <?php if ($currentPath !== $baseDir): ?>
            <?php $parent = dirname(relativePath($currentPath, $baseDir)); ?>
            <a href="?path=<?= urlencode($parent) ?>" class="text-blue-600 hover:underline text-sm">⬅ Back</a>
        <?php endif; ?>
    </div>

    <!-- Folder Stats -->
    <div class="mb-6 p-4 bg-white rounded-lg shadow flex flex-wrap gap-4">
        <span class="text-gray-700">Total Size: <strong><?= round($stats['size'] / 1024 / 1024 / 1024, 2) ?> GB</strong></span>
        <span class="text-gray-700">Images: <strong><?= $stats['images'] ?></strong></span>
        <span class="text-gray-700">Videos: <strong><?= $stats['videos'] ?></strong></span>
        <span class="text-gray-700">Subfolders: <strong><?= $stats['folders'] ?></strong></span>
    </div>

    <form method="POST" onsubmit="return confirm('Are you sure you want to perform this action on selected items?')">
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 scrollbar overflow-y-auto max-h-[75vh]">
            <?php
            $files = scandir($currentPath);
            foreach ($files as $file) {
                if ($file === "." || $file === "..") continue;
                $full = $currentPath . "/" . $file;
                $rel = relativePath($full, $baseDir);

                echo "<div class='card bg-white rounded-lg shadow p-4 flex flex-col justify-between'>";
                echo "<div>";
                echo "<input type='checkbox' name='files[]' value='$rel' class='mb-2'>";

                if (is_dir($full)) {
                    $fstats = folderStats($full);
                    echo "<a href='?path=" . urlencode($rel) . "' class='block text-blue-600 hover:underline font-semibold text-lg truncate'>📁 $file</a>";
                    echo "<p class='text-xs text-gray-500 mt-1'>Size: " . round($fstats['size'] / 1024 / 1024 / 1024, 2) . " GB | Images: {$fstats['images']} | Videos: {$fstats['videos']} | Subfolders: {$fstats['folders']}</p>";
                } else {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg','jpeg','png','gif'])) {
                        echo "<img src='assets/$rel' class='rounded w-full max-h-40 object-cover mb-2'>";
                    } elseif (in_array($ext, ['mp4','webm','ogg'])) {
                        echo "<video src='assets/$rel' controls class='rounded w-full max-h-40 mb-2'></video>";
                    } else {
                        echo "<p class='mb-2 truncate'>$file</p>";
                    }
                    echo "<div class='flex justify-between items-center gap-2'>";
                    echo "<a href='assets/$rel' download class='bg-green-600 text-white px-3 py-1 rounded-md hover:bg-green-700 text-sm'>Download</a>";
                    echo "<a href='?delete=" . urlencode($rel) . "&path=" . urlencode(relativePath($currentPath, $baseDir)) . "' onclick='return confirm(\"Delete $file?\")' class='bg-black text-white px-3 py-1 rounded-md hover:bg-gray-800 text-sm'>Delete</a>";
                    echo "</div>";
                    echo "<p class='text-xs text-gray-500 mt-1'>Size: " . round(filesize($full) / 1024 / 1024, 2) . " MB</p>";
                }

                echo "</div>";
                echo "</div>";
            }
            ?>
        </div>

        <div class="mt-6 flex gap-4">
            <button type="submit" name="bulk_delete" class="bg-black text-white px-5 py-2 rounded-md hover:bg-gray-800 shadow">Delete Selected</button>
            <button type="submit" name="bulk_download" class="bg-blue-600 text-white px-5 py-2 rounded-md hover:bg-blue-700 shadow">Download Selected</button>
        </div>
    </form>

    <br><hr><br>
    <div class="flex justify-center items-center">
        <img src="logo.png" style="width: 6em;" alt="Logo">
        <a href="https://www.elegantwork.co.za" target="_blank" class="text-black py-3 rounded-lg font-semibold ml-4 text-1xl" style="font-size: 0.8em;">Developed & hosted by Elegant Work Group (Pty) Ltd</a>
    </div>
</div>
</body>
</html>
