<?php
/**
 * Inventory operations.
 *
 * @package Logistica
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Provides small DB helpers for dashboard stats.
 */
class Logistica_Inventory {
	/**
	 * Counts records in a custom table.
	 *
	 * @param string $table_key Table key.
	 * @return int
	 */
	public static function count_records( $table_key ) {
		global $wpdb;

		$cache_key = 'logistica_inventory_count_' . sanitize_key( $table_key );
		$cached    = get_transient( $cache_key );
		if ( false !== $cached ) {
			return (int) $cached;
		}

		$table = Logistica_Database::table( $table_key );
		if ( ! $table ) {
			return 0;
		}

		if ( 'inventario_bodega' === $table_key ) {
			$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE estado = 'activo'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		} else {
			$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		set_transient( $cache_key, $count, 5 * MINUTE_IN_SECONDS );

		return $count;
	}
}
