<?php
/**
 * Role repository.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

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

/**
 * Data access for staff roles / module permissions.
 */
class LUCRSURE_Role_Repository extends LUCRSURE_Repository {

	/**
	 * Table base name.
	 *
	 * @var string
	 */
	protected $table = 'roles';

	/**
	 * Column formats.
	 *
	 * @var array<string,string>
	 */
	protected $formats = array(
		'name'        => '%s',
		'slug'        => '%s',
		'description' => '%s',
		'modules'     => '%s',
		'is_active'   => '%d',
		'is_system'   => '%d',
		'created_at'  => '%s',
		'updated_at'  => '%s',
	);

	/**
	 * Decode the modules JSON for a role.
	 *
	 * @param array $role Role row.
	 * @return string[]
	 */
	public static function modules( $role ) {
		if ( empty( $role['modules'] ) ) {
			return array();
		}
		$decoded = json_decode( $role['modules'], true );
		return is_array( $decoded ) ? $decoded : array();
	}

	/**
	 * Count staff assigned to each role.
	 *
	 * @return array<int,int> role_id => count.
	 */
	public function staff_counts() {
		global $wpdb;
		$rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$wpdb->prepare(
				'SELECT role_id, COUNT(*) AS total FROM %i GROUP BY role_id',
				lucrsure_table( 'staff' )
			),
			ARRAY_A
		);
		$out = array();
		foreach ( (array) $rows as $row ) {
			$out[ (int) $row['role_id'] ] = (int) $row['total'];
		}
		return $out;
	}
}
