<?php
/**
 * wallet_lib.php
 * Wallet balance + commission logic, shared by:
 *   - the automatic FamPay success resolver (includes/fampay_order_resolver.php)
 *   - the manual Admin/User "Action" status-change endpoint (auth/update_order_status.php)
 *   - the Wallet page itself (auth/wallet.php) for balance/history display
 *   - the Add Funds flow (auth/lib/wallet_pay.php + auth/lib/wallet_callback.php)
 *
 * Commission is only ever deducted from deduct_commission_on_success() -
 * callers must only call this AFTER an order has actually been confirmed
 * SUCCESS (never on Pending/Failed - that's the caller's responsibility,
 * this function doesn't re-check order status itself).
 */

function get_commission_settings($conn) {
    $result = $conn->query("SELECT commission_type, commission_value FROM site_settings LIMIT 1");
    $row = $result ? $result->fetch_assoc() : null;
    return [
        'type'  => $row['commission_type'] ?? 'percent',
        'value' => (float)($row['commission_value'] ?? 0),
    ];
}

function calculate_commission($amount, $settings) {
    if ($settings['type'] === 'fixed') {
        return round($settings['value'], 2);
    }
    // percent
    return round(((float)$amount) * $settings['value'] / 100, 2);
}

/**
 * Deducts commission from a merchant's wallet for one successful order.
 * Safe to call even if commission_value is 0 (just logs a ₹0 entry) so the
 * transaction history stays complete. Wallet is allowed to go negative -
 * this only records the debt, it does not block anything by itself (see
 * note in auth/wallet.php about enforcing a hold if you want that later).
 *
 * If the wallet migration hasn't been run yet (columns missing), this
 * quietly does nothing rather than fatal-crashing the order-success flow -
 * losing a commission entry is recoverable, breaking payment confirmation
 * for a merchant's real customer is not.
 */
function deduct_commission_on_success($conn, $user_id, $order_id, $amount) {
    if (!$user_id) return; // nothing to charge if there's no owning merchant (shouldn't normally happen)

    $settings = get_commission_settings($conn);
    $commission = calculate_commission($amount, $settings);

    if ($commission <= 0) return; // 0% / ₹0 configured - nothing to deduct, don't log a noise entry

    $stmt = $conn->prepare("UPDATE users SET wallet = wallet - ? WHERE id = ?");
    if (!$stmt) return;
    $stmt->bind_param("di", $commission, $user_id);
    $stmt->execute();
    $stmt->close();

    $newBalance = get_wallet_balance($conn, $user_id);

    $txnId = 'COMM' . strtoupper(substr(md5($order_id . microtime()), 0, 12));
    $note = $settings['type'] === 'percent'
        ? ($settings['value'] . '% commission on order ' . $order_id)
        : ('Flat commission on order ' . $order_id);

    $stmt = $conn->prepare("INSERT INTO wallet_transactions (user_id, wallet_txnid, order_id, date, type, amount, balance_after, note, operation_type) VALUES (?, ?, ?, NOW(), 'Commission', ?, ?, ?, 'debit')");
    if (!$stmt) return;
    $stmt->bind_param("issdds", $user_id, $txnId, $order_id, $commission, $newBalance, $note);
    $stmt->execute();
    $stmt->close();
}

function get_wallet_balance($conn, $user_id) {
    $stmt = $conn->prepare("SELECT wallet FROM users WHERE id = ?");
    if (!$stmt) return 0.0;
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return (float)($row['wallet'] ?? 0);
}

/**
 * Credits a merchant's wallet (used by the Add Funds payment callback once
 * a real top-up payment has been confirmed COMPLETED).
 */
function credit_wallet($conn, $user_id, $order_id, $amount, $note = 'Wallet top-up') {
    $stmt = $conn->prepare("UPDATE users SET wallet = wallet + ? WHERE id = ?");
    if (!$stmt) return;
    $stmt->bind_param("di", $amount, $user_id);
    $stmt->execute();
    $stmt->close();

    $newBalance = get_wallet_balance($conn, $user_id);

    $txnId = 'TOPUP' . strtoupper(substr(md5($order_id . microtime()), 0, 10));
    $stmt = $conn->prepare("INSERT INTO wallet_transactions (user_id, wallet_txnid, order_id, date, type, amount, balance_after, note, operation_type) VALUES (?, ?, ?, NOW(), 'TopUp', ?, ?, ?, 'credit')");
    if (!$stmt) return;
    $stmt->bind_param("issdds", $user_id, $txnId, $order_id, $amount, $newBalance, $note);
    $stmt->execute();
    $stmt->close();
}

function get_wallet_history($conn, $user_id, $limit = 100) {
    $stmt = $conn->prepare("SELECT * FROM wallet_transactions WHERE user_id = ? ORDER BY date DESC, id DESC LIMIT ?");
    if (!$stmt) return [];
    $stmt->bind_param("ii", $user_id, $limit);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $rows;
}
