<?php

namespace DZ\ImageShield\XF\Pub\Controller;

use DZ\ImageShield\Shield;
use XF;
use XF\Entity\User;
use XF\Mvc\FormAction;

class AccountController extends XFCP_AccountController
{
    /**
     * @param User $visitor
     */
    protected function preferencesSaveProcess(User $visitor): FormAction
    {
        $form = parent::preferencesSaveProcess($visitor);

        if ($visitor->hasPermission('general', 'dzImageShield_toggle')) {
            $option = $this->filter([
                'option' => [
                    'dz_is_enabled' => 'uint',
                ],
            ]);
            $form->setupEntityInput($visitor->Option, [
                'dz_is_enabled' => $option['option']['dz_is_enabled'],
            ]);
        }

        if ($visitor->hasPermission('general', 'dzImageShield_customText')) {
            $input = $this->filter([
                'dzImageShield_mode' => 'str',
                'dzImageShield_text' => 'str',
            ]);

            if ($input['dzImageShield_mode'] === 'custom') {
                if (strlen($input['dzImageShield_text']) === 0) {
                    throw $this->errorException(XF::phrase('please_enter_valid_value'));
                }

                if (strlen($input['dzImageShield_text']) > 25) {
                    throw $this->errorException(XF::phrase('please_enter_value_using_x_characters_or_fewer', [
                        'count' => 25,
                    ]));
                }
            }

            Shield::storeUserOverlayText(
                $visitor->user_id,
                $input['dzImageShield_mode'] === 'custom' ? $input['dzImageShield_text'] : ''
            );
        }

        return $form;
    }
}
