<?php
namespace App\classes;
use mysqli;

class BalanceHistory
{
    public static function log(mysqli $conn, int $agentId, float $changeAmount, string $reason, ?int $refId = null, ?string $beneficiaryNumber = null)
    {
        // Check if balance history logging is disabled (for production issues)
        if (defined('DISABLE_BALANCE_HISTORY') && DISABLE_BALANCE_HISTORY === true) {
            return true; // Return success without logging
        }
        
        $stmt = $conn->prepare("SELECT balance FROM agents WHERE id = ?");
        $stmt->bind_param("i", $agentId);
        $stmt->execute();
        $result = $stmt->get_result();
        $agent = $result->fetch_assoc();
        $stmt->close();

        if (!$agent) {
            error_log("BalanceHistory: Agent ID $agentId not found.");
            return false;
        }

        $balanceAfter = $agent['balance']; // This is the balance *after* the current transaction has been applied

        // Ensure reason is not empty
        if (empty($reason)) {
            $reason = 'transaction';
        }

        try {
            $insertStmt = $conn->prepare("INSERT INTO balance_history (agent_id, change_amount, balance_after, reason, ref_id, beneficiary_number) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$insertStmt) {
                error_log("BalanceHistory: Prepare failed: " . $conn->error);
                return false;
            }
            $insertStmt->bind_param("iddsis", $agentId, $changeAmount, $balanceAfter, $reason, $refId, $beneficiaryNumber);
            $success = $insertStmt->execute();
            if (!$success) {
                error_log("BalanceHistory: Execute failed: " . $insertStmt->error);
            }
            $insertStmt->close();
            return $success;
        } catch (mysqli_sql_exception $e) {
            error_log("BalanceHistory: SQL Exception - " . $e->getMessage());
            return false;
        }
    }
}
