<?php
/**
 * Usuario compatible con WordPress para la app standalone.
 */

if ( ! class_exists( 'WP_User', false ) ) {
	class WP_User {
		public $ID = 0;
		public $user_login = '';
		public $user_pass = '';
		public $user_nicename = '';
		public $user_email = '';
		public $display_name = '';
		public $user_registered = '';
		public $roles = array();
		public $caps = array();

		/**
		 * @param object|null $data Datos del usuario.
		 */
		public function __construct( $data = null ) {
			if ( is_object( $data ) ) {
				foreach ( get_object_vars( $data ) as $key => $value ) {
					$this->$key = $value;
				}
			}
		}

		/**
		 * @return bool
		 */
		public function exists() {
			return $this->ID > 0;
		}

		/**
		 * @param string $role Role slug.
		 * @return void
		 */
		public function add_role( $role ) {
			$role = sanitize_key( (string) $role );
			if ( '' === $role ) {
				return;
			}

			if ( ! in_array( $role, $this->roles, true ) ) {
				$this->roles[] = $role;
			}

			if ( class_exists( 'Logistica_Roles', false ) && isset( Logistica_Roles::get_role_definitions()[ $role ] ) ) {
				update_user_meta( $this->ID, Logistica_Roles::USER_META_ROLE, $role );
			}
		}

		/**
		 * @param string $role Role slug.
		 * @return void
		 */
		public function remove_role( $role ) {
			$role = sanitize_key( (string) $role );
			$this->roles = array_values( array_filter( $this->roles, static function ( $existing ) use ( $role ) {
				return $existing !== $role;
			} ) );

			if ( class_exists( 'Logistica_Roles', false ) ) {
				$assigned = get_user_meta( $this->ID, Logistica_Roles::USER_META_ROLE, true );
				if ( $assigned === $role ) {
					delete_user_meta( $this->ID, Logistica_Roles::USER_META_ROLE );
				}
			}
		}
	}
}
