<?php
session_start();
require_once "config.php"; // $db

// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id  = (int)$_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'User';

// Pull fresh is_admin from DB in case you changed it in phpMyAdmin
$stmt = $db->prepare("SELECT is_admin FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($is_admin);
$stmt->fetch();
$stmt->close();
$is_admin = (int)$is_admin;

// ---------- STATS ----------
$stats = [
    "total_uploads"    => 0,
    "total_received"   => 0,
    "avg_rating"       => 0,
    "collection_count" => 0
];

// Total uploads
$res = $db->query("SELECT COUNT(*) AS c FROM images WHERE user_id = {$user_id}");
$stats["total_uploads"] = (int)($res->fetch_assoc()["c"] ?? 0);

// Total received
$res = $db->query("SELECT COUNT(*) AS c FROM received_images WHERE user_id = {$user_id}");
$stats["total_received"] = (int)($res->fetch_assoc()["c"] ?? 0);

// Average rating given
$res = $db->query("SELECT AVG(rating) AS avg_rating FROM ratings WHERE user_id = {$user_id}");
$row = $res->fetch_assoc();
$stats["avg_rating"] = $row && $row["avg_rating"] !== null ? round($row["avg_rating"], 1) : 0;

// Collection count
$res = $db->query("SELECT COUNT(*) AS c FROM collections WHERE user_id = {$user_id}");
$stats["collection_count"] = (int)($res->fetch_assoc()["c"] ?? 0);

// ---------- COLLECTION ----------
$collection = [];
$res = $db->query("
    SELECT c.slot_number, i.id, i.filename
    FROM collections c
    JOIN images i ON c.image_id = i.id
    WHERE c.user_id = {$user_id}
    ORDER BY c.slot_number ASC
");
while ($row = $res->fetch_assoc()) {
    $collection[(int)$row["slot_number"]] = $row;
}

// ---------- RECEIVED IMAGES ----------
$received = [];
$res = $db->query("
    SELECT 
        i.id,
        i.filename,
        i.hidden_username,
        i.age_days,
        i.disabled,
        (SELECT AVG(rating) FROM ratings WHERE image_id = i.id) AS avg_rating,
        (SELECT COUNT(*) FROM collections WHERE image_id = i.id) AS collection_count,
        (SELECT tag_text FROM tags WHERE image_id = i.id AND user_id = {$user_id} LIMIT 1) AS my_tag,
        (SELECT rating FROM ratings WHERE image_id = i.id AND user_id = {$user_id} LIMIT 1) AS my_rating,
        (SELECT username FROM users WHERE id = i.user_id) AS owner_username
    FROM received_images r
    JOIN images i ON r.image_id = i.id
    WHERE r.user_id = {$user_id}
    ORDER BY r.received_at DESC
");
while ($row = $res->fetch_assoc()) {
    $received[] = $row;
}

// JSON for JS
$collection_json = json_encode($collection);
$received_json   = json_encode($received);
$stats_json      = json_encode($stats);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TitZ · CatZ · ToeZ</title>
<script src="https://cdn.tailwindcss.com"></script>

<script src="js/upload.js"></script>
<script src="js/receive.js"></script>
<script src="js/rate.js"></script>
<script src="js/tag.js"></script>
<script src="js/collection.js"></script>
<script src="js/admin.js"></script>

<style>
/* You can drop your custom CSS here if you had any */
body { background: #020617; color: #e5e7eb; }
</style>
</head>

<body class="min-h-screen pb-24 md:pb-0">

<header class="sticky top-0 z-40 bg-black/80 backdrop-blur-md border-b border-pink-500/30">
    <div class="max-w-6xl mx-auto px-4 py-3 flex justify-between items-center">
        <h1 class="text-2xl md:text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-pink-500 via-purple-500 to-cyan-500 cursor-pointer"
            onclick="showSection('home')">
            TitZ · CatZ · ToeZ
        </h1>

        <div class="flex items-center gap-3">
            <?php if ($is_admin === 1): ?>
            <button onclick="toggleAdmin()" class="hidden md:block px-3 py-1 bg-red-600/20 border border-red-500/50 rounded text-xs text-red-400 hover:bg-red-600/40">
                Admin
            </button>
            <?php endif; ?>

            <div class="flex flex-col items-end">
                <span class="text-xs text-gray-400">Daily Uploads</span>
                <span class="text-lg font-bold text-pink-400" id="uploadCounter">0/3</span>
            </div>

            <button onclick="showSection('profile')" class="w-10 h-10 rounded-full bg-gradient-to-br from-pink-500 to-purple-600 flex items-center justify-center text-sm font-bold border-2 border-white/20">
                ME
            </button>
        </div>
    </div>
</header>

<main class="max-w-6xl mx-auto px-4 py-6 space-y-6">

    <!-- HOME -->
    <section id="home" class="space-y-6">

        <!-- Upload -->
        <div class="bg-gray-900/50 border border-cyan-500/30 rounded-2xl p-6">
            <h2 class="text-xl font-bold mb-4 text-cyan-400 flex items-center gap-2">
                <span class="text-2xl">📤</span> Upload Your NFT
            </h2>

            <div id="uploadContainer" class="space-y-4">
                <div class="rounded-xl p-8 text-center cursor-pointer border border-dashed border-gray-600"
                     onclick="document.getElementById('fileInput').click()">
                    <input type="file" id="fileInput" class="hidden" accept="image/*" multiple>
                    <div class="text-5xl mb-3">🖼️</div>
                    <p class="text-lg font-semibold mb-2">Drop images here or click to upload</p>
                    <p class="text-sm text-gray-400">Max 3 per day • JPG, PNG, GIF</p>
                </div>

                <div id="uploadPreview" class="hidden space-y-3">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3" id="previewGrid"></div>

                    <div class="flex gap-3">
                        <input type="text" id="uploadTag" placeholder="Enter tag for all uploads..."
                               class="flex-1 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm">
                        <button onclick="submitUploads()" class="px-6 py-2 bg-pink-600 hover:bg-pink-500 rounded-lg font-bold transition">
                            UPLOAD & RECEIVE
                        </button>
                    </div>

                    <label class="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
                        <input type="checkbox" id="hideUsername" class="w-4 h-4 rounded border-gray-600 text-pink-600">
                        <span>Hide my username permanently (cannot be undone)</span>
                    </label>
                </div>
            </div>

            <div id="cooldownMessage" class="hidden text-center py-8">
                <div class="text-6xl mb-4">⏰</div>
                <h3 class="text-xl font-bold text-yellow-400 mb-2">Daily Limit Reached</h3>
                <p class="text-gray-400 mb-4">Come back tomorrow for more uploads!</p>
                <div class="text-2xl font-mono text-cyan-400" id="countdownTimer">23:59:59</div>
            </div>
        </div>

        <!-- Received -->
        <div class="bg-gray-900/50 border border-pink-500/30 rounded-2xl p-6">
            <h2 class="text-xl font-bold mb-4 text-pink-400 flex items-center gap-2">
                <span class="text-2xl">🎁</span> Your Received NFTs
            </h2>

            <div id="receivedGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <!-- JS will render RECEIVED here -->
            </div>
        </div>

    </section>

    <!-- COLLECTION -->
    <section id="collection" class="hidden space-y-6">
        <div class="bg-gray-900/50 border border-green-500/30 rounded-2xl p-6">
            <h2 class="text-xl font-bold mb-4 text-green-400 flex items-center gap-2">
                <span class="text-2xl">💎</span> Your NFT Collection (Max 5)
            </h2>

            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6" id="collectionGrid">
                <!-- JS will render COLLECTION here -->
            </div>
        </div>
    </section>

    <!-- PROFILE -->
    <section id="profile" class="hidden space-y-6">
        <div class="bg-gray-900/50 border border-purple-500/30 rounded-2xl p-6">

            <div class="flex items-center gap-4 mb-6">
                <div class="w-20 h-20 rounded-full bg-gradient-to-br from-pink-500 to-purple-600 flex items-center justify-center text-3xl font-bold border-4 border-white/20">
                    ME
                </div>
                <div>
                    <h2 class="text-2xl font-bold"><?= htmlspecialchars($username) ?></h2>
                    <p class="text-gray-400 text-sm">Member</p>
                </div>
            </div>

            <div class="grid grid-cols-2 gap-4 mb-6">
                <div class="bg-gray-800/50 rounded-lg p-4 text-center">
                    <div class="text-3xl font-bold text-pink-400" id="totalUploads"><?= $stats["total_uploads"] ?></div>
                    <div class="text-xs text-gray-400">Total Uploads</div>
                </div>

                <div class="bg-gray-800/50 rounded-lg p-4 text-center">
                    <div class="text-3xl font-bold text-cyan-400" id="totalReceived"><?= $stats["total_received"] ?></div>
                    <div class="text-xs text-gray-400">Total Received</div>
                </div>

                <div class="bg-gray-800/50 rounded-lg p-4 text-center">
                    <div class="text-3xl font-bold text-yellow-400" id="avgRating"><?= $stats["avg_rating"] ?></div>
                    <div class="text-xs text-gray-400">Your Avg Rating</div>
                </div>

                <div class="bg-gray-800/50 rounded-lg p-4 text-center">
                    <div class="text-3xl font-bold text-green-400" id="collectionCount"><?= $stats["collection_count"] ?>/5</div>
                    <div class="text-xs text-gray-400">Collection</div>
                </div>
            </div>

            <a href="logout.php" class="block w-full text-center py-3 bg-red-600/20 border border-red-500/50 text-red-400 rounded-lg hover:bg-red-600/40 transition text-sm">
                Logout
            </a>
        </div>
    </section>

</main>

<?php if ($is_admin === 1): ?>
<div id="adminPanel" class="fixed bottom-0 right-0 m-4 bg-gray-900 border border-red-500/40 rounded-lg p-4 hidden">
    <!-- Admin UI will be handled by admin.js -->
    <p class="text-sm text-red-300">Admin Panel</p>
</div>
<?php endif; ?>

<div id="replaceModal" class="hidden"></div>
<div id="toast" class="hidden"></div>

<script>
const RECEIVED   = <?= $received_json ?>;
const COLLECTION = <?= $collection_json ?>;
const STATS      = <?= $stats_json ?>;

function showSection(id) {
    ["home", "collection", "profile"].forEach(sec => {
        document.getElementById(sec).classList.add("hidden");
    });
    document.getElementById(id).classList.remove("hidden");
}

// Here you’d call your JS renderers if you’ve built them:
// renderReceived(RECEIVED);
// renderCollection(COLLECTION);
// updateProfile(STATS);
</script>

</body>
</html>