<?php

// ##############################################################
//	TENTO SKRIPT NAPROGRAMOVAL
//	UZIVANI TOHOTO DILO JE MOZNE POUZE SE SOUHLASEM AUTORA
//	KONTAKT:
// ##############################################################

use KupShop\KupShopBundle\Email\ReviewResponseEmail;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

$main_class = 'reviews';

class Reviews extends Window
{
    protected $objectId;

    public function get_vars()
    {
        $vars = parent::get_vars();

        if (isset($vars['body']['data']['id_product'])) {
            $this->objectId = $vars['body']['data']['id_product'];
            $product = Variation::createProductOrVariation($this->objectId, null);
            $product->createFromDB();

            $vars['body']['product'] = $product;
        }

        return $vars;
    }

    public function handleUpdate()
    {
        if ($this->getAction() == 'edit') {
            $this->sendResponseEmail();
        }

        return parent::handleUpdate();
    }

    public function getData()
    {
        $data = parent::getData();
        $data['date'] = $this->prepareDateTime($data['date']);
        if (!empty($data['response']) && empty($data['response_time'])) {
            $data['response_time'] = (new DateTime())->format('Y-m-d H:i:s');
        }

        return $data;
    }

    public function handleDelete()
    {
        $ID = $this->getID();
        try {
            sqlQueryBuilder()
                ->update($this->getTableName())
                ->set('figure', 0)
                ->where(\Query\Operator::equals(['id' => $this->getID()]))
                ->execute();
        } catch (\Doctrine\DBAL\DBALException $e) {
            $this->returnError('Hodnocení se nepodařilo smazat.');
        }

        writeDownActivity(sprintf(translate('activityDeleted'), $ID));

        redirect("launch.php?s={$this->getName()}.php&acn=erased");
    }

    private function sendResponseEmail()
    {
        $object = $this->getObject();
        $data = $this->getData();
        // Response already exists, empty or with no way to identify user
        if (!empty($object['response']) || empty($data['response']) || empty($data['id_order'])) {
            return;
        }

        $email = sqlQueryBuilder()->select('invoice_email')
            ->from('orders')
            ->where(\Query\Operator::equals(['id' => $data['id_order']]))
            ->execute()->fetchOne();

        if (empty($email)) {
            return;
        }

        $emailService = ServiceContainer::getService(ReviewResponseEmail::class);
        $message = $emailService->getEmail([
            'ODPOVED_HODNOCENI' => $data['response'],
        ]);
        $message['to'] = $email;
        $emailService->sendEmail($message);
    }

    public function getShowOnWeb()
    {
        if ($this->objectId === null) {
            return null;
        }

        return ['type' => 'product', 'id' => $this->objectId];
    }
}
