<?php
/**
 * Abstract Repository Class
 *
 * Base class for all repositories. All database access is handled through DatabaseHandler.
 *
 * @package Awesomemotive\Rewardswp\Abstracts
 * @since 1.1.0
 */

namespace Awesomemotive\Rewardswp\Abstracts;

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

use Awesomemotive\Rewardswp\Database\DatabaseHandler;

/**
 * Class AbstractRepository
 *
 * Provides base functionality for repositories including:
 * - Raw SQL query execution via DatabaseHandler
 * - Built-in caching support (reports cache group)
 * - Parameter binding helpers
 * - Single value retrieval
 *
 * All database operations are delegated to DatabaseHandler for consistency.
 *
 * @since 1.1.0
 */
abstract class AbstractRepository {

	/**
	 * Default cache group for repositories.
	 *
	 * @since 1.1.0
	 */
	const CACHE_GROUP = 'rewardswp_reports';

	/**
	 * Database handler instance.
	 *
	 * @since 1.1.0
	 *
	 * @var DatabaseHandler
	 */
	protected DatabaseHandler $db_handler;

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 *
	 * @param DatabaseHandler $db_handler Database handler instance.
	 */
	public function __construct( DatabaseHandler $db_handler ) {
		$this->db_handler = $db_handler;
	}

	/**
	 * Execute a raw SQL query with optional caching.
	 *
	 * Delegates to DatabaseHandler with reports cache group.
	 * Uses prepared statements for security. Caches results by default.
	 *
	 * @since 1.1.0
	 *
	 * @param string $sql    SQL query with %s, %d placeholders.
	 * @param array  $params Optional. Parameters to bind to query. Default empty array.
	 * @param bool   $cache  Optional. Whether to cache results. Default true.
	 *
	 * @return array Array of results (ARRAY_A format) or empty array on failure.
	 */
	protected function query( string $sql, array $params = [], bool $cache = true ): array {
		return $this->db_handler->query( $sql, $params, $cache, self::CACHE_GROUP );
	}

	/**
	 * Get a single value from a query.
	 *
	 * Delegates to DatabaseHandler with reports cache group.
	 * Useful for COUNT, SUM, MAX, etc. queries.
	 *
	 * @since 1.1.0
	 *
	 * @param string $sql    SQL query with %s, %d placeholders.
	 * @param array  $params Optional. Parameters to bind to query. Default empty array.
	 * @param bool   $cache  Optional. Whether to cache results. Default true.
	 *
	 * @return mixed|null Single value or null if not found.
	 */
	protected function get_var( string $sql, array $params = [], bool $cache = true ) {
		return $this->db_handler->get_var( $sql, $params, $cache, self::CACHE_GROUP );
	}
}
