<?php
require_once "../includes/config.php";

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

// Validate habit ID
if (!isset($_POST['habit_id'])) {
    echo json_encode(["status" => "error", "message" => "Missing habit ID"]);
    exit;
}

$habitId = intval($_POST['habit_id']);
$today   = date('Y-m-d');

// Get today's champion
$todaysChampion = getTodaysChampion($pdo);
$championId     = $todaysChampion['id'];

// Fetch habit details
$stmt = $pdo->prepare("
    SELECT id, title, xp_reward, linked_item_id, consume_amount
    FROM habits
    WHERE id = ?
");
$stmt->execute([$habitId]);
$habit = $stmt->fetch();

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

$xpReward      = (int)$habit['xp_reward'];
$linkedItemId  = $habit['linked_item_id'];
$consumeAmount = $habit['consume_amount'];

// ------------------------------------------------------------
// INSERT COMPLETION RECORD
// ------------------------------------------------------------
$insert = $pdo->prepare("
    INSERT INTO habit_completions (habit_id, champion_id, completion_date, xp_earned)
    VALUES (?, ?, ?, ?)
");
$insert->execute([$habitId, $championId, $today, $xpReward]);

// ------------------------------------------------------------
// UPDATE CHAMPION XP
// ------------------------------------------------------------
$updateXP = $pdo->prepare("
    UPDATE champion_stats
    SET total_xp = total_xp + ?
    WHERE champion_id = ?
");
$updateXP->execute([$xpReward, $championId]);

// ------------------------------------------------------------
// OPTIONAL: CONSUME ITEM
// ------------------------------------------------------------
$lowStockTriggered = false;
$remainingQty      = null;

if (!empty($linkedItemId) && !empty($consumeAmount)) {

    // Fetch item
    $itemStmt = $pdo->prepare("
        SELECT id, title, quantity, quantity_max
        FROM items
        WHERE id = ?
    ");
    $itemStmt->execute([$linkedItemId]);
    $item = $itemStmt->fetch();

    if ($item) {
        $newQty = max(0, (int)$item['quantity'] - $consumeAmount);

        // Update quantity
        $updateItem = $pdo->prepare("
            UPDATE items
            SET quantity = ?
            WHERE id = ?
        ");
        $updateItem->execute([$newQty, $linkedItemId]);

        $remainingQty = $newQty;

        // LOW STOCK CHECK
        $percent = null;
        if (!empty($item['quantity_max']) && $item['quantity_max'] > 0) {
            $percent = ($newQty / $item['quantity_max']) * 100;
        }

        if (
            $newQty <= $GLOBALS['LOW_STOCK_ABSOLUTE'] ||
            (!is_null($percent) && $percent <= $GLOBALS['LOW_STOCK_PERCENT'])
        ) {
            $lowStockTriggered = true;

            // (Email sending can be added later)
        }
    }
}

// ------------------------------------------------------------
// RESPONSE
// ------------------------------------------------------------
echo json_encode([
    "status" => "success",
    "xp_gained" => $xpReward,
    "remaining_quantity" => $remainingQty,
    "low_stock" => $lowStockTriggered
]);

exit;
?>