<?php
session_start();

function validate_user_id($userId)
{
    return preg_match('/^[a-f0-9]{32}$/', $userId);
}

$userId = $_SESSION['user_id'] ?? '';
if (!validate_user_id($userId)) {
    header("Location: login.php");
    exit;
}

$userDir = __DIR__ . "/users/" . basename($userId);
$userWebDir = "users/" . basename($userId);

if (!is_dir($userDir)) {
    if (!mkdir($userDir, 0700, true)) {
        header("Location: login.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',
];

$error = '';
$success = '';

$profilePic = "images/default-avatar.png";
foreach (['jpg', 'jpeg', 'png'] as $ext) {
    $imgPath = "$userDir/profile.$ext";
    if (file_exists($imgPath) && is_file($imgPath)) {
        $profilePic = "$userWebDir/profile.$ext";
        break;
    }
}

$limitFile = "$userDir/post_limit.json";
$today = date("Y-m-d");

$postData = ['date' => $today, 'count' => 0];
if (file_exists($limitFile)) {
    $limitContent = file_get_contents($limitFile);
    if ($limitContent !== false) {
        $savedData = json_decode($limitContent, true);
        if ($savedData && isset($savedData['date']) && $savedData['date'] === $today) {
            $postData = $savedData;
        }
    }
}

function validate_uploaded_image($file, $max_size = 1024 * 1024)
{
    $upload_errors = [
        UPLOAD_ERR_INI_SIZE => "File exceeds upload_max_filesize",
        UPLOAD_ERR_FORM_SIZE => "File exceeds MAX_FILE_SIZE",
        UPLOAD_ERR_PARTIAL => "File partially uploaded",
        UPLOAD_ERR_NO_FILE => "No file uploaded",
        UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder",
        UPLOAD_ERR_CANT_WRITE => "Failed to write file",
        UPLOAD_ERR_EXTENSION => "PHP extension stopped upload"
    ];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return $upload_errors[$file['error']] ?? "Upload error occurred";
    }

    if ($file['size'] > $max_size) {
        return "Image must be less than " . round($max_size / 1024 / 1024, 1) . "MB";
    }

    if ($file['size'] == 0) {
        return "File is empty";
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/pjpeg'];
    if (!in_array($file['type'], $allowed_types)) {
        return "Only JPG and PNG images are allowed";
    }

    $file_signature = file_get_contents($file['tmp_name'], false, null, 0, 4);
    $signatures = [
        'image/jpeg' => "\xFF\xD8\xFF",
        'image/png'  => "\x89PNG"
    ];

    $expected_signature = '';
    if (strpos($file['type'], 'jpeg') !== false) {
        $expected_signature = $signatures['image/jpeg'];
    } elseif (strpos($file['type'], 'png') !== false) {
        $expected_signature = $signatures['image/png'];
    }

    if ($expected_signature && strpos($file_signature, $expected_signature) !== 0) {
        return "Invalid image file";
    }

    $image_info = @getimagesize($file['tmp_name']);
    if (!$image_info) {
        return "Invalid image file";
    }

    return true;
}

function safe_file_upload($source, $destination)
{
    $dir = dirname($destination);
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0700, true)) {
            return false;
        }
    }

    if (!is_writable($dir)) {
        return false;
    }

    return move_uploaded_file($source, $destination);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    $requestTime = $_SERVER['REQUEST_TIME'] ?? time();
    if (abs($requestTime - time()) > 30) {
        $error = "Invalid request";
    } elseif ($postData['count'] >= 3) {
        $error = "You have reached the maximum of 3 posts today. Please try again tomorrow!";
    } else {
        $item1_name = trim($_POST['item1_name'] ?? '');
        $item2_name = trim($_POST['item2_name'] ?? '');
        $category = $_POST['category'] ?? '';

        if (empty($item1_name) || empty($item2_name)) {
            $error = "Both item names are required";
        } elseif (strlen($item1_name) > 50 || strlen($item2_name) > 50) {
            $error = "Item names must be less than 50 characters";
        } elseif (!preg_match('/^[a-zA-Z0-9 ]+$/', $item1_name) || !preg_match('/^[a-zA-Z0-9 ]+$/', $item2_name)) {
            $error = "Item names can only contain English letters and numbers";
        } elseif (!in_array($category, $categories)) {
            $error = "Please select a valid category";
        } else {
            $image1 = $_FILES['item1_image'] ?? null;
            $image2 = $_FILES['item2_image'] ?? null;

            if (!$image1 || !$image2) {
                $error = "Please upload both images!";
            } else {
                $validation1 = validate_uploaded_image($image1);
                $validation2 = validate_uploaded_image($image2);

                if ($validation1 !== true) {
                    $error = "Image 1: " . $validation1;
                } elseif ($validation2 !== true) {
                    $error = "Image 2: " . $validation2;
                } else {
                    $postId = time() . '_' . bin2hex(random_bytes(4));
                    $postDir = __DIR__ . "/posts/user_posts/" . basename($postId);

                    if (!mkdir($postDir, 0700, true)) {
                        $error = "There was a problem creating the post!";
                    } else {
                        $ext1 = (strpos($image1['type'], 'jpeg') !== false) ? 'jpg' : 'png';
                        $ext2 = (strpos($image2['type'], 'jpeg') !== false) ? 'jpg' : 'png';

                        $path1 = "$postDir/image_1.$ext1";
                        $path2 = "$postDir/image_2.$ext2";

                        if (!safe_file_upload($image1['tmp_name'], $path1)) {
                            $error = "Failed to upload image 1";
                            @rmdir($postDir);
                        } elseif (!safe_file_upload($image2['tmp_name'], $path2)) {
                            $error = "Failed to upload image 2";
                            @unlink($path1);
                            @rmdir($postDir);
                        } else {
                            $data = [
                                'user_id' => $userId,
                                'name1' => htmlspecialchars($item1_name, ENT_QUOTES, 'UTF-8'),
                                'name2' => htmlspecialchars($item2_name, ENT_QUOTES, 'UTF-8'),
                                'category' => $category,
                                'date' => date("Y-m-d H:i:s"),
                                'votes1' => [],
                                'votes2' => [],
                                'comments' => [],
                                'request' => true,
                                'status' => false
                            ];

                            if (file_put_contents("$postDir/data.json", json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX) !== false) {
                                $postData['count']++;
                                $postData['date'] = $today;
                                file_put_contents($limitFile, json_encode($postData), LOCK_EX);

                                $success = "Your post has been successfully submitted and is awaiting review";
                            } else {
                                $error = "There was a problem saving the post!";
                                @unlink($path1);
                                @unlink($path2);
                                @rmdir($postDir);
                            }
                        }
                    }
                }
            }
        }
    }
}

$username = '';
$userFile = __DIR__ . "/users/" . basename($userId) . "/data.json";
if (file_exists($userFile)) {
    $userData = file_get_contents($userFile);
    if ($userData !== false) {
        $userInfo = json_decode($userData, true);
        if ($userInfo && isset($userInfo['username'])) {
            $username = htmlspecialchars($userInfo['username'], ENT_QUOTES, 'UTF-8');
        }
    }
}
?>

<meta charset="UTF-8">
<head>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@30.1.0/dist/font-face.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <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>

    <script src="scripts/disable-zoom.js"></script>
    <script src="scripts/connection-check.js"></script>

    <link rel="icon" type="image/png" href="/images/favicon.png">
    <title>Rankly / Send Post</title>
</head>

<style>
    #offline-overlay {
        position: fixed;
        inset: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.75);
        z-index: 999999;
        pointer-events: none;
        opacity: 0;
        transition: opacity 0.5s ease;
        user-select: none;
    }

    #offline-overlay.active {
        pointer-events: auto;
        opacity: 1;
    }

    #offline-overlay .offline-card {
        width: 125px;
        height: 125px;
        background: url('images/loading.png') center/contain no-repeat;
        filter: drop-shadow(0 0px 30px rgba(255, 255, 255, 0.25));
        animation: pulse 2.5s infinite alternate ease-in-out;
    }
</style>

<body class="mx-auto">
    <div class="mx-auto px-4 pt-5">
        <div class="absolute inset-0 rounded-lg pointer-events-none" style="background: radial-gradient(circle at top left, rgba(255, 255, 255, 0), transparent 70%);"></div>

        <form action="send_post.php" method="POST" enctype="multipart/form-data" class="space-y-6">
            <div class="grid grid-cols-1 gap-6">

                <div class="w-full flex items-center justify-between rounded-lg">
                    <a href="index.php">
                        <i data-lucide="arrow-left" class="w-5 h-5 text-white mb-1"></i>
                    </a>

                    <div>
                        <button type="submit" name="submit"
                            class="bg-white text-[#000000] font-medium py-1 px-3 rounded-lg transition text-sm flex items-center">
                            <i data-lucide="check" class="w-4 h-4 mr-1"></i>Post
                        </button>
                    </div>
                </div>

                <div class="flex items-center space-x-3 mt-1">
                    <img src="<?= htmlspecialchars($profilePic, ENT_QUOTES, 'UTF-8') ?>" alt="Avatar" class="w-10 h-10 rounded-[6px] object-cover">
                    <span class="text-white text-[20px] font-normal">Do you want to post?</span>
                </div>

                <?php if ($error): ?>
                    <div style="direction: ltr;" class="flex items-center text-[13px] mt-1 text-left text-white pr-4 rounded mb-1">
                        <i class="w-4 h-4 mr-2 text-red-600" data-lucide="ban"></i>
                        <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div style="direction: ltr;" class="flex items-center text-[13px] mt-1 text-left text-white pr-4 rounded mb-1">
                        <i class="w-4 h-4 mr-2 text-green-600" data-lucide="check"></i>
                        <?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>

                <div class="flex justify-center gap-4">
                    <div class="flex flex-col items-center flex-1">
                        <label for="item2_image" class="cursor-pointer w-full">
                            <div id="item2Preview" class="w-full h-48 rounded-lg flex items-center justify-center mb-2 overflow-hidden bg-[#ffffff08]">
                                <div class="flex flex-col items-center space-y-2">
                                    <span class="text-gray-400 text-4xl select-none">
                                        <i class="fas fa-camera text-gray-500"></i>
                                    </span>
                                    <span class="text-sm text-gray-500 select-none">Upload Image</span>
                                </div>
                            </div>
                            <input type="file" id="item2_image" name="item2_image" accept="image/*" class="hidden" onchange="previewImage(this, 'item2Preview')">
                        </label>
                        <div class="flex items-center bg-[#ffffff08] text-[15px] rounded-lg mt-1 px-3 py-2 focus-within:ring-2 focus-within:ring-blue-500">
                            <i data-lucide="pencil-line" class="w-4 h-4 text-[#ffffff85]"></i>
                            <input style="direction: ltr;" type="text" id="item2_name" name="item2_name" required
                                placeholder="Item Name 2"
                                class="w-full ml-2 bg-transparent text-gray-200 placeholder-[#ffffff25] focus:outline-none" />
                        </div>
                    </div>

                    <div class="flex flex-col items-center flex-1">
                        <label for="item1_image" class="cursor-pointer w-full">
                            <div id="item1Preview" class="w-full h-48 rounded-lg flex items-center justify-center mb-2 overflow-hidden bg-[#ffffff08]">
                                <div class="flex flex-col items-center space-y-2">
                                    <span class="text-gray-400 text-4xl select-none">
                                        <i class="fas fa-camera text-gray-500"></i>
                                    </span>
                                    <span class="text-sm text-gray-500 select-none">Upload Image</span>
                                </div>
                            </div>
                            <input type="file" id="item1_image" name="item1_image" accept="image/*" class="hidden" onchange="previewImage(this, 'item1Preview')">
                        </label>
                        <div class="flex items-center bg-[#ffffff08] text-[15px] rounded-lg mt-1 px-3 py-2 focus-within:ring-2 focus-within:ring-blue-500">
                            <i data-lucide="pencil-line" class="w-4 h-4 text-[#ffffff85]"></i>
                            <input style="direction: ltr;" type="text" id="item1_name" name="item1_name" required
                                placeholder="Item Name 1"
                                class="w-full ml-2 bg-transparent text-gray-200 placeholder-[#ffffff25] focus:outline-none" />
                        </div>
                    </div>
                </div>
            </div>

            <div class=" w-full h-[1px] bg-gradient-to-r from-transparent via-white/40 to-transparent"></div>

            <div class="mx-auto relative">
                <select
                    style="direction: ltr;"
                    id="category"
                    name="category"
                    required
                    class="w-full pl-4 pr-10 py-3 bg-[#252525] text-white rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="" disabled selected>Select Category</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat); ?>"><?php echo htmlspecialchars($cat); ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="absolute inset-y-0 right-0 flex items-center px-3 pointer-events-none">
                    <svg class="w-4 h-4 text-gray-300" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                    </svg>
                </div>
            </div>
        </form>
    </div>

    <div class="flex">
        <div style="direction: ltr;" class="w-full max-w-md mx-4 border-b-[1px] border-[#ffffff25]">
            <button id="rulesToggle"
                class="flex items-center gap-2 w-full text-[#ffffff75] text-[15px] p-3 cursor-pointer">

                <i data-lucide="scale" class="w-5 h-5 mb-1"></i>
                <span>Conditions for registering user posts</span>
            </button>

            <div id="rulesBox"
                class="bg-[#ffffff01] text-gray-200 overflow-hidden max-h-0 transition-all duration-300">

                <ul class="border-l-[1px] ml-2 mt-5 mb-5 border-[#ffffff15] pl-3 text-sm leading-7">
                    <li>High-quality images under one megabyte</li>
                    <li>The images must comply with the criteria</li>
                    <li>Select the appropriate category to compare</li>
                    <li>Product names must be correct and complete</li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        function previewImage(input, previewId) {
            const preview = document.getElementById(previewId);
            const file = input.files[0];
            const reader = new FileReader();

            reader.onload = function(e) {
                preview.innerHTML = `<img src="${e.target.result}" class="w-full h-full object-cover">`;
            }

            if (file) {
                reader.readAsDataURL(file);
            }
        }

        const toggleBtn = document.getElementById('rulesToggle');
        const rulesBox = document.getElementById('rulesBox');

        toggleBtn.addEventListener('click', () => {
            const isOpen = rulesBox.style.maxHeight && rulesBox.style.maxHeight !== "0px";

            if (isOpen) {
                rulesBox.style.maxHeight = "0px";
            } else {
                rulesBox.style.maxHeight = rulesBox.scrollHeight + "px";
            }
        });
    </script>
</body>

<script>
    lucide.createIcons();

    const item1Input = document.getElementById('item1_name');
    const item2Input = document.getElementById('item2_name');

    function filterEnglishNumbers(e) {
        e.target.value = e.target.value.replace(/[^a-zA-Z0-9 ]/g, '');
    }

    item1Input.addEventListener('input', filterEnglishNumbers);
    item2Input.addEventListener('input', filterEnglishNumbers);
</script>