<?php
/**
 * User Tabs Frontend Handler
 *
 * Handles frontend script enqueuing and localization
 *
 * @since 4.2.0
 * @package WPUF\UserDirectory
 */

namespace WPUF\UserDirectory;

/**
 * UserTabsFrontend class
 */
class UserTabsFrontend {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'wp_head', array( $this, 'output_user_context' ) );
    }

    /**
     * Enqueue frontend scripts
     */
    public function enqueue_scripts() {
        // Only enqueue if user tabs block is present
        if ( $this->has_user_tabs_block() ) {
            $asset_file = include plugin_dir_path( __FILE__ ) . '../assets/js/user-tabs-frontend.asset.php';

            wp_enqueue_script(
                'wpuf-user-tabs-frontend',
                plugin_dir_url( __FILE__ ) . '../assets/js/user-tabs-frontend.js',
                $asset_file['dependencies'],
                $asset_file['version'],
                true
            );

            // Localize script with necessary data
            wp_localize_script( 'wpuf-user-tabs-frontend', 'wpufUserTabs', array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce'   => wp_create_nonce( 'wpuf_user_tabs_nonce' ),
                'userId'  => $this->get_current_user_id(),
                'userObject' => $this->get_current_user_object(),
                'labels'  => array(
                    'about'    => __( 'About', 'wpuf-pro' ),
                    'posts'    => __( 'Posts', 'wpuf-pro' ),
                    'comments' => __( 'Comments', 'wpuf-pro' ),
                ),
                'settings' => array(
                    'postsPerPage' => apply_filters( 'wpuf_user_tabs_posts_per_page', 10 ),
                    'commentsPerPage' => apply_filters( 'wpuf_user_tabs_comments_per_page', 10 ),
                    'excerptLength' => apply_filters( 'wpuf_user_tabs_excerpt_length', 20 ),
                    'commentLength' => apply_filters( 'wpuf_user_tabs_comment_length', 100 ),
                )
            ) );
        }
    }

    /**
     * Output user context in head for JavaScript
     */
    public function output_user_context() {
        if ( $this->has_user_tabs_block() ) {
            $user_id = $this->get_current_user_id();
            $user_object = $this->get_current_user_object();

            echo '<script type="text/javascript">';
            echo 'window.wpufUserTabsContext = ' . wp_json_encode( array(
                'userId' => $user_id,
                'userObject' => $user_object,
                'isLoggedIn' => is_user_logged_in(),
                'currentUrl' => esc_url_raw( $_SERVER['REQUEST_URI'] ?? '' ),
            ) ) . ';';
            echo '</script>';
        }
    }

    /**
     * Check if current page has user tabs block
     *
     * @return bool
     */
    private function has_user_tabs_block() {
        global $post;

        if ( ! $post ) {
            return false;
        }

        // Check if block exists in post content
        return has_block( 'wpuf-ud/tabs', $post );
    }

    /**
     * Get current user ID based on context
     *
     * @return int|null User ID
     */
    private function get_current_user_id() {
        // Check URL parameters first
        $user_id = $this->get_user_id_from_url();

        if ( $user_id ) {
            return $user_id;
        }

        // Fallback to logged-in user
        return get_current_user_id() ?: null;
    }

    /**
     * Get user ID from URL parameters
     *
     * @return int|null User ID
     */
    private function get_user_id_from_url() {
        // Check for username parameter
        $username = sanitize_text_field( $_GET['username'] ?? '' );
        if ( $username ) {
            $user = get_user_by( 'login', $username );
            return $user ? $user->ID : null;
        }

        // Check for user_id parameter
        $user_id = absint( $_GET['user_id'] ?? 0 );
        if ( $user_id ) {
            $user = get_user_by( 'id', $user_id );
            return $user ? $user->ID : null;
        }

        return null;
    }

    /**
     * Get current user object
     *
     * @return array|null User data
     */
    private function get_current_user_object() {
        $user_id = $this->get_current_user_id();

        if ( ! $user_id ) {
            return null;
        }

        $user = get_user_by( 'id', $user_id );

        if ( ! $user ) {
            return null;
        }

        return array(
            'id'          => $user->ID,
            'username'    => $user->user_login,
            'user_email'  => $user->user_email,
            'displayName' => $user->display_name,
            'firstName'   => $user->first_name,
            'lastName'    => $user->last_name,
            'description' => $user->description,
            'user_url'    => $user->user_url,
            'avatar'      => get_avatar_url( $user->ID ),
            'roles'       => $user->roles,
            'meta'        => $this->get_user_meta_data( $user->ID ),
        );
    }

    /**
     * Get relevant user meta data
     *
     * @param int $user_id User ID
     * @return array User meta data
     */
    private function get_user_meta_data( $user_id ) {
        $meta_keys = apply_filters( 'wpuf_user_tabs_meta_keys', array(
            'phone',
            'website',
            'facebook',
            'twitter',
            'linkedin',
            'instagram',
            'youtube',
        ) );

        $meta_data = array();

        foreach ( $meta_keys as $key ) {
            $value = get_user_meta( $user_id, $key, true );
            if ( $value ) {
                $meta_data[ $key ] = $value;
            }
        }

        return $meta_data;
    }
}

// Initialize the class
new UserTabsFrontend();
