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

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

$categories = [
    'Technology & Devices',
    'Entertainment & Media',
    'Games & Platforms',
    'Lifestyle & Style',
    'Food & Taste',
    'Places & Travel',
    'People & Public Figures',
    'Cars & Tools',
    'Life & Beliefs',
    'Brands & Companies',
    'Products & Instruments',
    'Money & Services',
    'Education & Learning',
    'Memes & Culture',
];

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

// Handle post submission
if (isset($_POST['submit'])) {
    $name1 = $_POST['name1'];
    $name2 = $_POST['name2'];
    $category = $_POST['category'];

    $postId = time();
    $postDir = "$postsDir/$postId";
    mkdir($postDir, 0777, true);

    $image1 = $_FILES['image1'];
    $image2 = $_FILES['image2'];

    if ($image1['error'] === 0) {
        move_uploaded_file($image1['tmp_name'], "$postDir/image_1.jpg");
    }
    if ($image2['error'] === 0) {
        move_uploaded_file($image2['tmp_name'], "$postDir/image_2.jpg");
    }

    $data = [
        'name1' => $name1,
        'name2' => $name2,
        'category' => $category,
        'date' => date("Y-m-d H:i:s"),
        'votes1' => [],
        'votes2' => [],
        'comments' => []
    ];

    file_put_contents("$postDir/data.json", json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

// Handle post search
$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 = [];

    // Search in admin posts (posts/$post_id)
    $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'
            ];
        }
    }

    // Search in user posts (posts/user_posts/$post_id)
    $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';

                // Get username from user data
                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;
}
?>
<!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 - Send Post</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">
            <div class="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">Create New Post</h2>
                </div>

                <form method="post" enctype="multipart/form-data" class="flex flex-col gap-4 p-6">

                    <div class="flex flex-col">
                        <label class="mb-1 text-gray-700 font-medium">Comparison Name 1</label>
                        <input type="text" name="name1" required
                            class="px-3 py-2 outline-none focus:outline-none rounded-md bg-white text-gray-800 border border-gray-300">
                    </div>

                    <div class="flex flex-col border-b-[1px] border-[#00000010] pb-8">
                        <label class="mb-1 text-gray-700 font-medium">Comparison Image 1</label>
                        <input type="file" name="image1" accept="image/*" required
                            class="px-3 py-2 outline-none focus:outline-none rounded-md bg-white text-gray-800 border border-gray-300">
                    </div>

                    <div class="flex flex-col">
                        <label class="mb-1 text-gray-700 font-medium">Comparison Name 2</label>
                        <input type="text" name="name2" required
                            class="px-3 py-2 outline-none focus:outline-none rounded-md bg-white text-gray-800 border border-gray-300">
                    </div>

                    <div class="flex flex-col border-b-[1px] border-[#00000010] pb-8">
                        <label class="mb-1 text-gray-700 font-medium">Comparison Image 2</label>
                        <input type="file" name="image2" accept="image/*" required
                            class="px-3 py-2 outline-none focus:outline-none rounded-md bg-white text-gray-800 border border-gray-300">
                    </div>

                    <div class="flex flex-col">
                        <label class="mb-1 outline-none focus:outline-none text-gray-700 font-medium">Category</label>
                        <select name="category" required
                            class="px-3 py-2 rounded-md bg-white text-gray-800 border border-gray-300">
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?= htmlspecialchars($cat) ?>"><?= htmlspecialchars($cat) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <button type="submit" name="submit"
                        class="mt-2 bg-green-600 text-[15px] text-white font-normal px-3 py-1 rounded-md">
                        Submit Post
                    </button>

                </form>
            </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>