<?php

/**
 * Profile Fields Configuration REST Controller
 *
 * Admin-only endpoints for managing field definitions and avatar settings.
 *
 * @package ArraySubs\Features\ProfileFields\REST
 * @since 1.9.0
 */

namespace ArraySubs\Features\ProfileFields\REST;

defined('ABSPATH') || exit;

use ArraySubs\Supports\BaseRestController;

/**
 * Field configuration REST controller.
 */
class FieldConfigController extends BaseRestController
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Register REST routes.
     *
     * @return void
     */
    public function registerRoutes(): void
    {
        register_rest_route(
            $this->namespace,
            '/profile-fields/config',
            [
                [
                    'methods'             => 'GET',
                    'callback'            => [$this, 'getConfig'],
                    'permission_callback' => [$this, 'checkAdminPermission'],
                ],
                [
                    'methods'             => 'POST',
                    'callback'            => [$this, 'saveConfig'],
                    'permission_callback' => [$this, 'checkAdminPermission'],
                ],
            ]
        );

        register_rest_route(
            $this->namespace,
            '/profile-fields/user/(?P<user_id>[\d]+)',
            [
                [
                    'methods'             => 'GET',
                    'callback'            => [$this, 'getUserData'],
                    'permission_callback' => [$this, 'checkAdminPermission'],
                    'args'                => [
                        'user_id' => [
                            'required'          => true,
                            'type'              => 'integer',
                            'sanitize_callback' => 'absint',
                        ],
                    ],
                ],
            ]
        );
    }

    /**
     * Check admin permission.
     *
     * @return bool
     */
    public function checkAdminPermission(): bool
    {
        if (!is_user_logged_in()) {
            return false;
        }

        return current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }

    /**
     * Get profile fields configuration and avatar settings.
     *
     * @return \WP_REST_Response
     */
    public function getConfig(): \WP_REST_Response
    {
        return arraysubs_rest_response(
            [
                'fields'                        => arraysubs_get_profile_fields_config(),
                'avatar_settings'               => arraysubs_get_avatar_settings(),
                'custom_profile_fields_enabled' => arraysubs_is_custom_profile_fields_enabled(),
            ],
            200,
            esc_html__('Configuration retrieved', 'arraysubs')
        );
    }

    /**
     * Save profile fields configuration and avatar settings.
     *
     * @param \WP_REST_Request $request REST request.
     * @return \WP_REST_Response
     */
    public function saveConfig(\WP_REST_Request $request): \WP_REST_Response
    {
        $params = $request->get_json_params();

        if (array_key_exists('custom_profile_fields_enabled', $params)) {
            arraysubs_update_setting(
                'profile_builder.custom_profile_fields_enabled',
                (bool) $params['custom_profile_fields_enabled']
            );
        }

        if (isset($params['fields']) && is_array($params['fields'])) {
            arraysubs_save_profile_fields_config($params['fields']);
        }

        if (isset($params['avatar_settings']) && is_array($params['avatar_settings'])) {
            arraysubs_save_avatar_settings($params['avatar_settings']);
        }

        return arraysubs_rest_response(
            [
                'fields'                        => arraysubs_get_profile_fields_config(),
                'avatar_settings'               => arraysubs_get_avatar_settings(),
                'custom_profile_fields_enabled' => arraysubs_is_custom_profile_fields_enabled(),
            ],
            200,
            esc_html__('Configuration saved', 'arraysubs')
        );
    }

    /**
     * Get profile field data for a specific user (admin view).
     *
     * @param \WP_REST_Request $request REST request.
     * @return \WP_REST_Response
     */
    public function getUserData(\WP_REST_Request $request): \WP_REST_Response
    {
        $user_id = absint($request->get_param('user_id'));
        $user    = get_userdata($user_id);

        if (!$user) {
            return arraysubs_rest_response(null, 404, esc_html__('User not found', 'arraysubs'));
        }

        $fields      = arraysubs_get_enabled_profile_fields();
        $field_values = [];

        foreach ($fields as $field) {
            $value = arraysubs_get_user_profile_field($user_id, $field['key']);

            if ('upload' === $field['type'] && !empty($value)) {
                $upload_dir = arraysubs_get_profile_upload_dir($user_id);
                $field_values[$field['key']] = [
                    'value'    => $value,
                    'url'      => $upload_dir['url'] . '/' . $value,
                    'filename' => basename($value),
                ];
            } else {
                $field_values[$field['key']] = $value;
            }
        }

        $avatar_data = arraysubs_get_user_avatar($user_id);

        return arraysubs_rest_response(
            [
                'user_id'      => $user_id,
                'display_name' => $user->display_name,
                'email'        => $user->user_email,
                'fields'       => $field_values,
                'avatar'       => [
                    'has_avatar' => $avatar_data['has_avatar'],
                    'url'        => $avatar_data['has_avatar'] ? $avatar_data['url'] : '',
                    'gravatar'   => get_avatar_url($user_id, ['size' => 150]),
                ],
            ],
            200,
            esc_html__('User profile data retrieved', 'arraysubs')
        );
    }
}
