<commit_before><?php

namespace Application\Bundle\DefaultBundle\Controller;

use Application\Bundle\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Stfalcon\Bundle\EventBundle\Entity\Event;
use Stfalcon\Bundle\EventBundle\Entity\Ticket;
use Stfalcon\Bundle\EventBundle\Entity\Payment;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Stfalcon\Bundle\EventBundle\Entity\Mail;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

/**
 * Class AdminController.
 */
class AdminController extends Controller
{
    /**
     * @Route("/admin/event/{slug}/users/add", name="adminusersadd")
     *
     * @Security("has_role('ROLE_ADMIN')")
     *
     * @param Event $event
     *
     * @Template()
     *
     * @return array
     */
    public function addUsersAction(Event $event)
    {
        // @todo удалить этот метод. одноразовый харкод
        $em = $this->getDoctrine()->getManager();

        if (isset($_POST['users'])) {
            $users = explode("\r\n", $_POST['users']);

            foreach ($users as $data) {
                // данные с формы
                $dt = explode(' ', $data);
                unset($data);
                $data['name'] = $dt[0];
                $data['surname'] = $dt[1];
                $data['email'] = $dt[2];
                $data['discount'] = isset($dt[3]);

                $user = $this->get('fos_user.user_manager')->findUserBy(array('email' => $data['email']));

                // создаем нового пользователя
                if (!$user) {
                    /** @var User $user */
                    $user = $this->get('fos_user.user_manager')->createUser();
                    $user->setEmail($data['email'])
                        ->setName($data['name'])
                        ->setSurname($data['surname']);

                    // генерация временного пароля
                    $password = substr(str_shuffle(md5(time())), 5, 8);
                    $user->setPlainPassword($password);
                    $user->setEnabled(true);

                    $errors = $this->container->get('validator')->validate($user);
                    if ($errors->count() > 0) {
                        echo 'User create Bad credentials!';
                        exit;
                    }

                    $this->get('fos_user.user_manager')->updateUser($user);

                    // отправляем сообщение о регистрации
                    $body = $this->container->get('stfalcon_event.mailer_helper')->renderTwigTemplate(
                        'ApplicationUserBundle:Registration:automatically.html.twig',
                        [
                            'user' => $user,
                            'plainPassword' => $password,
                        ]
                    );

                    $message = \Swift_Message::newInstance()
                        ->setSubject('Регистрация на сайте Frameworks Days')
                        // @todo refact
                        ->setFrom('<EMAIL>', 'Fwdays')
                        ->setTo($user->getEmail())
                        ->setBody($body, 'text/html');

                    // @todo каждый вызов отнимает память
                    $this->get('mailer')->send($message);

                    echo "#{$user->getId()} {$user->getFullname()} — Create a new user<br>";
                } else {
                    echo "<b>#{$user->getId()} {$user->getFullname()} — already registered</b><br>";
                }

                // обновляем информацию о компании
                $user->setCountry('Украина');
                if (isset($_POST['city'])) {
                    $user->setCity($_POST['city']);
                }

                $user->setCompany($_POST['company']);
                $em->persist($user);
                $em->flush();

                // проверяем или у него нет билетов на этот ивент
                /** @var Ticket $ticket */
                $ticket = $em->getRepository('StfalconEventBundle:Ticket')
                    ->findOneBy(array('event' => $event->getId(), 'user' => $user->getId()));

                if (!$ticket) {
                    $ticket = new Ticket();
                    $ticket->setEvent($event);
                    $ticket->setUser($user);

                    $em->persist($ticket);
                }

                if ($ticket->isPaid()) {
                    echo '<b>he has already paid participation in the conference!</b><br>';
                } else {
                    // цена участия (с учетом скидки)
                    $amount = $data['discount'] ? $_POST['amount'] * 0.8 : $_POST['amount'];
                    $ticket->setAmount($amount);
                    $ticket->setHasDiscount($data['discount']);
                    $ticket->setAmountWithoutDiscount($_POST['amount']);

                    $oldPayment = $ticket->getPayment();

                    if ($oldPayment) {
                        $oldPayment->removeTicket($ticket);
                    }
                    echo 'create a new payment<br>';
                    $payment = (new Payment())
                        ->setUser($user)
                        ->setAmount($ticket->getAmount())
                        ->setBaseAmount($ticket->getAmountWithoutDiscount())
                        ->setGate('admin');
                    $payment->addTicket($ticket);
                    $ticket->setPayment($payment);
                    $payment->markedAsPaid();

                    $em->persist($payment);

                    $em->flush();
                    echo 'mark as paid<br>';
                }
            }

            echo 'complete';
            exit;
        }

        return [];
    }

    /**
     * Widget share contacts.
     *
     * @return Response
     */<commit_msg>Fix admin user ticket<commit_after><?php

namespace Application\Bundle\DefaultBundle\Controller;

use Application\Bundle\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Stfalcon\Bundle\EventBundle\Entity\Event;
use Stfalcon\Bundle\EventBundle\Entity\Ticket;
use Stfalcon\Bundle\EventBundle\Entity\Payment;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Stfalcon\Bundle\EventBundle\Entity\Mail;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

/**
 * Class AdminController.
 */
class AdminController extends Controller
{
    /**
     * @Route("/admin/event/{slug}/users/add", name="adminusersadd")
     *
     * @Security("has_role('ROLE_ADMIN')")
     *
     * @param Event $event
     *
     * @Template()
     *
     * @return array
     */
    public function addUsersAction(Event $event)
    {
        // @todo удалить этот метод. одноразовый харкод
        $em = $this->getDoctrine()->getManager();

        if (isset($_POST['users'])) {
            $users = explode("\r\n", $_POST['users']);

            foreach ($users as $data) {
                // данные с формы
                $dt = explode(' ', $data);
                unset($data);
                $data['name'] = $dt[0];
                $data['surname'] = $dt[1];
                $data['email'] = $dt[2];
                $data['discount'] = isset($dt[3]);

                $user = $this->get('fos_user.user_manager')->findUserBy(array('email' => $data['email']));

                // создаем нового пользователя
                if (!$user) {
                    /** @var User $user */
                    $user = $this->get('fos_user.user_manager')->createUser();
                    $user->setEmail($data['email'])
                        ->setName($data['name'])
                        ->setSurname($data['surname']);

                    // генерация временного пароля
                    $password = substr(str_shuffle(md5(time())), 5, 8);
                    $user->setPlainPassword($password);
                    $user->setEnabled(true);

                    $errors = $this->container->get('validator')->validate($user);
                    if ($errors->count() > 0) {
                        echo 'User create Bad credentials!';
                        exit;
                    }

                    $this->get('fos_user.user_manager')->updateUser($user);

                    // отправляем сообщение о регистрации
                    $body = $this->container->get('stfalcon_event.mailer_helper')->renderTwigTemplate(
                        'ApplicationUserBundle:Registration:automatically.html.twig',
                        [
                            'user' => $user,
                            'plainPassword' => $password,
                        ]
                    );

                    $message = \Swift_Message::newInstance()
                        ->setSubject('Регистрация на сайте Frameworks Days')
                        // @todo refact
                        ->setFrom('<EMAIL>', 'Fwdays')
                        ->setTo($user->getEmail())
                        ->setBody($body, 'text/html');

                    // @todo каждый вызов отнимает память
                    $this->get('mailer')->send($message);

                    echo "#{$user->getId()} {$user->getFullname()} — Create a new user<br>";
                } else {
                    echo "<b>#{$user->getId()} {$user->getFullname()} — already registered</b><br>";
                }

                // обновляем информацию о компании
                $user->setCountry('Украина');
                if (isset($_POST['city'])) {
                    $user->setCity($_POST['city']);
                }

                $user->setCompany($_POST['company']);
                $em->persist($user);
                $em->flush();

                // проверяем или у него нет билетов на этот ивент
                /** @var Ticket $ticket */
                $ticket = $em->getRepository('StfalconEventBundle:Ticket')
                    ->findOneBy(array('event' => $event->getId(), 'user' => $user->getId()));

                if (!$ticket) {
                    $ticket = new Ticket();
                    $ticket->setEvent($event);
                    $ticket->setUser($user);

                    $em->persist($ticket);
                }

                if ($ticket->isPaid()) {
                    echo '<b>he has already paid participation in the conference!</b><br>';
                } else {
                    // цена участия (с учетом скидки)
                    $amount = $data['discount'] ? $_POST['amount'] * 0.8 : $_POST['amount'];
                    $ticket->setAmount($amount);
                    $ticket->setHasDiscount($data['discount']);
                    $ticket->setAmountWithoutDiscount($_POST['amount']);

                    $oldPayment = $ticket->getPayment();

                    if ($oldPayment) {
                        $oldPayment->removeTicket($ticket);
                        $em->persist($oldPayment);
                    }
                    echo 'create a new payment<br>';
                    $payment = (new Payment())
                        ->setUser($user)
                        ->setAmount($ticket->getAmount())
                        ->setBaseAmount($ticket->getAmountWithoutDiscount())
                        ->setGate('admin');
                    $payment->addTicket($ticket);
                    $ticket->setPayment($payment);
                    $em->persist($payment);
                    $em->flush();

                    $payment->markedAsPaid();
                    $em->flush();

                    echo 'mark as paid<br>';
                }
            }

            echo 'complete';
            exit;
        }

        return [];
    }

    /**
     * Widget share contacts.
     *
     * @return Response
     */
{'fraction_non_alphanumeric': 0.14225840251470945, 'fraction_numerical': 0.0016119932296284356, 'mean_word_length': 1.4835868694955965, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 157, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1116240', 'n_tokens_mistral': 3356, 'n_tokens_neox': 3161, 'n_words': 529}