<?php
require_once "../includes/db.php";
require_once "../includes/functions.php";

$todaysChampion = getTodaysChampion($pdo);
$championId = $todaysChampion['id'];

// Fetch champion stats
$stmt = $pdo->prepare("
    SELECT total_xp, level
    FROM champion_stats
    WHERE champion_id = ?
");
$stmt->execute([$championId]);
$stats = $stmt->fetch();

// Fetch today's habits
$sql = "
    SELECT * FROM habits
    WHERE frequency = 'daily'
       OR (frequency = 'weekly' AND WEEKDAY(CURDATE()) = WEEKDAY(CURDATE()))
       OR (frequency = 'fortnightly' AND (WEEK(CURDATE()) % 2) = (WEEK(created_at) % 2))
       OR (frequency = 'monthly' AND DAY(CURDATE()) = DAY(created_at))
       OR (frequency = 'one_off' AND specific_date = CURDATE())
";
$habits = $pdo->query($sql)->fetchAll();

// Fetch today's completions
$today = date('Y-m-d');
$completedStmt = $pdo->prepare("
    SELECT COUNT(*) AS total
    FROM habit_completions
    WHERE champion_id = ? AND completion_date = ?
");
$completedStmt->execute([$championId, $today]);
$completedToday = $completedStmt->fetchColumn();

// Fetch total bounties completed today
$bountyStmt = $pdo->prepare("
    SELECT COUNT(*) AS total
    FROM habit_completions hc
    JOIN habits h ON h.id = hc.habit_id
    WHERE hc.champion_id = ? AND hc.completion_date = ? AND h.is_bounty = 1
");
$bountyStmt->execute([$championId, $today]);
$bountiesToday = $bountyStmt->fetchColumn();



// Latest 5 items
$latestItems = $pdo->query("
    SELECT title, image_path, rarity
    FROM items
    ORDER BY id DESC
    LIMIT 5
")->fetchAll();

// Depleted items (<20% remaining, only where quantity + max exist)
$depletedStmt = $pdo->query("
    SELECT title, image_path, quantity, quantity_max
    FROM items
    WHERE quantity_max IS NOT NULL 
      AND quantity_max > 0
      AND quantity IS NOT NULL
      AND (quantity / quantity_max) <= 0.2
    ORDER BY (quantity / quantity_max) ASC
");
$depletedItems = $depletedStmt->fetchAll();






?>
<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/app.js"></script>

    <style>
        .dashboard-grid {
            width: 1000px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            color: #eee;
        }

        .card {
            background: #1a1a1f;
            border: 1px solid #444;
            padding: 20px;
            border-radius: 8px;
        }

        .card h2 {
            color: #ffcc66;
            margin-bottom: 10px;
        }

        .champion-card {
            text-align: center;
        }

        .champion-name {
            font-size: 28px;
            color: #ffcc66;
        }

        .champion-class {
            font-size: 18px;
            color: #ccc;
        }

        .xp-bar {
            background: #333;
            border-radius: 6px;
            height: 20px;
            margin-top: 10px;
            overflow: hidden;
        }

        .xp-fill {
            background: #ffcc66;
            height: 100%;
        }

        .habit-item {
            background: #2a2a30;
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 10px;
            border: 1px solid #444;
        }

        .habit-item button {
            margin-top: 10px;
            background: #4caf50;
            border: none;
            padding: 8px 12px;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }

        .habit-item button:hover {
            background: #45a049;
        }

        .bounty-tag {
            background: #7a0000;
            padding: 3px 6px;
            border-radius: 4px;
            font-size: 12px;
            color: #fff;
        }

        .stats-box {
            font-size: 16px;
            line-height: 1.6;
        }

        .mini-calendar {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 4px;
            margin-top: 10px;
        }

        .mini-day {
            background: #2a2a30;
            padding: 6px;
            text-align: center;
            border-radius: 4px;
            border: 1px solid #444;
        }

        .mini-today {
            background: #ffcc66;
            color: #000;
            font-weight: bold;
        }
    </style>
</head>
<body>
<?php include "../includes/menu.php"; ?>
<div class="dashboard-grid">

    <!-- Champion Card -->
    <div class="card champion-card">
        <h2>Today's Champion</h2>
        <div class="champion-name"><?= $todaysChampion['name'] ?></div>
        <div class="champion-class"><?= $todaysChampion['class_name'] ?></div>

        <h3>Level <?= $stats['level'] ?></h3>
        <p><?= number_format($stats['total_xp']) ?> XP</p>

        <?php
        $xpIntoLevel = $stats['total_xp'] % 100;
        $xpPercent = ($xpIntoLevel / 100) * 100;
        ?>
        <div class="xp-bar">
            <div class="xp-fill" style="width: <?= $xpPercent ?>%"></div>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="card stats-box">
        <h2>Quick Stats</h2>
        <p><strong>Habits Today:</strong> <?= count($habits) ?></p>
        <p><strong>Completed Today:</strong> <?= $completedToday ?></p>
        <p><strong>Bounties Completed:</strong> <?= $bountiesToday ?></p>
        <p><strong>Remaining:</strong> <?= count($habits) - $completedToday ?></p>

        <h3 style="margin-top:15px; color:#ffcc66;">Mini Calendar</h3>
        <div class="mini-calendar">
            <?php
            $days = ["S","M","T","W","T","F","S"];
            $todayIndex = date('w');
            foreach ($days as $i => $d) {
                $class = $i == $todayIndex ? "mini-day mini-today" : "mini-day";
                echo "<div class='$class'>$d</div>";
            }
            ?>
        </div>
    </div>










<!-- Latest Items -->
<div class="card">
    <h2>Latest Items</h2>
    <?php if (empty($latestItems)): ?>
        <p>No items yet.</p>
    <?php else: ?>
        <?php foreach ($latestItems as $item): ?>
            <div style="display:flex; align-items:center; gap:8px; margin-bottom:6px;">
                <?php if ($item['image_path']): ?>
                    <img src="../<?= $item['image_path'] ?>" style="width:32px;height:32px;object-fit:cover;">
                <?php endif; ?>
                <span><?= htmlspecialchars($item['title']) ?></span>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Depleted Items -->
<div class="card">
    <h2>Depleted Items (&lt;= 20%)</h2>
    <?php if (empty($depletedItems)): ?>
        <p>Nothing low right now.</p>
    <?php else: ?>
        <?php foreach ($depletedItems as $item): ?>
            <?php
            $percent = round(($item['quantity'] / $item['quantity_max']) * 100);
            ?>
            <div style="display:flex; align-items:center; gap:8px; margin-bottom:6px;">
                <?php if ($item['image_path']): ?>
                    <img src="../<?= $item['image_path'] ?>" style="width:32px;height:32px;object-fit:cover;">
                <?php endif; ?>
                <span><?= htmlspecialchars($item['title']) ?> — <?= $item['quantity'] ?>/<?= $item['quantity_max'] ?> (<?= $percent ?>%)</span>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>









    <!-- Today's Habits -->
    <div class="card" style="grid-column: span 2;">
        <h2>Today's Habits & Bounties</h2>

        <?php if (empty($habits)): ?>
            <p>No habits today.</p>
        <?php else: ?>
            <?php foreach ($habits as $habit): ?>
                <div class="habit-item" id="habit-<?= $habit['id'] ?>">
                    <strong><?= htmlspecialchars($habit['title']) ?></strong>

                    <?php if ($habit['is_bounty']): ?>
                        <span class="bounty-tag">BOUNTY</span>
                    <?php endif; ?>

                    <p><?= htmlspecialchars($habit['description']) ?></p>

                    <button onclick="completeHabit(<?= $habit['id'] ?>)">Complete</button>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

</div>

</body>
</html>