<?php
/**
 * helper_balance.php
 * 
 * Recalculate the correct customer balance from customer_transactions.
 * This makes the system ALWAYS correct even إذا صار حذف فاتورة / تعديل / دفعات.
 */

if (!function_exists('recalcCustomerBalance')) {

    function recalcCustomerBalance(PDO $pdo, int $customer_id)
    {
        // اجمع كل الديون والدفع والإرجاع
        $stmt = $pdo->prepare("
            SELECT 
                SUM(
                    CASE 
                        WHEN type = 'debt' THEN amount 
                        WHEN type = 'payment' THEN -amount
                        WHEN type = 'refund' THEN amount  -- refund reduces negative balance
                        ELSE 0
                    END
                ) AS balance
            FROM customer_transactions
            WHERE customer_id = ?
        ");
        $stmt->execute([$customer_id]);

        $balance = floatval($stmt->fetchColumn() ?? 0);

        // حدث جدول customers
        $update = $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?");
        $update->execute([$balance, $customer_id]);

        return $balance;
    }
}
