<?php
/**
 * WhatsApp role access-list policy.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_WhatsApp_Access_Policy {

	public static function number_keys() {
		return array( 'admin_numbers', 'stock_manager_numbers', 'lead_numbers' );
	}

	public static function group_keys() {
		return array( 'admin_group_jids', 'stock_manager_group_jids', 'lead_group_jids' );
	}

	public static function normalize_role( $role ) {
		$role = sanitize_key( (string) $role );
		if ( in_array( $role, array( 'admin', 'owner', 'founder' ), true ) ) {
			return 'admin';
		}
		if ( in_array( $role, array( 'stock_manager', 'stock', 'stock_manager_numbers', 'stockmanager' ), true ) ) {
			return 'stock_manager';
		}
		if ( in_array( $role, array( 'lead', 'leads', 'customer', 'user' ), true ) ) {
			return 'lead';
		}

		return '';
	}

	public static function role_to_number_key( $role ) {
		$role = self::normalize_role( $role );
		if ( 'stock_manager' === $role ) {
			return 'stock_manager_numbers';
		}
		if ( 'lead' === $role ) {
			return 'lead_numbers';
		}

		return 'admin_numbers';
	}

	public static function role_to_group_key( $role ) {
		$role = self::normalize_role( $role );
		if ( 'stock_manager' === $role ) {
			return 'stock_manager_group_jids';
		}
		if ( 'lead' === $role ) {
			return 'lead_group_jids';
		}

		return 'admin_group_jids';
	}

	public static function sanitize_entries( $entries ) {
		$entries = is_array( $entries ) ? $entries : array();
		$out     = array();
		$seen    = array();

		foreach ( $entries as $entry ) {
			if ( is_array( $entry ) ) {
				$phone = isset( $entry['phone'] ) ? $entry['phone'] : ( isset( $entry['number'] ) ? $entry['number'] : '' );
				$label = isset( $entry['label'] ) ? $entry['label'] : '';
			} else {
				$phone = $entry;
				$label = '';
			}

			$phone = '*' === trim( (string) $phone ) ? '*' : Niwa_AI_Admin_Autonomy_WhatsApp_Identity::normalize_sender_id( $phone );
			if ( '' === $phone || isset( $seen[ $phone ] ) ) {
				continue;
			}

			$seen[ $phone ] = true;
			$out[] = array(
				'phone' => $phone,
				'label' => function_exists( 'sanitize_text_field' ) ? sanitize_text_field( mb_substr( (string) $label, 0, 100 ) ) : substr( preg_replace( '/[\r\n\t]+/', ' ', (string) $label ), 0, 100 ),
			);
		}

		return $out;
	}

	public static function sanitize_group_entries( $entries ) {
		$entries = is_array( $entries ) ? $entries : array();
		$out     = array();
		$seen    = array();

		foreach ( $entries as $entry ) {
			if ( is_array( $entry ) ) {
				$jid   = isset( $entry['jid'] ) ? $entry['jid'] : ( isset( $entry['group_jid'] ) ? $entry['group_jid'] : '' );
				$label = isset( $entry['label'] ) ? $entry['label'] : '';
			} else {
				$jid   = $entry;
				$label = '';
			}

			$jid = Niwa_AI_Admin_Autonomy_WhatsApp_Identity::normalize_group_jid( $jid );
			if ( '' === $jid || isset( $seen[ $jid ] ) ) {
				continue;
			}

			$seen[ $jid ] = true;
			$out[] = array(
				'jid'   => $jid,
				'label' => function_exists( 'sanitize_text_field' ) ? sanitize_text_field( mb_substr( (string) $label, 0, 100 ) ) : substr( preg_replace( '/[\r\n\t]+/', ' ', (string) $label ), 0, 100 ),
			);
		}

		return $out;
	}

	public static function entries_contain_phone( $entries, $phone ) {
		$phone = '*' === trim( (string) $phone ) ? '*' : Niwa_AI_Admin_Autonomy_WhatsApp_Identity::normalize_sender_id( $phone );
		if ( '' === $phone ) {
			return false;
		}

		foreach ( self::sanitize_entries( $entries ) as $entry ) {
			$current = isset( $entry['phone'] ) ? (string) $entry['phone'] : '';
			if ( '*' === $current || ( '' !== $current && hash_equals( $current, $phone ) ) ) {
				return true;
			}
		}

		return false;
	}

	public static function entries_contain_group( $entries, $jid ) {
		$jid = Niwa_AI_Admin_Autonomy_WhatsApp_Identity::normalize_group_jid( $jid );
		if ( '' === $jid ) {
			return false;
		}

		foreach ( self::sanitize_group_entries( $entries ) as $entry ) {
			$current = isset( $entry['jid'] ) ? (string) $entry['jid'] : '';
			if ( '' !== $current && hash_equals( $current, $jid ) ) {
				return true;
			}
		}

		return false;
	}

	public static function build_summary( $wa ) {
		$wa    = is_array( $wa ) ? $wa : array();
		$parts = array();
		foreach ( array(
			'admin'         => 'admin_numbers',
			'stock_manager' => 'stock_manager_numbers',
			'lead'          => 'lead_numbers',
		) as $role => $key ) {
			$items = array();
			foreach ( self::sanitize_entries( isset( $wa[ $key ] ) ? $wa[ $key ] : array() ) as $entry ) {
				$label   = isset( $entry['label'] ) && '' !== (string) $entry['label'] ? (string) $entry['label'] . ' ' : '';
				$items[] = trim( $label . self::mask_phone( isset( $entry['phone'] ) ? $entry['phone'] : '' ) );
			}
			$parts[] = $role . ': ' . ( empty( $items ) ? 'none' : implode( ', ', $items ) );
		}

		return implode( ' | ', $parts );
	}

	public static function group_entries_to_jids( $entries ) {
		$jids = array();
		foreach ( self::sanitize_group_entries( $entries ) as $entry ) {
			if ( ! empty( $entry['jid'] ) ) {
				$jids[] = (string) $entry['jid'];
			}
		}

		return array_values( array_unique( $jids ) );
	}

	public static function mask_phone( $phone ) {
		if ( '*' === trim( (string) $phone ) ) {
			return '*';
		}
		$phone = Niwa_AI_Admin_Autonomy_WhatsApp_Identity::normalize_sender_id( $phone );
		if ( strlen( $phone ) <= 5 ) {
			return $phone;
		}

		return substr( $phone, 0, 3 ) . '***' . substr( $phone, -2 );
	}
}
