<?php
session_start();

$targetUserId = $_GET['user_id'] ?? '';

if (!$targetUserId) {
    header("Location: explore.php");
    exit;
}

if (isset($_SESSION['user_id']) && $_SESSION['user_id'] === $targetUserId) {
    header("Location: profile.php");
    exit;
}

$targetUserDir = __DIR__ . "/users/$targetUserId";
$targetUserWebDir = "users/$targetUserId";

$dataFile = "$targetUserDir/data.json";
if (!file_exists($dataFile)) {
    header("Location: explore.php");
    exit;
}

$data = json_decode(file_get_contents($dataFile), true);


$target_display_name = $data['displayname'] ?? '';
$targetUsername = $data['username'] ?? '';
$age = $data['age'] ?? '';
$registered = $data['registered'] ?? '';

$profilePic = "images/default-avatar.png";
$imgJpg = "$targetUserDir/profile.jpg";
$imgPng = "$targetUserDir/profile.png";

if (file_exists($imgJpg)) $profilePic = "$targetUserWebDir/profile.jpg";
if (file_exists($imgPng)) $profilePic = "$targetUserWebDir/profile.png";

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

$votesCount = 0;
$commentsCount = 0;

$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'] ?? '') === $targetUserId &&
                ($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;

                if (in_array($targetUserId, $postData['votes1'] ?? [])) $votesCount++;
                if (in_array($targetUserId, $postData['votes2'] ?? [])) $votesCount++;

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

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

$userPostsCount = count($userPosts);

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

?>

<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 <?= htmlspecialchars($targetUsername) ?></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"><?= htmlspecialchars($targetUsername) ?></p>
                <span class="text-[13px] text-[#ffffff50]">
                    <span class="text-[15px] text-[#ffffff25]"># </span><?= htmlspecialchars($targetUsername) ?>
                </span>
            </div>

            <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 class="relative w-full h-[150px] 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; ?>
            </div>

            <div class="absolute right-6 bottom-[-45px]">
                <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>
            </div>
        </div>
    </div>

    <div class="mt-[60px] px-4 relative">
        <div class="relative text-right mb-5">
            <textarea 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>
        </div>

        <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">هیچ مقایسه‌ای ثبت نکرده‌ اید</p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        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';
                });
            });
        });
    </script>

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

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