<?php
/**
 * WhatsApp command-role guard.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_WhatsApp_Command_Access {
	private $lead_allowed = array( 'help', 'start', 'new', 'reset', 'stop' );
	private $stock_manager_allowed = array( 'help', 'start', 'new', 'reset', 'stop' );

	public function guard( $command, $callback_command, $context ) {
		$context = is_array( $context ) ? $context : array();
		if ( 'whatsapp' !== ( isset( $context['channel'] ) ? sanitize_key( (string) $context['channel'] ) : '' ) ) {
			return null;
		}

		$role       = isset( $context['user_role'] ) ? sanitize_key( (string) $context['user_role'] ) : 'admin';
		$command_id = $this->command_id( $command, $callback_command );
		if ( '' === $command_id || 'admin' === $role ) {
			return null;
		}

		if ( 'lead' === $role && ! in_array( $command_id, $this->lead_allowed, true ) ) {
			return array(
				'reply'             => 'Ta WhatsApp komanda nije dostupna za lead/customer razgovor. Mozete koristiti /help, /new, /reset i /stop.',
				'remember_exchange' => false,
			);
		}

		if ( 'stock_manager' === $role && ! in_array( $command_id, $this->stock_manager_allowed, true ) ) {
			return array(
				'reply'             => 'Ta komanda nije dostupna za stock manager nalog. Mozete koristiti /help, /new, /reset i /stop.',
				'remember_exchange' => false,
			);
		}

		return null;
	}

	private function command_id( $command, $callback_command ) {
		$callback_command = sanitize_key( (string) $callback_command );
		if ( '' !== $callback_command ) {
			return $callback_command;
		}

		$parts = preg_split( '/\s+/', trim( (string) $command ), 2 );
		return sanitize_key( isset( $parts[0] ) ? (string) $parts[0] : '' );
	}
}
