<?php
include_once __DIR__ . "/../db.php";

/**
 * Return a user's current credit balance.
 * If the user has no row in `users`, insert one and award the signup bonus.
 */
function getUserCredits($chat_id) {
    global $pdo, $config;

    $stmt = $pdo->prepare("SELECT credits FROM users WHERE chat_id = ?");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row === false) {
        $bonus = $config['signup_credits'] ?? 20;
        $pdo->prepare("INSERT INTO users (chat_id, credits) VALUES (?, ?) ON DUPLICATE KEY UPDATE chat_id = chat_id")
            ->execute([$chat_id, $bonus]);
        logCreditTransaction($chat_id, $bonus, 'signup_bonus', 'Welcome bonus');
        return $bonus;
    }

    return (int)($row['credits'] ?? 0);
}

/**
 * Deduct credits from a user after a successful plan generation.
 */
function deductCredits($chat_id, $amount, $description = '') {
    global $pdo;
    $pdo->prepare("UPDATE users SET credits = GREATEST(0, credits - ?) WHERE chat_id = ?")
        ->execute([$amount, $chat_id]);
    logCreditTransaction($chat_id, -$amount, 'plan_generation', $description);
}

/**
 * Add credits to a user (manual top-up or admin grant).
 */
function addCredits($chat_id, $amount, $type = 'manual_topup', $description = '') {
    global $pdo;
    $pdo->prepare("UPDATE users SET credits = credits + ? WHERE chat_id = ?")
        ->execute([$amount, $chat_id]);
    logCreditTransaction($chat_id, $amount, $type, $description);
}

/**
 * Log a credit transaction for auditing.
 */
function logCreditTransaction($chat_id, $amount, $type, $description = '') {
    global $pdo;
    $pdo->prepare("INSERT INTO credit_transactions (chat_id, amount, type, description) VALUES (?, ?, ?, ?)")
        ->execute([$chat_id, $amount, $type, $description]);
}

/**
 * Read a value from the settings table.
 */
function getSetting($key, $default = null) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT `value` FROM settings WHERE `key` = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? $row['value'] : $default;
}

function getSettingInt($key, $default = 0) {
    return (int)getSetting($key, $default);
}

/**
 * Upsert a value in the settings table.
 */
function setSetting($key, $value) {
    global $pdo;
    $pdo->prepare("INSERT INTO settings (`key`, `value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `value` = ?")
        ->execute([$key, $value, $value]);
}

/**
 * Calculate actual credit cost for a diet plan based on its complexity.
 * Base cost comes from the DB setting; surcharge for larger plans.
 */
function calculateDietPlanCredits($planJson) {
    $base      = getSettingInt('diet_plan_cost', 10);
    $mealCount = count($planJson['meals'] ?? []);
    $itemCount = array_sum(array_map(fn($m) => count($m['items'] ?? []), $planJson['meals'] ?? []));
    if ($mealCount >= 6 && $itemCount >= 20) return $base + 5;
    if ($mealCount >= 5 && $itemCount >= 15) return $base + 2;
    return $base;
}

/**
 * Calculate actual credit cost for a workout plan based on its complexity.
 * Base cost comes from the DB setting; surcharge for denser plans.
 */
function calculateWorkoutPlanCredits($planJson) {
    $base          = getSettingInt('workout_plan_cost', 20);
    $dayCount      = count($planJson['schedule'] ?? []);
    $exerciseCount = array_sum(array_map(fn($d) => count($d['exercises'] ?? []), $planJson['schedule'] ?? []));
    if ($dayCount >= 5 && $exerciseCount >= 25) return $base + 8;
    if ($dayCount >= 4 && $exerciseCount >= 15) return $base + 3;
    return $base;
}

/**
 * Send the "not enough credits" message with a Contact to Refill button.
 */
function sendInsufficientCreditsMessage($chat_id, $needed, $current) {
    global $config;
    $support      = ltrim($config['support_username'] ?? '', '@');
    $rupeePerCredit = getSettingInt('rupee_per_credit', 1);
    $keyboard = [
        "inline_keyboard" => [
            [["text" => "💬 Contact to Refill Credits", "url" => "https://t.me/{$support}"]],
            [["text" => "📊 My Status",  "callback_data" => "view_status"],
             ["text" => "🏠 Main Menu",  "callback_data" => "main_menu"]],
        ]
    ];
    $msg  = "💳 <b>Not Enough Credits</b>\n\n";
    $msg .= "This action costs <b>{$needed} credit" . ($needed > 1 ? 's' : '') . "</b>.\n";
    $msg .= "Your balance: <b>{$current} credit" . ($current !== 1 ? 's' : '') . "</b>\n\n";
    $msg .= "💱 Rate: <b>₹{$rupeePerCredit} = 1 Credit</b>\n\n";
    $msg .= "👉 Contact <b>@{$support}</b> on Telegram to top up your credits.";
    sendMessage($chat_id, $msg, $keyboard);
}

/**
 * Send a confirmation after a plan is generated showing credits spent and remaining.
 */
function sendCreditDeductedNotice($chat_id, $spent, $remaining) {
    sendMessage($chat_id, "💳 <b>{$spent} credit" . ($spent > 1 ? 's' : '') . " used</b> · Balance: <b>{$remaining} remaining</b>");
}
