<?php
// wallet/includes/wallet_db.php
require_once __DIR__ . '/../core/db_connect.php';

/**
 * Tenant Balance = total deposits only.
 * Usage/costs are handled separately in tenant-dashboard.php.
 */
function getTenantBalance($tenant_id, $pdo) {
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(amount),0) 
        FROM tenant_wallet_deposits 
        WHERE tenant_id = ?
    ");
    $stmt->execute([$tenant_id]);
    return (float)$stmt->fetchColumn();
}

/**
 * Landlord Balance = deposits - fees - payouts.
 */
function getLandlordBalance($landlord_id, $pdo) {
    $stmt = $pdo->prepare("
        SELECT 
            COALESCE(SUM(d.amount - d.fee),0) - 
            COALESCE((
                SELECT SUM(p.amount) 
                FROM landlord_wallet_payouts p 
                WHERE p.landlord_id = ?
            ),0) AS balance
        FROM tenant_wallet_deposits d
        WHERE d.landlord_id = ?
    ");
    $stmt->execute([$landlord_id, $landlord_id]);
    return (float)$stmt->fetchColumn();
}

/**
 * Record a new tenant deposit.
 */
function addTenantDeposit($tenant_id, $landlord_id, $amount, $fee, $pdo) {
    $stmt = $pdo->prepare("
        INSERT INTO tenant_wallet_deposits (tenant_id, landlord_id, amount, fee)
        VALUES (?, ?, ?, ?)
    ");
    return $stmt->execute([$tenant_id, $landlord_id, $amount, $fee]);
}

/**
 * Record a landlord payout.
 */
function addLandlordPayout($landlord_id, $amount, $pdo) {
    $stmt = $pdo->prepare("
        INSERT INTO landlord_wallet_payouts (landlord_id, amount)
        VALUES (?, ?)
    ");
    return $stmt->execute([$landlord_id, $amount]);
}
