<?php
namespace UM_Elementor\Helpers;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * WordPress Native User Meta Field Renderer
 * 
 * Centralized class for rendering WordPress native user meta fields
 * in Elementor widgets with consistent formatting and field type support.
 */
class WP_User_Meta_Renderer
{
    /**
     * Special field identifiers
     */
    private const SPECIAL_FIELDS = [
        'USER_AVATAR' => 'User Avatar',
        'PROFILE_PHOTO' => 'profile_photo',
        'COVER_PHOTO' => 'cover_photo'
    ];

    /**
     * YouTube URL patterns for video extraction
     */
    private const YOUTUBE_PATTERNS = [
        '/watch\?v=([a-zA-Z0-9_-]+)/',
        '/youtu\.be\/([a-zA-Z0-9_-]+)/',
        '/embed\/([a-zA-Z0-9_-]+)/',
        '/v\/([a-zA-Z0-9_-]+)/'
    ];

    /**
     * Current user ID being rendered
     */
    private $current_user_id = 0;

    /**
     * Set current user ID
     */
    public function setCurrentUser($user_id)
    {
        $this->current_user_id = $user_id;
    }

    /**
     * Render user meta fields from widget settings
     * 
     * @param array $settings Widget settings
     * @param string $control_name Settings key for meta fields
     * @return string Rendered HTML
     */
    public function render_meta_fields(array $settings, string $control_name = 'um_user_meta_control'): string
    {
        if (empty($settings[$control_name])) {
            return '';
        }

        ob_start();

        foreach ($settings[$control_name] as $item) {
            $standardized_item = $this->standardize_item($item);
            $this->render_single_meta_field($standardized_item);
        }

        return ob_get_clean();
    }

    /**
     * Render a single meta field item (for table widgets and specialized layouts)
     * 
     * @param array $item Field configuration array
     * @return string Rendered field HTML
     */
    public function render_single_field(array $item): string
    {
        if (!isset($item['um_user_meta_field_value'])) {
            return '';
        }

        $field_key = $item['um_user_meta_field_value'];
        $meta_value = UM_Elementor_Utils::getUserMeta($this->current_user_id, $field_key);

        if (empty($meta_value)) {
            return '';
        }

        ob_start();

        $this->render_field_label($item, $field_key);
        $this->render_field_value($field_key, $meta_value);

        return ob_get_clean();
    }

    /**
     * Standardize item array for consistent processing
     * 
     * @param array $item Raw item array
     * @return array Standardized item array
     */
    private function standardize_item(array $item): array
    {
        $field_key = $item['um_user_meta_field_value'] ?? $item['um_user_meta_field_value_front'] ?? '';
        $show_label = $item['um_user_meta_field_label'] ?? $item['um_user_meta_field_label_front'] ?? 1;

        $out = [
            'um_user_meta_field_value' => $field_key,
            'um_user_meta_field_label' => $show_label,
        ];

        if (isset($item['field_visibility'])) {
            $out['field_visibility'] = $item['field_visibility'];
        }
        if (isset($item['field_visibility_roles'])) {
            $out['field_visibility_roles'] = $item['field_visibility_roles'];
        }

        foreach ( [
            'field_value_condition_enable',
            'field_value_condition_key',
            'field_value_condition_operator',
            'field_value_condition_value',
        ] as $vc_key ) {
            if ( isset( $item[ $vc_key ] ) ) {
                $out[ $vc_key ] = $item[ $vc_key ];
            }
        }

        return $out;
    }

    /**
     * Render a single meta field with wrapper
     * 
     * @param array $item Field configuration
     */
    private function render_single_meta_field(array $item): void
    {
        if (class_exists('\UM_Elementor_Field_Visibility') && ! \UM_Elementor_Field_Visibility::can_view($item, (int) $this->current_user_id)) {
            return;
        }

        $field_key = $item['um_user_meta_field_value'] ?? '';
        $show_label = $item['um_user_meta_field_label'] ?? 1;

        if (empty($field_key)) {
            return;
        }

        if ($this->is_special_field($field_key)) {
            $this->render_special_field($field_key);
            return;
        }

        $this->render_regular_field($field_key, $show_label);
    }

    /**
     * Check if field is a special field type
     * 
     * @param string $field_key Field key to check
     * @return bool True if special field
     */
    private function is_special_field(string $field_key): bool
    {
        return in_array($field_key, self::SPECIAL_FIELDS, true);
    }

    /**
     * Render special field types
     * 
     * @param string $field_key Special field key
     */
    private function render_special_field(string $field_key): void
    {
        switch ($field_key) {
            case self::SPECIAL_FIELDS['USER_AVATAR']:
                $this->render_user_avatar_with_name();
                break;
            case self::SPECIAL_FIELDS['PROFILE_PHOTO']:
                $this->render_user_avatar();
                break;
            case self::SPECIAL_FIELDS['COVER_PHOTO']:
                $this->render_cover_photo();
                break;
        }
    }

    /**
     * Render regular meta field
     * 
     * @param string $field_key Field key
     * @param bool $show_label Whether to show label
     */
    private function render_regular_field(string $field_key, bool $show_label): void
    {
        $meta_value = UM_Elementor_Utils::getUserMeta($this->current_user_id, $field_key);

        if (empty($meta_value)) {
            return;
        }

        $this->output_meta_field($field_key, $meta_value, $show_label);
    }

    /**
     * Output meta field HTML with wrapper
     * 
     * @param string $field_key Field key
     * @param mixed $meta_value Field value
     * @param bool $show_label Whether to show field label
     */
    private function output_meta_field(string $field_key, $meta_value, bool $show_label): void
    {
        echo '<span class="um-meta-field">';

        if ($show_label) {
            $this->render_field_label_html($field_key);
        }

        echo '<span class="um-custom-field">';
        $this->render_field_value($field_key, $meta_value);
        echo '</span>';
        echo '</span>';
    }

    /**
     * Render field label if enabled
     * 
     * @param array $item Field item
     * @param string $field_key Field key
     */
    private function render_field_label(array $item, string $field_key): void
    {
        if (isset($item['um_user_meta_field_label']) && $item['um_user_meta_field_label']) {
            echo "<span class='um-custom-label'>" . esc_attr($this->get_field_label($field_key)) . ":</span> ";
        }
    }

    /**
     * Render field label HTML
     * 
     * @param string $field_key Field key
     */
    private function render_field_label_html(string $field_key): void
    {
        $label = $this->get_field_label($field_key);
        echo '<span class="um-custom-label">' . esc_attr($label) . ':</span>';
    }

    /**
     * Get field label for WordPress native fields
     * 
     * @param string $field_key Field key
     * @return string Field label
     */
    private function get_field_label(string $field_key): string
    {
        $labels = [
            'first_name' => __('First Name', 'ultimate-member-widgets-for-elementor'),
            'last_name' => __('Last Name', 'ultimate-member-widgets-for-elementor'),
            'description' => __('Biographical Info', 'ultimate-member-widgets-for-elementor'),
            'user_url' => __('Website', 'ultimate-member-widgets-for-elementor'),
            'nickname' => __('Nickname', 'ultimate-member-widgets-for-elementor'),
            'user_email' => __('Email', 'ultimate-member-widgets-for-elementor'),
            'user_login' => __('Username', 'ultimate-member-widgets-for-elementor'),
            'display_name' => __('Display Name', 'ultimate-member-widgets-for-elementor'),
            'user_registered' => __('Registration Date', 'ultimate-member-widgets-for-elementor'),
            'user_nicename' => __('Nicename', 'ultimate-member-widgets-for-elementor'),
        ];

        return $labels[$field_key] ?? ucwords(str_replace('_', ' ', $field_key));
    }

    /**
     * Render field value based on its type
     * 
     * @param string $field_key Field key
     * @param mixed $meta_value Field value
     */
    private function render_field_value(string $field_key, $meta_value): void
    {
        if ($field_key === 'full_name') {
            $user = get_user_by('ID', $this->current_user_id);
            if ($user) {
                $first_name = trim((string) $user->first_name);
                $last_name = trim((string) $user->last_name);
                $full_name = trim($first_name . ' ' . $last_name);
                if ($full_name === '') {
                    $full_name = (string) $user->display_name;
                }
                echo esc_html($full_name);
            }
            return;
        }

        if ($field_key === 'registration_date') {
            $user = get_user_by('ID', $this->current_user_id);
            if ($user && !empty($user->user_registered)) {
                echo esc_html(date_i18n(get_option('date_format'), strtotime($user->user_registered)));
            }
            return;
        }

        if ($field_key === 'profile_url') {
            echo esc_url(UM_Elementor_Utils::getUserProfileUrl($this->current_user_id));
            return;
        }

        if ($this->is_special_field($field_key)) {
            $this->render_special_field($field_key);
            return;
        }

        $field_type = $this->get_field_type($field_key);
        $this->render_field_by_type($field_key, $meta_value, $field_type);
    }

    /**
     * Get field type for WordPress native fields
     * 
     * @param string $field_key Field key
     * @return string Field type
     */
    private function get_field_type(string $field_key): string
    {
        $field_types = [
            'user_url' => 'url',
            'user_email' => 'email',
            'description' => 'textarea',
            'first_name' => 'text',
            'last_name' => 'text',
            'nickname' => 'text',
            'display_name' => 'text',
            'user_login' => 'text',
            'user_registered' => 'date',
        ];

        return $field_types[$field_key] ?? 'text';
    }

    /**
     * Render field based on its type
     * 
     * @param string $field_key Field key
     * @param mixed $meta_value Field value
     * @param string $field_type Field type
     */
    private function render_field_by_type(string $field_key, $meta_value, string $field_type): void
    {
        $field_renderers = [
            'url' => 'render_url_field',
            'email' => 'render_email_field',
            'date' => 'render_date_field',
            'textarea' => 'render_textarea_field'
        ];

        if (isset($field_renderers[$field_type])) {
            $method = $field_renderers[$field_type];
            $this->$method($meta_value);
        } else {
            $this->render_default_field($meta_value);
        }
    }

    /**
     * Render URL field with consistent formatting
     * 
     * @param string $meta_value URL value
     */
    public function render_url_field(string $meta_value): void
    {
        if (empty($meta_value)) {
            return;
        }

        $link_url = esc_url($meta_value);
        $display_url = esc_html($link_url);

        echo wp_kses_post("<a href='{$link_url}' target='_blank' rel='noopener noreferrer'>{$display_url}</a>");
        echo wp_kses_post("<i class='um-faicon-link'></i>");
    }

    /**
     * Render email field with consistent formatting
     * 
     * @param string $meta_value Email value
     */
    public function render_email_field(string $meta_value): void
    {
        if (empty($meta_value)) {
            return;
        }

        $link_email = esc_attr($meta_value);
        $display_email = esc_html($meta_value);

        echo wp_kses_post("<a href='mailto:{$link_email}'>{$display_email}</a>");
        echo wp_kses_post("<i class='um-faicon-envelope'></i>");
    }

    /**
     * Render date field with consistent formatting
     * 
     * @param string $meta_value Date value
     */
    public function render_date_field(string $meta_value): void
    {
        if (empty($meta_value)) {
            return;
        }

        $date = date_i18n(get_option('date_format'), strtotime($meta_value));
        echo esc_html($date);
    }

    /**
     * Render textarea field with consistent formatting
     * 
     * @param string $meta_value Textarea value
     */
    public function render_textarea_field(string $meta_value): void
    {
        if (empty($meta_value)) {
            return;
        }

        echo wp_kses_post(wpautop($meta_value));
    }

    /**
     * Render default field types with consistent formatting
     * 
     * @param mixed $meta_value Field value
     */
    public function render_default_field($meta_value): void
    {
        if (is_array($meta_value)) {
            $values = array_map('esc_attr', $meta_value);
            echo wp_kses_post(implode(', ', $values));
        } else {
            echo esc_attr($meta_value);
        }
    }

    /**
     * Render user avatar
     */
    public function render_user_avatar(): void
    {
        $user = get_user_by('ID', $this->current_user_id);
        if (!$user) {
            return;
        }

        $display_name = $user->display_name;
        $profile_url = UM_Elementor_Utils::getUserProfileUrl($this->current_user_id);
        $avatar_url = UM_Elementor_Utils::getUserAvatarUrl($this->current_user_id, 100);

        echo '<div class="um-elementor-member-image">';
        echo '<a title="' . esc_attr($display_name) . '" href="' . esc_url($profile_url) . '">';
        echo '<img src="' . esc_url($avatar_url) . '" alt="' . esc_attr($display_name) . '" width="100" height="100">';
        echo '</a>';
        echo '</div>';
    }

    /**
     * Render user avatar with name (for table layouts)
     */
    public function render_user_avatar_with_name(): void
    {
        $user = get_user_by('ID', $this->current_user_id);
        if (!$user) {
            return;
        }

        $display_name = $user->display_name;
        $profile_url = UM_Elementor_Utils::getUserProfileUrl($this->current_user_id);
        $avatar_url = UM_Elementor_Utils::getUserAvatarUrl($this->current_user_id, 70);

        echo '<div class="um-table-column-avatar">';
        echo '<a title="' . esc_attr($display_name) . '" href="' . esc_url($profile_url) . '" class="user-avatar-link">';
        echo '<img src="' . esc_url($avatar_url) . '" alt="' . esc_attr($display_name) . '" width="70" height="70">';
        echo '</a>';
        echo '<a title="' . esc_attr($display_name) . '" href="' . esc_url($profile_url) . '" class="user-avatar-name">';
        echo '<h6 class="user-avatar-name-text">' . esc_html($display_name) . '</h6>';
        echo '</a>';
        echo '</div>';
    }

    /**
     * Render cover photo (placeholder for WordPress native)
     */
    public function render_cover_photo(): void
    {
        $user = get_user_by('ID', $this->current_user_id);
        if (!$user) {
            return;
        }

        $cover_url = $this->get_cover_photo_url($this->current_user_id);

        if (empty($cover_url)) {
            return;
        }

        $display_name = $user->display_name;

        echo '<div class="um-elementor-cover-photo">';
        echo '<img src="' . esc_url($cover_url) . '" alt="' . esc_attr($display_name) . ' cover photo" loading="lazy">';
        echo '</div>';
    }

    /**
     * Get cover photo URL (WordPress native version)
     * 
     * @param int $user_id User ID
     * @return string|null Cover photo URL or null
     */
    private function get_cover_photo_url(int $user_id): ?string
    {
        $cover_photo = get_user_meta($user_id, 'cover_photo', true);
        if (empty($cover_photo)) {
            return null;
        }

        $upload_dir = wp_upload_dir();
        return esc_url($upload_dir['baseurl'] . '/users/' . $user_id . '/' . $cover_photo);
    }
} 
