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

header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["error" => "Invalid request"]);
    exit;
}

$habit_id = $_POST['habit_id'] ?? null;

if (!$habit_id) {
    echo json_encode(["error" => "Missing habit_id"]);
    exit;
}

// Get habit info
$stmt = $pdo->prepare("SELECT * FROM habits WHERE id = ?");
$stmt->execute([$habit_id]);
$habit = $stmt->fetch();

if (!$habit) {
    echo json_encode(["error" => "Habit not found"]);
    exit;
}

// Get today's champion
$champion = getTodaysChampion($pdo);

// Calculate XP
$xp = calculateXP($habit['frequency'], $habit['is_bounty']);

// Insert completion record
$stmt = $pdo->prepare("
    INSERT INTO habit_completions (habit_id, champion_id, completion_date, xp_earned)
    VALUES (?, ?, CURDATE(), ?)
");
$stmt->execute([$habit_id, $champion['id'], $xp]);

// Add XP to champion stats
addXP($pdo, $champion['id'], $xp);

echo json_encode([
    "success" => true,
    "xp" => $xp,
    "champion" => $champion['name']
]);