<?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)) {
    header("Location: login.php");
    exit;
}

function safe_json_read($file)
{
    if (!file_exists($file) || !is_readable($file)) {
        return null;
    }

    $content = file_get_contents($file);
    if ($content === false) {
        return null;
    }

    $data = json_decode($content, true);
    return json_last_error() === JSON_ERROR_NONE ? $data : null;
}

$dataFile = "$userDir/data.json";
$data = safe_json_read($dataFile);

if (!$data) {
    header("Location: login.php");
    exit;
}

$display_name = htmlspecialchars($data['displayname'] ?? '');
$username = htmlspecialchars($data['username'] ?? '');
$age = htmlspecialchars($data['age'] ?? '');
$registered = htmlspecialchars($data['registered'] ?? '');

$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;
    }
}

$bioFile = "$userDir/bio.txt";
$bio = file_exists($bioFile) ? file_get_contents($bioFile) : "Hi, I am $display_name";

if (isset($_POST['logout'])) {
    session_destroy();
    header("Location: login.php");
    exit;
}

$uploadCooldown = 30 * 60;

$uploadInfoFile = "$userDir/upload_info.json";
$uploadInfo = file_exists($uploadInfoFile) ? json_decode(file_get_contents($uploadInfoFile), true) : [];

$now = time();

if (isset($_POST['upload_profile'])) {
    $lastProfileUpload = $uploadInfo['profile'] ?? 0;
    if ($now - $lastProfileUpload < $uploadCooldown) {
        $error = "You can only change your profile picture every 30 minutes";
    } else {
        if (!isset($_FILES['profile'])) {
            $error = "No file selected!";
        } else {
            $file = $_FILES['profile'];
            $allowed = ["image/jpeg" => "jpg", "image/png" => "png"];

            if (!isset($allowed[$file['type']])) {
                $error = "Only JPG and PNG are allowed!";
            } elseif ($file['size'] > 599 * 1024) {
                $error = "The file must not be larger than 500KB";
            } else {
                $ext = $allowed[$file['type']];
                $savePath = "$userDir/profile.$ext";

                @unlink("$userDir/profile.jpg");
                @unlink("$userDir/profile.png");

                move_uploaded_file($file['tmp_name'], $savePath);

                $uploadInfo['profile'] = $now;
                file_put_contents($uploadInfoFile, json_encode($uploadInfo));

                header("Location: profile.php");
                exit;
            }
        }
    }
}

if (isset($_POST['upload_background'])) {
    $lastBackgroundUpload = $uploadInfo['background'] ?? 0;
    if ($now - $lastBackgroundUpload < $uploadCooldown) {
        $bgError = "You can only change the background image every 30 minutes";
    } else {
        if (!isset($_FILES['background'])) {
            $bgError = "No file selected";
        } else {
            $file = $_FILES['background'];
            $allowed = ["image/jpeg" => "jpg", "image/png" => "png", "image/gif" => "gif"];

            if (!isset($allowed[$file['type']])) {
                $bgError = "فرمت مجاز: JPG، PNG یا GIF.";
            } elseif ($file['size'] > 599 * 1024) {
                $bgError = "The file size should not exceed 500KB";
            } else {
                $ext = $allowed[$file['type']];
                $tmpPath = $file['tmp_name'];

                list($width, $height) = getimagesize($tmpPath);
                if ($width <= $height) {
                    $bgError = "The image must be rectangular (width greater than height)";
                } else {
                    $savePath = "$userDir/background_profile.$ext";

                    foreach (["jpg", "png", "gif"] as $e) {
                        @unlink("$userDir/background_profile.$e");
                    }

                    move_uploaded_file($tmpPath, $savePath);

                    $uploadInfo['background'] = $now;
                    file_put_contents($uploadInfoFile, json_encode($uploadInfo));

                    header("Location: profile.php");
                    exit;
                }
            }
        }
    }
}

$backgroundPic = '';
foreach (["jpg", "png", "gif"] as $e) {
    if (file_exists("$userDir/background_profile.$e")) {
        $backgroundPic = "$userWebDir/background_profile.$e";
        break;
    }
}

if (isset($_POST['save_bio'])) {
    $newBio = trim($_POST['bio'] ?? '');

    if (strlen($newBio) > 500) {
        $newBio = substr($newBio, 0, 500);
    }

    $newBio = htmlspecialchars($newBio, ENT_QUOTES, 'UTF-8');

    if (file_put_contents($bioFile, $newBio, LOCK_EX) !== false) {
        header("Location: profile.php");
        exit;
    }
}

$commentsCount = 0;
$votesCount = 0;

$postsDir = __DIR__ . "/posts";
if (is_dir($postsDir)) {
    foreach (glob("$postsDir/*/data.json") as $postFile) {
        $post = json_decode(file_get_contents($postFile), true);

        if (in_array($userId, $post['votes1'] ?? [])) $votesCount++;
        if (in_array($userId, $post['votes2'] ?? [])) $votesCount++;

        foreach ($post['comments'] as $c) {
            if (($c['user'] ?? '') === $userId) {
                $commentsCount++;
            }
        }
    }
}

$userPosts = [];
$usersPostsDir = __DIR__ . "/posts/user_posts";
if (is_dir($usersPostsDir)) {
    foreach (glob("$usersPostsDir/*") as $postDir) {
        $dataFile = "$postDir/data.json";
        if (file_exists($dataFile)) {
            $postData = json_decode(file_get_contents($dataFile), true);

            if (($postData['user_id'] ?? '') === $userId &&
                ($postData['request'] ?? true) === false &&
                ($postData['status'] ?? false) === true
            ) {

                $postData['id'] = basename($postDir);
                $postData['source'] = 'user';

                $totalVotes = (count($postData['votes1'] ?? []) + count($postData['votes2'] ?? []));
                $postData['total_votes'] = $totalVotes;

                $postData['popularity_score'] = $totalVotes;

                $userPosts[] = $postData;
            }
        }
    }
}

usort($userPosts, function ($a, $b) {
    return ($b['popularity_score'] ?? 0) - ($a['popularity_score'] ?? 0);
});

$userPostsCount = count($userPosts);
?>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="/images/favicon.png">
    <title>Rankly / Profile <?= $username ?></title>
</head>

<body>
    <?php include "header.php"; ?>

    <div class="text-white mt-5 rtl">
        <div style="font-family: 'Roboto Flex', sans-serif;"
            class="flex flex-row justify-between items-start pr-5 pl-5 mb-4 rtl">
            <div class="text-left">
                <p class="text-2xl font-semibold"><?= $display_name ?></p>
                <span class="text-[13px] text-[#ffffff50]">
                    <span class="text-[15px] text-[#ffffff25]">@ </span><?= $username ?>
                </span>
            </div>

            <div class="flex justfiy-between gap-5">
                <a href="settings.php">
                    <i data-lucide="settings" class="w-5 h-5 text-[#ffffff50] transition"></i>
                </a>

                <form id="logoutForm" method="post">
                    <button type="button" id="logoutBtn" class="text-white">
                        <i data-lucide="log-out" class="w-5 h-5 text-[#ffffff50] transition"></i>
                    </button>
                </form>
            </div>

            <div id="logoutLoading" class="hidden fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50">
                <div class="w-16 h-16 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
            </div>
        </div>

        <div class="border-b border-white/20"></div>

        <div class="relative w-full h-[150px] bg-gradient-to-r from-[#2b2b2b] to-[#1e1e1e] ">
            <div id="backgroundContainer" class="relative w-full h-[150px] cursor-pointer overflow-hidden">
                <?php if ($backgroundPic): ?>
                    <img src="<?= $backgroundPic ?>?<?= time() ?>" class="w-full h-full object-cover">
                <?php else: ?>
                    <div class="background w-full h-full"></div>
                <?php endif; ?>

                <form id="backgroundForm" method="post" enctype="multipart/form-data" class="hidden">
                    <input type="file" name="background" id="backgroundInput" accept="image/png,image/jpeg,image/gif">
                    <input type="hidden" name="upload_background" value="1">
                </form>
            </div>
            <form method="post" enctype="multipart/form-data" class="absolute right-6 bottom-[-60px]">
                <label class="cursor-pointer block">
                    <div class="w-24 h-24 rounded-[15px] p-[5px] bg-[#111111] overflow-hidden">
                        <img src="<?= $profilePic ?>?<?= time() ?>"
                            class="w-full h-full object-cover rounded-[10px]">
                    </div>
                    <input type="file" name="profile" class="hidden" onchange="this.form.submit()">
                </label>
                <input type="hidden" name="upload_profile" value="1">
            </form>
        </div>
    </div>
    <div class="mt-[60px] px-4 relative">
        <form method="post" id="bioForm" class="relative text-right mb-5">
            <textarea id="bioText" name="bio" readonly
                class="w-full bg-[#191919] p-3 rounded-lg text-white resize-none h-[6.5rem] overflow-hidden"
                style="line-height: 1.5rem;"><?= htmlspecialchars($bio) ?></textarea>
            <button type="button" id="editBio" class="absolute top-2 right-2 text-white">
                <i class="w-5 h-5 m-2 text-[#ffffff25]" data-lucide="edit-3"></i>
            </button>
            <button type="submit" id="saveBio" class="absolute top-2 right-2 hidden">
                <i class="w-5 h-5 m-2 text-green-400" data-lucide="check"></i>
            </button>
            <input type="hidden" name="save_bio" value="1">

            <div id="charCount" class="absolute bottom-1 left-2 text-xs text-[#ffffff50]">200</div>
        </form>

        <div class="flex flex-row justify-start text-left text-[#ffffff75] text-[13px]">
            <i class="w-4 h-4 mr-1" data-lucide="calendar-days"></i>
            <p class="mr-3 text-[12px]"><span class="font-medium">Membership:</span> <?= $registered ?></p>
            <span>|</span>
            <i class="w-4 h-4 ml-3 mr-1" data-lucide="box"></i>
            <p class="text-[12px]"><span class="font-medium">Age:</span> <?= $age ?: 'Null' ?></p>
        </div>
    </div>

    <div class="flex flex-row px-4 justify-start text-left border-b pb-5 border-[#ffffff25] rtl text-white text-[15px] mr-1 mt-3 gap-x-4">

        <p class="flex items-center gap-x-1">
            <span class="mr-1 text-white"><?= $votesCount ?></span><span class="font-medium text-[#ffffff85]">Vote Comparisons</span>
        </p>
        <p class="flex items-center gap-x-1">
            <span class="mr-1 text-white"><?= $commentsCount ?></span><span class="font-medium text-[#ffffff85]">Comment sent</span>
        </p>
    </div>

    <h2 class="text-[21px] font-bold ml-6 mt-6 text-white text-left posts-title">Comparisons Recorded</h2>
    <p class="text-[12px] font-bold mb-4 ml-6 mt-[3px] text-[#ffffff50] text-left posts-title"><?= $userPostsCount ?> Posts</p>

    <div class="px-4 mb-5">
        <?php if ($userPostsCount > 0): ?>
            <div class="space-y-6">
                <?php foreach ($userPosts as $post): ?>
                    <div id="post-<?= $post['id'] ?>"
                        class="post-item relative bg-[#ffffff08] rounded-lg flex flex-col overflow-hidden clickable-post cursor-pointer transition-all duration-300 hover:bg-[#ffffff20]"
                        data-post-id="<?= $post['id'] ?>">

                        <div class="flex justify-center items-center px-4 mt-4 gap-2 rtl text-gray-400 text-[12.5px]">
                            <i data-lucide="tag" class="w-4 h-4"></i>
                            <span><?= htmlspecialchars($post['category'] ?? 'General') ?></span>
                            <span>|</span>
                            <i data-lucide="calendar" class="w-4 h-4"></i>
                            <span><?= date('Y/m/d', strtotime($post['published_at'] ?? date('Y-m-d'))) ?></span>
                        </div>

                        <div class="flex flex-row justify-center items-start gap-4 p-4 pb-1 mb-2">
                            <?php for ($i = 1; $i <= 2; $i++): ?>
                                <div class="flex flex-col items-center flex-1">
                                    <?php
                                    $basePath = "posts/user_posts/{$post['id']}/image_{$i}";
                                    $ext = file_exists($basePath . ".jpg") ? "jpg" : (file_exists($basePath . ".png") ? "png" : "");
                                    ?>
                                    <div class="aspect-square w-full max-w-[75px] rounded-lg overflow-hidden row-start-1">
                                        <img src="<?= $basePath . '.' . $ext ?>"
                                            alt="<?= htmlspecialchars($post["name$i"]) ?>"
                                            class="w-full h-full object-cover">
                                    </div>

                                    <div class="min-h-[3rem] flex items-center justify-center row-start-2 w-full">
                                        <p class="text-sm text-white text-center line-clamp-2 font_inter w-full px-2">
                                            <?= htmlspecialchars($post["name$i"]) ?>
                                        </p>
                                    </div>

                                    <div class="bg-[#ffffff25] text-white text-center py-1 px-11 rounded-lg flex items-center gap-1">
                                        <i data-lucide="thumbs-up" class="icon w-4 h-4 mb-1"></i>
                                        <span class="count"><?= count($post["votes$i"] ?? []) ?></span>
                                    </div>
                                </div>
                                <?php if ($i == 1): ?>
                                    <div class="text-white font-semibold text-lg mt-[8%] select-none flex items-center justify-center h-full">
                                        OR
                                    </div>

                                    <div class="absolute left-1/2 bottom-[45px] w-[2px] mx-auto">
                                        <div class="h-[200px] bg-gradient-to-b from-transparent via-[#ffffff15] to-transparent mx-auto"></div>
                                    </div>
                                <?php endif; ?>
                            <?php endfor; ?>
                        </div>
                        <div class="flex items-center justify-center border-t-[1px] pt-3 border-[#ffffff15] mx-4 text-right text-white text-sm font-medium mb-3">
                            <?= count($post['comments'] ?? []) ?> Comment
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="w-[100%] h-[150px] bg-[#ffffff05] rounded-[12px] flex items-center justify-center">
                <p class="text-[#ffffff50] text-center">No Post Found</p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        lucide.createIcons();

        const editBtn = document.getElementById('editBio');
        const saveBtn = document.getElementById('saveBio');
        const bioText = document.getElementById('bioText');
        const charCount = document.getElementById('charCount');

        const maxChars = 158;
        const maxLines = 3;

        function setDirection(textarea) {
            const val = textarea.value.trim();
            if (!val) {
                textarea.dir = 'rtl';
                return;
            }
            const firstChar = val[0];
            textarea.dir = firstChar.match(/[A-Za-z0-9]/) ? 'ltr' : 'rtl';
        }

        function updateCharCount() {
            let value = bioText.value;

            if (value.length > maxChars) {
                value = value.slice(0, maxChars);
                bioText.value = value;
            }
            charCount.textContent = `${maxChars - value.length}`;

            const lines = value.split("\n");
            if (lines.length > maxLines) {
                bioText.value = lines.slice(0, maxLines).join("\n");
            }
        }

        bioText.addEventListener('keydown', (e) => {
            const lines = bioText.value.split("\n");
            if (e.key === "Enter" && lines.length >= maxLines) {
                e.preventDefault();
            }
        });

        setDirection(bioText);
        updateCharCount();

        editBtn.addEventListener('click', () => {
            bioText.removeAttribute('readonly');
            bioText.focus();
            editBtn.classList.add('hidden');
            saveBtn.classList.remove('hidden');
        });

        saveBtn.addEventListener('click', () => {
            bioText.setAttribute('readonly', true);
            saveBtn.classList.add('hidden');
            editBtn.classList.remove('hidden');
            setDirection(bioText);
            updateCharCount();
            document.getElementById('bioForm').submit();
        });

        bioText.addEventListener('input', () => {
            setDirection(bioText);
            updateCharCount();
        });

        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.clickable-post').forEach(post => {
                post.addEventListener('click', function(e) {
                    if (e.target.closest('.comment-btn') || e.target.closest('.vote-btn')) {
                        return;
                    }

                    const postId = this.dataset.postId;

                    this.style.transform = 'scale(0.95)';
                    this.style.transition = 'transform 0.2s ease';

                    setTimeout(() => {
                        this.style.transform = 'scale(1)';

                        sessionStorage.setItem('scrollToPost', postId);

                        window.location.href = 'explore.php';
                    }, 200);
                });

                post.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-2px)';
                    this.style.boxShadow = '0 10px 25px rgba(0,0,0,0.2)';
                });

                post.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = 'none';
                });
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            const container = document.getElementById('backgroundContainer');
            const fileInput = document.getElementById('backgroundInput');
            const form = document.getElementById('backgroundForm');

            container.addEventListener('click', () => {
                fileInput.click();
            });

            fileInput.addEventListener('change', () => {
                if (fileInput.files.length > 0) {
                    form.submit();
                }
            });
        });

        document.getElementById('logoutBtn').addEventListener('click', function() {
            const loading = document.getElementById('logoutLoading');

            loading.classList.remove('hidden');

            document.documentElement.style.overflow = 'hidden';
            document.body.style.overflow = 'hidden';
            document.body.style.position = 'fixed';
            document.body.style.width = '100%';
            document.body.style.height = '100%';

            loading.style.pointerEvents = 'all';

            const logoutDelay = 8000 + Math.random() * 4000;

            setTimeout(() => {
                const form = document.getElementById('logoutForm');
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'logout';
                input.value = '1';
                form.appendChild(input);

                form.submit();
            }, logoutDelay);
        });
    </script>

    <?php include "footer-nav.php"; ?>
</body>

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