<?php
require __DIR__ . "/core/session.php";

if (!is_logged_in()) {
    header("Location: ../index.php");
    exit;
}

$baseDir = dirname(__DIR__);
$postsDir = $baseDir . "/posts";
$usersDir = $baseDir . "/users";

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_post'])) {
        $postId = $_POST['post_id'];
        $postType = $_POST['post_type'];

        $postPath = $postType === 'user' ? "$postsDir/user_posts/$postId" : "$postsDir/$postId";

        if (is_dir($postPath)) {
            // Delete all files in the directory
            $files = glob("$postPath/*");
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            // Remove the directory
            rmdir($postPath);
        }

        header("Location: comparisons.php?deleted=1");
        exit;
    }

    if (isset($_POST['toggle_status'])) {
        $postId = $_POST['post_id'];
        $postPath = "$postsDir/user_posts/$postId/data.json";

        if (file_exists($postPath)) {
            $data = json_decode(file_get_contents($postPath), true);
            $data['status'] = !$data['status'];
            file_put_contents($postPath, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        }

        header("Location: comparisons.php?status_updated=1");
        exit;
    }

    if (isset($_POST['update_names'])) {
        $postId = $_POST['post_id'];
        $postType = $_POST['post_type'];
        $name1 = $_POST['name1'];
        $name2 = $_POST['name2'];

        $postPath = $postType === 'user' ? "$postsDir/user_posts/$postId/data.json" : "$postsDir/$postId/data.json";

        if (file_exists($postPath)) {
            $data = json_decode(file_get_contents($postPath), true);
            $data['name1'] = $name1;
            $data['name2'] = $name2;
            file_put_contents($postPath, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        }

        header("Location: comparisons.php?updated=1");
        exit;
    }
}

// Search functionality
$searchQuery = $_GET['search'] ?? '';
$allPosts = [];

// Get admin posts
$adminPosts = glob("$postsDir/*/data.json");
foreach ($adminPosts as $postFile) {
    $postId = basename(dirname($postFile));
    $data = json_decode(file_get_contents($postFile), true);

    if ($data) {
        $data['id'] = $postId;
        $data['type'] = 'admin';
        $data['source'] = 'posts';
        $data['status'] = true; // Admin posts are always active
        $data['user_id'] = null;
        $data['username'] = 'Admin';
        $data['email'] = 'admin@rankly.com';
        $data['displayname'] = 'Rankly';

        $allPosts[] = $data;
    }
}

// Get user posts
$userPostsDir = "$postsDir/user_posts";
if (is_dir($userPostsDir)) {
    $userPosts = glob("$userPostsDir/*/data.json");
    foreach ($userPosts as $postFile) {
        $postId = basename(dirname($postFile));
        $data = json_decode(file_get_contents($postFile), true);

        if ($data) {
            $data['id'] = $postId;
            $data['type'] = 'user';
            $data['source'] = 'user_posts';

            // Get user information
            $userId = $data['user_id'] ?? '';
            $username = 'Unknown';
            $email = 'Unknown';
            $displayname = 'Unknown User';

            if ($userId) {
                $userDataFile = "$usersDir/$userId/data.json";
                if (file_exists($userDataFile)) {
                    $userData = json_decode(file_get_contents($userDataFile), true);
                    $username = $userData['username'] ?? $userId;
                    $email = $userData['email'] ?? 'Unknown';
                    $displayname = $userData['displayname'] ?? $username;
                }
            }

            $data['username'] = $username;
            $data['email'] = $email;
            $data['displayname'] = $displayname;

            $allPosts[] = $data;
        }
    }
}

// Filter by search query
if (!empty($searchQuery)) {
    $searchQuery = strtolower(trim($searchQuery));
    $allPosts = array_filter($allPosts, function ($post) use ($searchQuery) {
        return strpos(strtolower($post['name1'] ?? ''), $searchQuery) !== false ||
            strpos(strtolower($post['name2'] ?? ''), $searchQuery) !== false ||
            strpos(strtolower($post['id'] ?? ''), $searchQuery) !== false ||
            strpos(strtolower($post['username'] ?? ''), $searchQuery) !== false ||
            strpos(strtolower($post['displayname'] ?? ''), $searchQuery) !== false;
    });
}

// Sort by date (newest first)
usort($allPosts, function ($a, $b) {
    return strtotime($b['date'] ?? '') - strtotime($a['date'] ?? '');
});
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/lucide@latest/dist/lucide.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="style.css">
    <title>Admin Dashboard - Comparisons</title>
</head>

<body class="flex">
    <div class="menu flex flex-col h-screen w-min">
        <div class="flex justify-center items-center mt-3">
            <img src="/../images/loading.png" alt="iamge" class="w-20">
        </div>
        <div class="pl-4 mt-5 text-[#00000075] font-medium">
            <a href="dashboard.php" class="flex row items-center"><i data-lucide="house" class="w-5 h-5"></i>Home</a>
            <a href="send_post.php" class="flex row items-center"><i data-lucide="send" class="w-5 h-5"></i>Post</a>
            <a href="comparisons.php" class="flex row items-center"><i data-lucide="search" class="w-5 h-5"></i>Comparisons</a>
            <a href="requests.php" class="flex row items-center"><i data-lucide="list-check" class="w-5 h-5"></i>Requests</a>
        </div>

        <div class="mt-auto pl-4 pb-4">
            <a href="core/logout.php" class="flex row items-center text-[#00000075]"><i data-lucide="octagon-minus" class="w-5 h-5"></i>Log Out</a>
        </div>
    </div>

    <div class="flex-1 flex flex-col h-screen overflow-hidden">
        <div class="bg-white border-b border-gray-200 p-6">
            <h1 class="text-[25px] font-medium text-gray-800">Comparisons Management</h1>
            <p class="text-[#000000]/50 text-[15px] font-normal mt-1">Manage all posts - Admin and User posts</p>

            <form method="get" class="mt-4 max-w-md">
                <div class="flex gap-2">
                    <input type="text" name="search" value="<?= htmlspecialchars($searchQuery) ?>"
                        placeholder="Search by names, ID, or username..."
                        class="flex-1 px-3 py-2 rounded-lg bg-white text-gray-800 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <button type="submit"
                        class="px-5 py-2 bg-black text-[15px] text-white font-normal rounded-md">
                        Search
                    </button>
                    <?php if (!empty($searchQuery)): ?>
                        <a href="comparisons.php"
                            class="px-5 py-2 bg-black text-[15px] text-white font-normal rounded-md">
                            Clear
                        </a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <div class="bg-gray-50 px-6 py-3 border-b border-gray-200">
            <p class="text-gray-600">
                Found <span class="font-semibold"><?= count($allPosts) ?></span> posts
                <?php if (!empty($searchQuery)): ?>
                    for "<?= htmlspecialchars($searchQuery) ?>"
                <?php endif; ?>
            </p>
        </div>

        <div class="flex-1 overflow-y-auto p-6">
            <?php if (empty($allPosts)): ?>
                <div class="text-center py-12">
                    <i data-lucide="inbox" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
                    <p class="text-gray-500 text-lg font-medium">No posts found</p>
                    <p class="text-gray-400 mt-1">
                        <?php if (!empty($searchQuery)): ?>
                            Try a different search term
                        <?php else: ?>
                            No posts available
                        <?php endif; ?>
                    </p>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-2">
                    <?php foreach ($allPosts as $post):
                        $postId = $post['id'];
                        $postType = $post['type'];
                        $isUserPost = $postType === 'user';

                        $imageBasePath = $isUserPost ? "$postsDir/user_posts/$postId" : "$postsDir/$postId";
                        $image1Path = null;
                        $image2Path = null;

                        foreach (['jpg', 'png', 'jpeg'] as $ext) {
                            if (!$image1Path && file_exists("$imageBasePath/image_1.$ext")) {
                                $image1Path = "../posts/" . ($isUserPost ? "user_posts/" : "") . "$postId/image_1.$ext";
                            }
                            if (!$image2Path && file_exists("$imageBasePath/image_2.$ext")) {
                                $image2Path = "../posts/" . ($isUserPost ? "user_posts/" : "") . "$postId/image_2.$ext";
                            }
                        }

                        $votes1 = count($post['votes1'] ?? []);
                        $votes2 = count($post['votes2'] ?? []);
                        $totalComments = count($post['comments'] ?? []);
                        $isActive = $post['status'] ?? true;
                    ?>
                        <div class="bg-gray-50 border border-gray-200 p-6">
                            <div class="flex justify-between items-start mb-4">
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 bg-gradient-to-br from-gray-500 to-gray-600 rounded-full flex items-center justify-center">
                                        <i data-lucide="<?= $isUserPost ? 'user' : 'shield' ?>" class="w-5 h-5 text-white"></i>
                                    </div>
                                    <div>
                                        <div class="flex items-center gap-2">
                                            <span class="font-semibold text-gray-800"><?= htmlspecialchars($post['displayname']) ?></span>
                                            <span class="text-xs px-2 py-1 rounded-full <?= $isUserPost ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800' ?>">
                                                <?= $isUserPost ? 'User Post' : 'Admin Post' ?>
                                            </span>
                                            <?php if ($isUserPost): ?>
                                                <span class="text-xs px-2 py-1 rounded-full <?= $isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                                    <?= $isActive ? 'Active' : 'Inactive' ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($isUserPost): ?>
                                                <form method="post">
                                                    <input type="hidden" name="post_id" value="<?= $postId ?>">
                                                    <button type="submit" name="toggle_status"
                                                        class="flex items-center gap-1 <?= $isActive ? 'bg-yellow-600 hover:bg-yellow-700' : 'bg-green-600 hover:bg-green-700' ?> text-white px-2 py-[1px] rounded text-sm transition">
                                                        <i data-lucide="<?= $isActive ? 'eye-off' : 'eye' ?>" class="w-4 h-4"></i>
                                                        <?= $isActive ? 'Deactivate' : 'Activate' ?>
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                        <p class="text-sm text-gray-600">@<?= htmlspecialchars($post['username']) ?> • <?= htmlspecialchars($post['email']) ?></p>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm text-gray-500"><?= $post['date'] ?></p>
                                    <p class="text-xs text-gray-400">ID: <?= substr($postId, 0, 8) ?>...</p>
                                </div>
                            </div>

                            <div class="grid grid-cols-2 gap-6 mb-4">
                                <div class="text-center">
                                    <div class="bg-gray-50 rounded-lg border border-gray-200 overflow-hidden h-[275px] mb-2">
                                        <?php if ($image1Path): ?>
                                            <img src="<?= $image1Path ?>" class="w-full h-full object-cover" alt="<?= htmlspecialchars($post['name1']) ?>">
                                        <?php else: ?>
                                            <div class="w-full h-full flex items-center justify-center bg-gray-100">
                                                <i data-lucide="image" class="w-8 h-8 text-gray-400"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <p class="font-medium text-gray-800"><?= htmlspecialchars($post['name1']) ?></p>
                                    <p class="text-sm text-gray-600 mt-1">Votes: <?= $votes1 ?></p>
                                </div>

                                <div class="text-center">
                                    <div class="bg-gray-50 rounded-lg border border-gray-200 overflow-hidden h-[275px] mb-2">
                                        <?php if ($image2Path): ?>
                                            <img src="<?= $image2Path ?>" class="w-full h-full object-cover" alt="<?= htmlspecialchars($post['name2']) ?>">
                                        <?php else: ?>
                                            <div class="w-full h-full flex items-center justify-center bg-gray-100">
                                                <i data-lucide="image" class="w-8 h-8 text-gray-400"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <p class="font-medium text-gray-800"><?= htmlspecialchars($post['name2']) ?></p>
                                    <p class="text-sm text-gray-600 mt-1">Votes: <?= $votes2 ?></p>
                                </div>
                            </div>

                            <div class="flex justify-between items-center mb-4 p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center gap-4 text-sm text-gray-600">
                                    <span class="flex items-center gap-1">
                                        <i data-lucide="tag" class="w-4 h-4"></i>
                                        <?= htmlspecialchars($post['category'] ?? 'General') ?>
                                    </span>
                                    <span class="flex items-center gap-1">
                                        <i data-lucide="message-circle" class="w-4 h-4"></i>
                                        <?= $totalComments ?> comments
                                    </span>
                                    <span class="flex items-center gap-1">
                                        <i data-lucide="bar-chart" class="w-4 h-4"></i>
                                        Total votes: <?= $votes1 + $votes2 ?>
                                    </span>
                                </div>
                            </div>

                            <div class="flex gap-2 justify-between items-center pt-4 border-t border-gray-200">
                                <div class="flex gap-2">
                                    <form method="post" class="flex gap-2" onsubmit="return confirm('Are you sure you want to update the names?')">
                                        <input type="hidden" name="post_id" value="<?= $postId ?>">
                                        <input type="hidden" name="post_type" value="<?= $postType ?>">
                                        <input type="text" name="name1" value="<?= htmlspecialchars($post['name1']) ?>"
                                            class="px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none">
                                        <input type="text" name="name2" value="<?= htmlspecialchars($post['name2']) ?>"
                                            class="px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none">
                                        <button type="submit" name="update_names"
                                            class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm transition">
                                            Update Names
                                        </button>
                                    </form>
                                </div>

                                <div class="flex gap-2">
                                    <form method="post" onsubmit="return confirm('Are you sure you want to delete this post? This action cannot be undone.')">
                                        <input type="hidden" name="post_id" value="<?= $postId ?>">
                                        <input type="hidden" name="post_type" value="<?= $postType ?>">
                                        <button type="submit" name="delete_post"
                                            class="flex items-center gap-1 bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm transition">
                                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        lucide.createIcons();

        <?php if (isset($_GET['deleted'])): ?>
            setTimeout(() => alert('Post deleted successfully!'), 100);
        <?php endif; ?>

        <?php if (isset($_GET['status_updated'])): ?>
            setTimeout(() => alert('Post status updated successfully!'), 100);
        <?php endif; ?>

        <?php if (isset($_GET['updated'])): ?>
            setTimeout(() => alert('Post names updated successfully!'), 100);
        <?php endif; ?>
    </script>
</body>

</html>