<?php

/**
 * Profile Fields Hooks
 *
 * Main hooks for the Profile Fields feature.
 * Enqueues assets for the frontend profile fields & avatar UI.
 *
 * @package ArraySubs\Features\ProfileFields\Services
 * @since 1.9.0
 */

namespace ArraySubs\Features\ProfileFields\Services;

defined('ABSPATH') || exit;

use ArraySubs\Supports\Config;

/**
 * Profile Fields hooks integration
 */
class Hooks
{
    /**
     * Enable auto-loading
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendAssets'], 100);
    }

    /**
     * Enqueue frontend assets for the My Account edit-account page.
     *
     * @return void
     */
    public function enqueueFrontendAssets(): void
    {
        if (!function_exists('is_account_page') || !is_account_page()) {
            return;
        }

        global $wp;

        $is_edit_account = isset($wp->query_vars['edit-account']);

        if (!$is_edit_account) {
            return;
        }

        $asset_file = Config::get('plugin.public_path') . 'build/profile-fields.asset.php';
        $asset      = file_exists($asset_file)
            ? require $asset_file
            : ['dependencies' => [], 'version' => ARRAYSUBS_VERSION];

        wp_enqueue_style(
            'arraysubs-profile-fields',
            Config::get('plugin.public_url') . 'build/profile-fields.css',
            [],
            $asset['version']
        );

        wp_enqueue_script(
            'arraysubs-profile-fields',
            Config::get('plugin.public_url') . 'build/profile-fields.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        $user_id         = get_current_user_id();
        $avatar_settings = arraysubs_get_avatar_settings();
        $avatar_data     = arraysubs_get_user_avatar($user_id);

        $json_flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;

        wp_add_inline_script(
            'arraysubs-profile-fields',
            'window.arraySubsProfileFields = ' . wp_json_encode(
                [
                    'nonce'          => wp_create_nonce('wp_rest'),
                    'apiBaseUrl'     => esc_url_raw(rest_url()),
                    'avatarEnabled'  => $avatar_settings['enabled'],
                    'avatarMaxSize'  => $avatar_settings['max_file_size'],
                    'avatarTypes'    => $avatar_settings['allowed_types'],
                    'currentAvatar'  => $avatar_data['has_avatar'] ? esc_url($avatar_data['url']) : '',
                    'hasAvatar'      => $avatar_data['has_avatar'],
                    'gravatarUrl'    => get_avatar_url($user_id, ['size' => 150]),
                    'i18n'           => [
                        'uploadAvatar'    => esc_html__('Upload Avatar', 'arraysubs'),
                        'changeAvatar'    => esc_html__('Change Avatar', 'arraysubs'),
                        'removeAvatar'    => esc_html__('Remove Avatar', 'arraysubs'),
                        'uploading'       => esc_html__('Uploading...', 'arraysubs'),
                        'fileTooLarge'    => esc_html__('File is too large.', 'arraysubs'),
                        'invalidFileType' => esc_html__('Invalid file type.', 'arraysubs'),
                        'uploadFailed'    => esc_html__('Upload failed. Please try again.', 'arraysubs'),
                        'removeFailed'    => esc_html__('Failed to remove avatar.', 'arraysubs'),
                        'chooseFile'      => esc_html__('Choose file', 'arraysubs'),
                        'noFileChosen'    => esc_html__('No file chosen', 'arraysubs'),
                        'maxSizeLabel'    => esc_html__('Max file size:', 'arraysubs'),
                    ],
                ],
                $json_flags
            ) . ';',
            'before'
        );
    }
}
