<?php

namespace WPUF\UserDirectory;

/**
 * Assets handler for User Directory
 *
 * Handles registration and enqueueing of CSS and JavaScript assets
 *
 * @since 4.2.0
 */
class Assets {

    /**
     * Constructor
     *
     * @since 4.2.0
     */
    public function __construct() {
        add_action( 'init', [ $this, 'register_all_scripts' ] );
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_shortcode_assets' ] );
    }

    /**
     * Register all the css and js from here
     *
     * @since 4.2.0
     *
     * @return void
     */
    public function register_all_scripts() {
        $styles  = $this->get_styles();
        $scripts = $this->get_scripts();

        do_action( 'wpuf_ud_before_register_scripts', $scripts, $styles );

        $this->register_styles( $styles );
        $this->register_scripts( $scripts );

        do_action( 'wpuf_ud_after_register_scripts', $scripts, $styles );
    }

    /**
     * Register the CSS from here. Need to define the CSS first from get_styles()
     *
     * @since 4.2.0
     *
     * @param array $styles Array of styles to register
     *
     * @return void
     */
    public function register_styles( $styles ) {
        foreach ( $styles as $handle => $style ) {
            $deps    = ! empty( $style['deps'] ) ? $style['deps'] : [];
            $version = ! empty( $style['version'] ) ? $style['version'] : WPUF_UD_VERSION;
            $media   = ! empty( $style['media'] ) ? $style['media'] : 'all';

            wp_register_style( 'wpuf-ud-' . $handle, $style['src'], $deps, $version, $media );
        }
    }

    /**
     * Register the JS from here. Need to define the JS first from get_scripts()
     *
     * @since 4.2.0
     *
     * @param array $scripts Array of scripts to register
     *
     * @return void
     */
    public function register_scripts( $scripts ) {
        foreach ( $scripts as $handle => $script ) {
            $deps      = ! empty( $script['deps'] ) ? $script['deps'] : [];
            $in_footer = ! empty( $script['in_footer'] ) ? $script['in_footer'] : true;
            $version   = ! empty( $script['version'] ) ? $script['version'] : WPUF_UD_VERSION;

            wp_register_script( 'wpuf-ud-' . $handle, $script['src'], $deps, $version, $in_footer );
        }
    }

    /**
     * Returns the list of styles
     *
     * @since 4.2.0
     *
     * @return array
     */
    public function get_styles() {
        $styles = [
            'styles'           => [
                'src' => WPUF_UD_ROOT_URI . '/assets/css/wpuf-ud.css',
            ],
            'shortcode-styles' => [
                'src'  => WPUF_UD_ROOT_URI . '/src/css/shortcode-user-directory.css',
                'deps' => [ 'wpuf-ud-styles' ],
            ],
            'avatar-upload'    => [
                'src' => WPUF_UD_ROOT_URI . '/src/css/avatar-upload.css',
            ],
            'cropperjs'        => [
                'src'     => WPUF_UD_ASSET_URI . '/vendors/cropper/cropper.min.css',
                'version' => '1.5.13',
            ],
        ];

        return apply_filters( 'wpuf_ud_styles_to_register', $styles );
    }

    /**
     * Returns the list of JS
     *
     * @since 4.2.0
     *
     * @return array
     */
    public function get_scripts() {
        $scripts = [
            'search-shortcode' => [
                'src'       => WPUF_UD_ROOT_URI . '/src/js/ud-search-shortcode.js',
                'deps'      => [ 'jquery' ],
                'in_footer' => true,
            ],
            'cropperjs'        => [
                'src'       => WPUF_UD_ASSET_URI . '/vendors/cropper/cropper.min.js',
                'deps'      => [],
                'version'   => '1.5.13',
                'in_footer' => true,
            ],
            'avatar-upload'    => [
                'src'       => WPUF_UD_ROOT_URI . '/src/js/avatar-upload.js',
                'deps'      => [ 'jquery', 'wpuf-ud-cropperjs' ],
                'in_footer' => true,
            ],
        ];

        return apply_filters( 'wpuf_ud_scripts_to_register', $scripts );
    }

    /**
     * Enqueue assets for shortcodes
     *
     * @since 4.2.0
     *
     * @return void
     */
    public function enqueue_shortcode_assets() {
        global $post;

        // Only enqueue if shortcode is present on the page
        if ( ! is_a( $post, 'WP_Post' ) ) {
            return;
        }

        // Check for both shortcode variants
        if ( ! has_shortcode( $post->post_content, 'wpuf_user_listing' ) &&
             ! has_shortcode( $post->post_content, 'wpuf_user_listing_id' ) ) {
            return;
        }

        $this->enqueue_directory_scripts();
        $this->enqueue_directory_styles();

        // If this is a profile view, enqueue avatar upload assets
        if ( $this->is_profile_view() ) {
            $this->enqueue_avatar_upload_assets();
        }
    }

    /**
     * Check if current request is a profile view
     *
     * @since 4.2.0
     *
     * @return bool
     */
    private function is_profile_view() {
        // Check for pretty URL query var (set by rewrite rules)
        if ( get_query_var( 'wpuf_user' ) ) {
            return true;
        }

        // Check for various profile URL parameters
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $profile_params = [ 'user_id', 'id', 'username', 'user', 'wpuf_profile_user' ];
        foreach ( $profile_params as $param ) {
            if ( ! empty( $_GET[$param] ) ) {
                return true;
            }
        }
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        return false;
    }

    /**
     * Enqueue directory JavaScript files
     *
     * @since 4.2.0
     *
     * @return void
     */
    private function enqueue_directory_scripts() {
        // Enqueue the shortcode-specific search functionality script
        wp_enqueue_script( 'wpuf-ud-search-shortcode' );

        // Localize script for AJAX
        wp_localize_script( 'wpuf-ud-search-shortcode', 'wpufUserDirectory', [
            'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
            'restUrl'     => rest_url( 'wpuf/v1/' ),
            'nonce'       => wp_create_nonce( 'wp_rest' ),
            'isShortcode' => true,
        ] );
    }

    /**
     * Enqueue directory CSS files
     *
     * @since 4.2.0
     *
     * @return void
     */
    private function enqueue_directory_styles() {
        // Enqueue the main styles
        wp_enqueue_style( 'wpuf-ud-styles' );

        // Enqueue shortcode-specific styles
        wp_enqueue_style( 'wpuf-ud-shortcode-styles' );
    }

    /**
     * Enqueue avatar upload assets
     *
     * @since 4.2.0
     *
     * @return void
     */
    public function enqueue_avatar_upload_assets() {
        // Enqueue Cropper.js library (CSS and JS)
        wp_enqueue_style( 'wpuf-ud-cropperjs' );
        wp_enqueue_script( 'wpuf-ud-cropperjs' );

        // Enqueue avatar upload styles
        wp_enqueue_style( 'wpuf-ud-avatar-upload' );

        // Enqueue avatar upload script
        wp_enqueue_script( 'wpuf-ud-avatar-upload' );

        // Localize script with required data
        wp_localize_script(
            'wpuf-ud-avatar-upload',
            'wpuf_ud',
            [
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce'   => wp_create_nonce( 'wpuf_avatar_upload_nonce' ),
            ]
        );
    }

    /**
     * Register a custom script
     *
     * @since 4.2.0
     *
     * @param string $handle Script handle
     * @param string $src Script source URL
     * @param array $deps Dependencies
     * @param string|bool $ver Version
     * @param bool $in_footer Load in footer
     *
     * @return void
     */
    public function register_script( $handle, $src, $deps = [], $ver = false, $in_footer = true ) {
        wp_register_script( $handle, $src, $deps, $ver, $in_footer );
    }

    /**
     * Register a custom style
     *
     * @since 4.2.0
     *
     * @param string $handle Style handle
     * @param string $src Style source URL
     * @param array $deps Dependencies
     * @param string|bool $ver Version
     * @param string $media Media type
     *
     * @return void
     */
    public function register_style( $handle, $src, $deps = [], $ver = false, $media = 'all' ) {
        wp_register_style( $handle, $src, $deps, $ver, $media );
    }

    /**
     * Enqueue a registered script
     *
     * @since 4.2.0
     *
     * @param string $handle Script handle
     *
     * @return void
     */
    public function enqueue_script( $handle ) {
        wp_enqueue_script( $handle );
    }

    /**
     * Enqueue a registered style
     *
     * @since 4.2.0
     *
     * @param string $handle Style handle
     *
     * @return void
     */
    public function enqueue_style( $handle ) {
        wp_enqueue_style( $handle );
    }
}

