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

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

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

$searchResults = [];
$searchQuery = '';

if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
    $searchQuery = trim($_GET['search']);
    $searchResults = searchPosts($searchQuery, $postsDir, $usersDir);
}

function searchPosts($query, $postsDir, $usersDir)
{
    $results = [];

    $adminPosts = glob($postsDir . '/*/data.json');
    foreach ($adminPosts as $postFile) {
        $postData = json_decode(file_get_contents($postFile), true);
        if ($postData && postMatchesSearch($postData, $query)) {
            $postId = basename(dirname($postFile));
            $results[] = [
                'type' => 'admin',
                'post_id' => $postId,
                'name1' => $postData['name1'] ?? '',
                'name2' => $postData['name2'] ?? '',
                'category' => $postData['category'] ?? '',
                'date' => $postData['date'] ?? '',
                'username' => 'Admin'
            ];
        }
    }

    $userPostsDir = $postsDir . '/user_posts';
    if (is_dir($userPostsDir)) {
        $userPosts = glob($userPostsDir . '/*/data.json');
        foreach ($userPosts as $postFile) {
            $postData = json_decode(file_get_contents($postFile), true);
            if (
                $postData && isset($postData['request']) && $postData['request'] === false &&
                isset($postData['status']) && $postData['status'] === true &&
                postMatchesSearch($postData, $query)
            ) {

                $postId = basename(dirname($postFile));
                $userId = $postData['user_id'] ?? '';
                $username = 'Unknown User';

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

                $results[] = [
                    'type' => 'user',
                    'post_id' => $postId,
                    'name1' => $postData['name1'] ?? '',
                    'name2' => $postData['name2'] ?? '',
                    'category' => $postData['category'] ?? '',
                    'date' => $postData['date'] ?? '',
                    'username' => $username
                ];
            }
        }
    }

    return $results;
}

function postMatchesSearch($postData, $query)
{
    $searchTerms = explode(' ', strtolower($query));
    $name1 = strtolower($postData['name1'] ?? '');
    $name2 = strtolower($postData['name2'] ?? '');
    $category = strtolower($postData['category'] ?? '');

    foreach ($searchTerms as $term) {
        if (
            strpos($name1, $term) !== false ||
            strpos($name2, $term) !== false ||
            strpos($category, $term) !== false
        ) {
            return true;
        }
    }
    return false;
}

if (isset($_POST['approve'])) {
    $postDir = $_POST['post_dir'];
    $absolutePostDir = $baseDir . "/" . $postDir;
    $dataFile = "$absolutePostDir/data.json";
    if (file_exists($dataFile)) {
        $data = json_decode(file_get_contents($dataFile), true);
        $data['request'] = false;
        $data['status'] = true;
        file_put_contents($dataFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
} elseif (isset($_POST['delete'])) {
    $postDir = $_POST['post_dir'];
    $absolutePostDir = $baseDir . "/" . $postDir;

    function rrmdir($dir)
    {
        foreach (glob($dir . '/*') as $file) {
            if (is_dir($file)) rrmdir($file);
            else unlink($file);
        }
        rmdir($dir);
    }
    if (is_dir($absolutePostDir)) {
        rrmdir($absolutePostDir);
    }
}

$pendingPosts = [];
$usersPostsDir = $postsDir . "/user_posts";
if (is_dir($usersPostsDir)) {
    foreach (glob("$usersPostsDir/*") as $postDir) {
        $dataFile = "$postDir/data.json";
        if (file_exists($dataFile)) {
            $data = json_decode(file_get_contents($dataFile), true);
            if ($data['request'] ?? false) {
                $pendingPosts[] = [
                    'dir' => $postDir,
                    'data' => $data,
                    'relative_dir' => "posts/user_posts/" . basename($postDir)
                ];
            }
        }
    }
}
?>
<!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 - Requests</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">
        <div class="flex-1 p-8 flex flex-col h-[770px]">
            <div class="flex flex-col h-full overflow-hidden">
                <div class="px-6 py-5 border-b border-gray-300">
                    <h2 class="text-[25px] font-medium text-gray-800 text-center">Request Posts</h2>
                </div>

                <div class="p-2 pt-6 flex-1 flex flex-col overflow-hidden">
                    <?php if (!empty($pendingPosts)): ?>
                        <div class="flex-1 overflow-y-auto space-y-4 pr-2 -mr-2">
                            <?php foreach ($pendingPosts as $post):
                                $d = $post['data'];
                                $relativeDir = $post['relative_dir'];
                                $userDir = $usersDir . "/" . $d['user_id'];

                                $username = $d['user_id'];
                                $userDataFile = "$userDir/data.json";
                                if (file_exists($userDataFile)) {
                                    $userData = json_decode(file_get_contents($userDataFile), true);
                                    if (isset($userData['username'])) {
                                        $username = $userData['username'];
                                    }
                                }

                                $profilePic = "../images/default-avatar.png";
                                if (file_exists("$userDir/profile.jpg")) $profilePic = "../users/{$d['user_id']}/profile.jpg";
                                if (file_exists("$userDir/profile.png")) $profilePic = "../users/{$d['user_id']}/profile.png";

                                $image1_path = null;
                                $image2_path = null;
                                foreach (['jpg', 'png', 'jpeg'] as $ext) {
                                    if (!$image1_path && file_exists($post['dir'] . "/image_1.$ext")) {
                                        $image1_path = "../posts/user_posts/" . basename($post['dir']) . "/image_1.$ext";
                                    }
                                    if (!$image2_path && file_exists($post['dir'] . "/image_2.$ext")) {
                                        $image2_path = "../posts/user_posts/" . basename($post['dir']) . "/image_2.$ext";
                                    }
                                }
                            ?>
                                <div class="bg-gray-50 rounded-lg p-4 border border-gray-200 hover:border-[#00000050] transition">
                                    <div class="flex items-center gap-3 mb-4 pb-3 border-b border-gray-100">
                                        <img src="<?= $profilePic ?>" class="w-10 h-10 rounded-full object-cover border border-gray-200">
                                        <div class="flex-1">
                                            <div class="flex justify-between items-center">
                                                <span class="text-gray-800 font-semibold"><?= htmlspecialchars($username) ?></span>
                                                <span class="text-gray-500 text-sm"><?= $d['date'] ?></span>
                                            </div>
                                            <p class="text-gray-600 text-sm mt-1">Category: <?= htmlspecialchars($d['category']) ?></p>
                                        </div>
                                    </div>

                                    <div class="grid grid-cols-2 gap-4 mb-4">
                                        <div class="text-center">
                                            <div class="relative bg-gray-50 rounded-lg border border-gray-200 overflow-hidden h-40">
                                                <?php if ($image1_path): ?>
                                                    <img src="<?= $image1_path ?>" class="w-full h-full object-cover" alt="<?= htmlspecialchars($d['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="text-gray-700 font-medium mt-2 text-sm"><?= htmlspecialchars($d['name1']) ?></p>
                                        </div>

                                        <div class="text-center">
                                            <div class="relative bg-gray-50 rounded-lg border border-gray-200 overflow-hidden h-40">
                                                <?php if ($image2_path): ?>
                                                    <img src="<?= $image2_path ?>" class="w-full h-full object-cover" alt="<?= htmlspecialchars($d['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="text-gray-700 font-medium mt-2 text-sm"><?= htmlspecialchars($d['name2']) ?></p>
                                        </div>
                                    </div>

                                    <form method="post" class="flex gap-2 justify-end pt-3 border-t border-gray-300">
                                        <input type="hidden" name="post_dir" value="<?= $relativeDir ?>">
                                        <button type="submit" name="delete"
                                            class="flex items-center justify-center w-full gap-2 bg-red-600 text-[15px] text-white font-normal px-3 py-1 rounded-md">
                                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            Delete
                                        </button>
                                        <button type="submit" name="approve"
                                            class="flex items-center justify-center w-full gap-2 bg-green-600 text-[15px] text-white font-normal px-3 py-1 rounded-md">
                                            <i data-lucide="check" class="w-4 h-4"></i>
                                            Approve
                                        </button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="flex-1 flex flex-col items-center justify-center text-gray-500">
                            <i data-lucide="inbox" class="w-16 h-16 mb-4 text-gray-300"></i>
                            <p class="text-lg font-medium mb-2">No Pending Requests</p>
                            <p class="text-sm">There are no posts waiting for approval</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="flex-1 p-8 flex flex-col">
            <div class="flex-1 flex flex-col overflow-hidden h-full">
                <div class="px-6 py-5 border-b border-gray-300">
                    <h2 class="text-[25px] font-medium text-gray-800 text-center">Search Posts</h2>
                </div>
                <div class="p-6 flex-1 flex flex-col">
                    <form method="get" class="mb-6">
                        <div class="flex gap-2">
                            <input type="text" name="search" value="<?= htmlspecialchars($searchQuery) ?>"
                                placeholder="Search by name or category..."
                                class="flex-1 outline-none focus:outline-none px-3 py-2 rounded-md bg-white text-gray-800 border border-gray-300">
                            <button type="submit"
                                class="px-4 py-2 bg-black text-[15px] text-white font-normal py-2 rounded-md">
                                Search
                            </button>
                        </div>
                    </form>

                    <?php if (!empty($searchQuery)): ?>
                        <div class="flex-1 flex flex-col">
                            <h3 class="text-lg font-semibold text-gray-800 mb-4">
                                Search Results for "<?= htmlspecialchars($searchQuery) ?>"
                            </h3>

                            <?php if (empty($searchResults)): ?>
                                <div class="flex-1 flex items-center justify-center">
                                    <p class="text-gray-500 text-center py-4">No posts found matching your search.</p>
                                </div>
                            <?php else: ?>
                                <div class="space-y-3 flex-1 overflow-y-auto max-h-[calc(100vh-300px)] pb-4">
                                    <?php foreach ($searchResults as $post): ?>
                                        <div class="bg-gray-50 rounded-lg p-4 border border-gray-200 hover:border-[#00000050] transition">
                                            <div class="flex justify-between items-start mb-2">
                                                <div>
                                                    <h4 class="font-semibold text-gray-800">
                                                        <?= htmlspecialchars($post['name1']) ?> vs <?= htmlspecialchars($post['name2']) ?>
                                                    </h4>
                                                    <p class="text-sm text-gray-600">Category: <?= htmlspecialchars($post['category']) ?></p>
                                                </div>
                                                <span class="text-xs px-2 py-1 rounded-full 
                                            <?= $post['type'] === 'admin' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800' ?>">
                                                    <?= $post['type'] === 'admin' ? 'Admin Post' : 'User Post' ?>
                                                </span>
                                            </div>
                                            <div class="flex justify-between items-center text-sm text-gray-500">
                                                <span>Posted by: <?= htmlspecialchars($post['username']) ?></span>
                                                <span><?= htmlspecialchars($post['date']) ?></span>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="flex-1 flex flex-col items-center justify-center">
                            <i data-lucide="search" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
                            <p class="text-gray-500">Enter a search term to find posts</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        lucide.createIcons();
    </script>

</body>

</html>