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

if (!isset($_GET['id'])) {
    die("Champion ID missing.");
}

$champion_id = intval($_GET['id']);

// Fetch champion info
$stmt = $pdo->prepare("
    SELECT c.*, cs.total_xp, cs.level
    FROM champions c
    LEFT JOIN champion_stats cs ON cs.champion_id = c.id
    WHERE c.id = ?
");
$stmt->execute([$champion_id]);
$champion = $stmt->fetch();

if (!$champion) {
    die("Champion not found.");
}

// Fetch XP progression (group by date)
$xpStmt = $pdo->prepare("
    SELECT completion_date, SUM(xp_earned) AS xp
    FROM habit_completions
    WHERE champion_id = ?
    GROUP BY completion_date
    ORDER BY completion_date ASC
");
$xpStmt->execute([$champion_id]);
$xpData = $xpStmt->fetchAll();

// Fetch recent completions
$recentStmt = $pdo->prepare("
    SELECT 
        hc.completion_date,
        h.title,
        h.frequency,
        h.is_bounty,
        hc.xp_earned
    FROM habit_completions hc
    JOIN habits h ON h.id = hc.habit_id
    WHERE hc.champion_id = ?
    ORDER BY hc.completion_date DESC
    LIMIT 20
");
$recentStmt->execute([$champion_id]);
$recent = $recentStmt->fetchAll();

// Breakdown stats
$breakdownStmt = $pdo->prepare("
    SELECT 
        h.frequency,
        h.is_bounty,
        COUNT(*) AS total
    FROM habit_completions hc
    JOIN habits h ON h.id = hc.habit_id
    WHERE hc.champion_id = ?
    GROUP BY h.frequency, h.is_bounty
");
$breakdownStmt->execute([$champion_id]);
$breakdown = $breakdownStmt->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $champion['name'] ?> — Champion Detail</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        .detail-container {
            width: 900px;
            margin: 0 auto;
            color: #eee;
        }

        .champion-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .champion-header h1 {
            color: #ffcc66;
        }

        .stats-box {
            background: #1a1a1f;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #444;
            margin-bottom: 25px;
        }

        .recent-table {
            width: 100%;
            border-collapse: collapse;
            background: #1a1a1f;
            border: 1px solid #444;
        }

        .recent-table th, .recent-table td {
            padding: 10px;
            border-bottom: 1px solid #333;
        }

        .recent-table th {
            background: #2a2a30;
            color: #ffcc66;
        }

        .bounty {
            color: #ff6666;
            font-weight: bold;
        }
    </style>
</head>
<body>

<div class="detail-container">

    <div class="champion-header">
        <h1><?= $champion['name'] ?> (<?= $champion['class_name'] ?>)</h1>
        <h3>Day: <?= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][$champion['day_of_week']] ?></h3>
        <h3>Level <?= $champion['level'] ?> — <?= number_format($champion['total_xp']) ?> XP</h3>
    </div>

    <!-- XP Chart -->
    <div class="stats-box">
        <h2 style="color:#ffcc66;">XP Progression</h2>
        <canvas id="xpChart"></canvas>
    </div>

    <!-- Breakdown -->
    <div class="stats-box">
        <h2 style="color:#ffcc66;">Completion Breakdown</h2>
        <?php if (empty($breakdown)): ?>
            <p>No completions yet.</p>
        <?php else: ?>
            <ul>
                <?php foreach ($breakdown as $row): ?>
                    <li>
                        <?= ucfirst($row['frequency']) ?>
                        <?= $row['is_bounty'] ? "(Bounty)" : "" ?>:
                        <strong><?= $row['total'] ?></strong>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>

    <!-- Recent Completions -->
    <div class="stats-box">
        <h2 style="color:#ffcc66;">Recent Completions</h2>

        <?php if (empty($recent)): ?>
            <p>No completions yet.</p>
        <?php else: ?>
            <table class="recent-table">
                <tr>
                    <th>Date</th>
                    <th>Habit</th>
                    <th>Type</th>
                    <th>XP</th>
                </tr>

                <?php foreach ($recent as $row): ?>
                    <tr>
                        <td><?= $row['completion_date'] ?></td>
                        <td><?= htmlspecialchars($row['title']) ?></td>
                        <td>
                            <?= ucfirst($row['frequency']) ?>
                            <?php if ($row['is_bounty']): ?>
                                <span class="bounty">Bounty</span>
                            <?php endif; ?>
                        </td>
                        <td><?= $row['xp_earned'] ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>

</div>

<script>
const ctx = document.getElementById('xpChart').getContext('2d');

const xpChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [
            <?php foreach ($xpData as $row) echo "'" . $row['completion_date'] . "',"; ?>
        ],
        datasets: [{
            label: 'XP Earned',
            data: [
                <?php foreach ($xpData as $row) echo $row['xp'] . ","; ?>
            ],
            borderColor: '#ffcc66',
            backgroundColor: 'rgba(255, 204, 102, 0.2)',
            borderWidth: 2,
            tension: 0.3,
            fill: true
        }]
    },
    options: {
        scales: {
            y: {
                ticks: { color: '#eee' },
                beginAtZero: true
            },
            x: {
                ticks: { color: '#eee' }
            }
        },
        plugins: {
            legend: { labels: { color: '#eee' } }
        }
    }
});
</script>

</body>
</html>