<?php
/**
 * VMO Initial-Setup Discount Policy.
 *
 * Founder-confirmed June 3 2026:
 *  - EVERY plan (Tester → Enterprise, Direct & QL) gets the IDENTICAL full
 *    premium website build (the ~18-agent generate_website_premium operation).
 *    Quality is NEVER tier-gated.
 *  - The premium build's true list price is ~$31.20 (~46,777 tokens) at the
 *    standard 12× markup. To keep onboarding affordable WITHOUT raising plan
 *    prices, the FIRST (initial) run of each subsidized setup operation is
 *    charged a one-time BONUS-discounted price (the legacy generate_website
 *    rate, ~$8.40 / 12,594 tokens). VMO absorbs only the real provider-cost
 *    delta (~$1.90 cash), once, amortized against recurring revenue.
 *  - After initial setup completes, the discount is GONE: any RERUN of a
 *    subsidized op pays the FULL catalog price and the UI must warn the user
 *    of the token cost vs their balance BEFORE charging.
 *
 * This file is the single source of truth for: which ops are setup-subsidized,
 * the discounted price, and whether a given user has used up their one-time
 * setup discount.
 *
 * @package VMO_AI_Website_Builder
 * @since   1.0.61
 */

if (!defined('ABSPATH')) exit;

require_once __DIR__ . '/vmo-operation-catalog.php';

if (!defined('VMO_INITIAL_SETUP_DONE_META')) {
    define('VMO_INITIAL_SETUP_DONE_META', 'vmo_initial_setup_completed');
}
if (!defined('VMO_INITIAL_SETUP_DONE_AT_META')) {
    define('VMO_INITIAL_SETUP_DONE_AT_META', 'vmo_initial_setup_completed_at');
}

if (!function_exists('vmo_initial_setup_discount_map')) {
    /**
     * Map of setup-subsidized operation keys → the one-time discounted token
     * charge applied on a user's FIRST setup run only.
     *
     * The premium website build is discounted down to the legacy
     * generate_website charge so the user perceives a large bonus while VMO
     * absorbs only the small provider-cost delta. Add other heavily-subsidized
     * onboarding ops here as needed (kept intentionally tight for now).
     *
     * @return array<string,int> operation_key => discounted_token_cost
     */
    function vmo_initial_setup_discount_map() {
        // Anchor the premium build's discounted price to the legacy
        // generate_website token cost so it tracks the catalog automatically.
        $legacy_website_tokens = function_exists('vmo_catalog_get_token_cost')
            ? (int) vmo_catalog_get_token_cost('generate_website')
            : 12594;
        if ($legacy_website_tokens <= 0) {
            $legacy_website_tokens = 12594;
        }

        $map = [
            'generate_website_premium'   => $legacy_website_tokens,
            'website_generation_premium' => $legacy_website_tokens,
        ];

        return apply_filters('vmo_initial_setup_discount_map', $map);
    }
}

if (!function_exists('vmo_op_is_setup_discountable')) {
    /**
     * Is this operation eligible for the one-time initial-setup discount at all?
     */
    function vmo_op_is_setup_discountable($operation_key) {
        $map = vmo_initial_setup_discount_map();
        return isset($map[$operation_key]);
    }
}

if (!function_exists('vmo_user_initial_setup_completed')) {
    /**
     * Has this user already consumed their one-time initial-setup discount?
     */
    function vmo_user_initial_setup_completed($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) {
            return false;
        }
        $done = get_user_meta($user_id, VMO_INITIAL_SETUP_DONE_META, true);
        $done = (bool) apply_filters('vmo_user_initial_setup_completed', (bool) $done, $user_id);
        return $done;
    }
}

if (!function_exists('vmo_mark_initial_setup_completed')) {
    /**
     * Mark a user's one-time initial-setup discount as consumed. Idempotent:
     * the first call records the timestamp; later calls are no-ops.
     *
     * @return bool true if this call flipped the flag, false if already set.
     */
    function vmo_mark_initial_setup_completed($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) {
            return false;
        }
        if (vmo_user_initial_setup_completed($user_id)) {
            return false;
        }
        update_user_meta($user_id, VMO_INITIAL_SETUP_DONE_META, 1);
        update_user_meta($user_id, VMO_INITIAL_SETUP_DONE_AT_META, current_time('mysql'));
        do_action('vmo_initial_setup_completed', $user_id);
        return true;
    }
}

if (!function_exists('vmo_op_is_discounted_now')) {
    /**
     * Will this specific operation be discounted for this user RIGHT NOW?
     * True only when the op is setup-discountable AND the user has not yet
     * consumed their one-time setup discount.
     */
    function vmo_op_is_discounted_now($user_id, $operation_key) {
        if (!vmo_op_is_setup_discountable($operation_key)) {
            return false;
        }
        return !vmo_user_initial_setup_completed($user_id);
    }
}

if (!function_exists('vmo_get_effective_token_cost')) {
    /**
     * Token cost the user will actually be charged for an operation, honoring
     * the one-time initial-setup discount. Falls back to the full catalog cost
     * for non-discountable ops or once the setup discount is spent.
     */
    function vmo_get_effective_token_cost($user_id, $operation_key) {
        $full = function_exists('vmo_get_token_cost')
            ? (int) vmo_get_token_cost($operation_key)
            : 0;

        if (vmo_op_is_discounted_now($user_id, $operation_key)) {
            $map = vmo_initial_setup_discount_map();
            $discounted = (int) ($map[$operation_key] ?? $full);
            // Never let a "discount" exceed the real price.
            return min($discounted, $full > 0 ? $full : $discounted);
        }

        return $full;
    }
}

if (!function_exists('vmo_get_operation_charge_breakdown')) {
    /**
     * Full pricing breakdown for an operation for a given user — used by the
     * rerun-warning modal and any pre-charge confirmation UI.
     *
     * @return array{
     *   operation:string, is_discountable:bool, is_discounted_now:bool,
     *   full_tokens:int, charged_tokens:int, discount_tokens:int,
     *   full_usd:float, charged_usd:float, balance_tokens:int,
     *   sufficient:bool, setup_completed:bool
     * }
     */
    function vmo_get_operation_charge_breakdown($user_id, $operation_key) {
        $user_id = (int) $user_id;

        $full_tokens = function_exists('vmo_get_token_cost')
            ? (int) vmo_get_token_cost($operation_key)
            : 0;
        $charged_tokens = vmo_get_effective_token_cost($user_id, $operation_key);
        $discount_tokens = max(0, $full_tokens - $charged_tokens);

        $rate = defined('VMO_TOKEN_RATE') ? (float) VMO_TOKEN_RATE : 0.000667;

        $balance = function_exists('vmo_get_token_balance')
            ? (int) vmo_get_token_balance($user_id)
            : 0;

        return [
            'operation'          => (string) $operation_key,
            'is_discountable'    => vmo_op_is_setup_discountable($operation_key),
            'is_discounted_now'  => vmo_op_is_discounted_now($user_id, $operation_key),
            'full_tokens'        => $full_tokens,
            'charged_tokens'     => $charged_tokens,
            'discount_tokens'    => $discount_tokens,
            'full_usd'           => round($full_tokens * $rate, 2),
            'charged_usd'        => round($charged_tokens * $rate, 2),
            'balance_tokens'     => $balance,
            'sufficient'         => $balance >= $charged_tokens,
            'setup_completed'    => vmo_user_initial_setup_completed($user_id),
        ];
    }
}

if (!function_exists('vmo_deduct_setup_operation')) {
    /**
     * Charge a setup-aware operation: applies the one-time discount on the
     * first run, full catalog price thereafter. Does NOT mark setup complete —
     * callers should call vmo_mark_initial_setup_completed() only AFTER the
     * operation succeeds, so a failed/partial run does not burn the discount.
     *
     * @return bool true if the charge succeeded (or was free), false if the
     *              user had insufficient tokens.
     */
    function vmo_deduct_setup_operation($user_id, $operation_key, $description = '') {
        $user_id = (int) $user_id;
        $cost = vmo_get_effective_token_cost($user_id, $operation_key);

        if ($cost <= 0) {
            return true;
        }
        if (!function_exists('vmo_deduct_tokens')) {
            return true;
        }

        if ($description === '') {
            $description = vmo_op_is_discounted_now($user_id, $operation_key)
                ? 'Initial setup (one-time bonus pricing): ' . $operation_key
                : $operation_key;
        }

        return (bool) vmo_deduct_tokens($user_id, $cost, $operation_key, $description);
    }
}
