<?php

namespace SGC\eGiftCard\Http\Model;
defined( 'ABSPATH' ) || exit; // Prevent direct file access.
/**
 * Class UserBalance
 *
 * Represents user balance data and provides methods to interact with the user_balances table.
 */
class UserBalance extends Model {
    
    /**
     * @var string The name of the database table.
     */
    protected $tableName = 'user_balances';

    /**
     * Get the balance for a specific user.
     *
     * @param int $user_id The ID of the user.
     * @return float The user's balance. Returns 0.0 if not found.
     */
    public function getBalanceByUserId( $user_id ) {
        // Prepare and execute the query to retrieve the user's balance
        $result = $this->_wpdb->get_var(
            $this->_wpdb->prepare("SELECT balance FROM {$this->tableName} WHERE user_id = %d", $user_id)
        );

        // Return the balance as a float or 0.0 if not found
        return (float) $result ?: 0.0;
    }

    /**
     * Update the balance for a specific user.
     *
     * @param int $user_id The ID of the user.
     * @param float $new_balance The new balance to set.
     * @return int|false The number of rows updated or false on failure.
     */
    public function updateBalance( $user_id, $new_balance ) {
        // Validate new_balance to ensure it's a float
        if ( ! is_numeric( $new_balance ) ) {
            return false; // or handle the error as needed
        }

        // Update the user's balance and last updated timestamp
        $result = $this->_wpdb->update(
            $this->tableName,
            [
                'balance'      => ( float ) $new_balance,
                'last_updated' => current_time( 'mysql' )
            ],
            ['user_id' => $user_id]
        );

        return $result;
    }
}