<?php
/**
 * CustomerRoleRule — passes when the customer has (or does not have) a given role.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class CustomerRoleRule extends AbstractRule {

	public function get_slug(): string {
		return 'customer_role';
	}

	public function get_label(): string {
		return __( 'Customer has role', 'cartcue-sales-automation' );
	}

	public function get_operators(): array {
		return [
			'is'     => __( 'is', 'cartcue-sales-automation' ),
			'is_not' => __( 'is not', 'cartcue-sales-automation' ),
		];
	}

	public function get_value_type(): string {
		return 'select';
	}

	public function get_value_options(): array {
		$roles   = wp_roles()->get_names();
		$options = [];
		foreach ( $roles as $slug => $label ) {
			$options[ $slug ] = translate_user_role( $label );
		}
		return $options;
	}

	public function evaluate( array $config, array $data ): bool {
		$customer_id = (int) ( $data['customer_id'] ?? 0 );

		// Determine user: try customer_id first, then resolve from order.
		if ( ! $customer_id && ! empty( $data['order_id'] ) ) {
			$order       = wc_get_order( (int) $data['order_id'] );
			$customer_id = $order ? (int) $order->get_customer_id() : 0;
		}

		if ( ! $customer_id ) {
			// Guest customer — treat as subscriber/customer role.
			$actual_role = 'customer';
		} else {
			$user = get_user_by( 'id', $customer_id );
			if ( ! $user ) {
				return false;
			}
			$roles       = (array) $user->roles;
			$actual_role = $roles[0] ?? 'subscriber';
		}

		$operator = sanitize_key( $config['operator'] ?? 'is' );
		$expected = sanitize_key( $config['value'] ?? 'customer' );

		return $this->compare( $actual_role, $operator, $expected );
	}
}
