<?php

namespace KupShop\BonusProgramBundle\Admin\Actions;

use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;
use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\BonusProgramBundle\BonusProgramBundle;
use Query\Operator;

class EditBonusPointsAction extends AbstractAction implements IAction
{
    public function getTypes(): array
    {
        return ['users'];
    }

    public function getName(): string
    {
        return translate('addOrRemovePoints', 'bonus_program');
    }

    public function showInMassEdit()
    {
        return true;
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        $result = new ActionResult(true);
        $userId = $this->getId();

        if (empty($config['bonusPoints'])) {
            return new ActionResult(false, translate('noPointsEntered', 'bonus_program'));
        }

        $bonusPoints = $config['bonusPoints'];
        $adminNote = trim($config['adminNote']) == '' ? translate('notePlaceholder', 'bonus_program') : $config['adminNote'];
        $status = $config['status'] ?? 'active';

        $newPoints = [
            'id_user' => $userId,
            'points' => $bonusPoints,
            'note' => $adminNote,
            'status' => $status,
        ];

        sqlQueryBuilder()
            ->insert('bonus_points')
            ->directValues($newPoints)
            ->setValue('date_created', 'NOW()')
            ->execute();

        $userEmail = sqlQueryBuilder()
            ->select('email')
            ->from('users', 'u')
            ->where(Operator::equals(['id' => $userId]))
            ->execute()
            ->fetchOne();

        addActivityLog(
            ActivityLog::SEVERITY_NOTICE,
            ActivityLog::TYPE_CHANGE,
            sprintf('Provedena ruční úprava bodů u uživatele "%s": '.$bonusPoints, $userEmail ?? ''),
            $newPoints,
            [BonusProgramBundle::LOG_TAG_BONUS_PROGRAM]
        );

        return $result;
    }
}
