<?php

/**
 * Avatar REST Controller
 *
 * Customer-facing endpoints for avatar upload and removal via AJAX.
 *
 * @package ArraySubs\Features\ProfileFields\REST
 * @since 1.9.0
 */

namespace ArraySubs\Features\ProfileFields\REST;

defined('ABSPATH') || exit;

use ArraySubs\Supports\BaseRestController;

/**
 * Avatar REST controller.
 */
class AvatarController extends BaseRestController
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Register REST routes.
     *
     * @return void
     */
    public function registerRoutes(): void
    {
        register_rest_route(
            $this->namespace,
            '/profile-fields/avatar',
            [
                [
                    'methods'             => 'POST',
                    'callback'            => [$this, 'uploadAvatar'],
                    'permission_callback' => [$this, 'checkCustomerPermission'],
                ],
                [
                    'methods'             => 'DELETE',
                    'callback'            => [$this, 'removeAvatar'],
                    'permission_callback' => [$this, 'checkCustomerPermission'],
                ],
            ]
        );
    }

    /**
     * Check that the user is logged in.
     *
     * @return bool
     */
    public function checkCustomerPermission(): bool
    {
        return is_user_logged_in();
    }

    /**
     * Upload avatar for the current user.
     *
     * @param \WP_REST_Request $request REST request.
     * @return \WP_REST_Response
     */
    public function uploadAvatar(\WP_REST_Request $request): \WP_REST_Response
    {
        $avatar_settings = arraysubs_get_avatar_settings();

        if (empty($avatar_settings['enabled'])) {
            return arraysubs_rest_response(null, 403, esc_html__('Avatar uploads are not enabled.', 'arraysubs'));
        }

        $files = $request->get_file_params();

        if (empty($files['avatar'])) {
            return arraysubs_rest_response(null, 400, esc_html__('No file provided.', 'arraysubs'));
        }

        $file     = $files['avatar'];
        $max_size = ($avatar_settings['max_file_size'] ?? 2) * MB_IN_BYTES;

        if ($file['error'] !== UPLOAD_ERR_OK) {
            return arraysubs_rest_response(null, 400, esc_html__('File upload error.', 'arraysubs'));
        }

        if ($file['size'] > $max_size) {
            return arraysubs_rest_response(
                null,
                400,
                /* translators: %d: max file size in MB */
                sprintf(esc_html__('File exceeds maximum size of %d MB.', 'arraysubs'), $avatar_settings['max_file_size'])
            );
        }

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $avatar_settings['allowed_types'], true)) {
            return arraysubs_rest_response(
                null,
                400,
                esc_html__('File type not allowed.', 'arraysubs')
            );
        }

        $wp_filetype = wp_check_filetype($file['name']);
        if (empty($wp_filetype['type'])) {
            return arraysubs_rest_response(null, 400, esc_html__('Invalid file type.', 'arraysubs'));
        }

        $user_id    = get_current_user_id();
        $upload_dir = arraysubs_get_avatar_upload_dir();

        if (!file_exists($upload_dir['path'])) {
            wp_mkdir_p($upload_dir['path']);
        }

        arraysubs_protect_upload_dir($upload_dir['path']);

        arraysubs_delete_user_avatar($user_id);

        $safe_name = $user_id . '-' . wp_generate_password(12, false) . '.' . $ext;
        $dest      = $upload_dir['path'] . '/' . $safe_name;

        if (!move_uploaded_file($file['tmp_name'], $dest)) {
            return arraysubs_rest_response(null, 500, esc_html__('Failed to save file.', 'arraysubs'));
        }

        update_user_meta($user_id, 'arraysubs_avatar', $safe_name);

        $avatar_data = arraysubs_get_user_avatar($user_id);

        return arraysubs_rest_response(
            [
                'url'        => $avatar_data['url'],
                'has_avatar' => true,
            ],
            200,
            esc_html__('Avatar uploaded successfully.', 'arraysubs')
        );
    }

    /**
     * Remove avatar for the current user.
     *
     * @return \WP_REST_Response
     */
    public function removeAvatar(): \WP_REST_Response
    {
        $user_id = get_current_user_id();

        arraysubs_delete_user_avatar($user_id);

        return arraysubs_rest_response(
            [
                'url'        => get_avatar_url($user_id, ['size' => 150]),
                'has_avatar' => false,
            ],
            200,
            esc_html__('Avatar removed.', 'arraysubs')
        );
    }
}
