<?php

$main_class = 'GDPRBoard';

use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\ContentBundle\Util\MenuUtil;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Email\UserDataEmail;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class GDPRBoard extends Frame
{
    protected $template = 'board/gdpr.tpl';

    protected $agreements = [
        ['label' => 'shopping-rules', 'name' => 'Všeobecné obchodní podmínky', 'selected_page' => null],
        ['label' => 'privacy_policy', 'name' => 'Zásady zpracování osobních údajů', 'selected_page' => null],
        ['label' => 'consent', 'name' => 'Souhlas se zpracováním OÚ', 'selected_page' => null],
    ];

    protected $gdpr_checklist = [
        ['Nastavení souhlasů', 'Vaše nastavení je v pořádku.', 'Vaše nastavení není v pořádku.'],
        ['Cookie lišta', 'Vaše nastavení je v pořádku.', 'Vaše nastavení není v pořádku.'],
    ];

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

        $qb = sqlQueryBuilder()->select('id', 'name', 'code as label')->from('menu_links')
            ->where(Operator::equals(['type' => MenuUtil::TYPE_PAGE]))
            ->orderBy('name');
        $pages = $qb->execute()->fetchAll();

        $check = true;
        foreach ($this->agreements as $key => &$agreement) {
            $label = $agreement['label'];
            $filter_pages = array_filter($pages, function ($v) use ($label) { return $v['label'] == $label; });
            $selected_page = reset($filter_pages);
            if ($selected_page) {
                $this->agreements[$key]['selected_page'] = $selected_page['id'];
            } else {
                $check = false;
            }
        }
        if ($check) {
            $checklist[] = ['name' => $this->gdpr_checklist[0][0], 'ok' => $check, 'message' => $this->gdpr_checklist[0][1]];
        } else {
            $checklist[] = ['name' => $this->gdpr_checklist[0][0], 'ok' => $check, 'message' => $this->gdpr_checklist[0][2]];
        }

        $settings = Settings::getDefault();
        $check = isset($settings->cookie_bar) && ($settings->cookie_bar['show_reject_btn'] == 'Y') && ($settings->cookie_bar['focus_close'] == 'Y') && ($settings->cookie_bar['preselect'] == 'N') && ($settings->cookie_bar['enable'] == 'Y');

        if ($check) {
            $checklist[] = ['name' => $this->gdpr_checklist[1][0], 'ok' => $check, 'message' => $this->gdpr_checklist[1][1]];
        } else {
            $checklist[] = ['name' => $this->gdpr_checklist[1][0], 'ok' => $check, 'message' => $this->gdpr_checklist[1][2]];
        }

        $vars['body']['agreements'] = $this->agreements;
        $vars['body']['html_pages'] = $pages;
        $vars['body']['checklist'] = $checklist;

        return $vars;
    }

    public function handleUpdateAgreements()
    {
        $data = getVal('data');
        foreach ($this->agreements as $key => $agreement) {
            $label = $agreement['label'];
            sqlQueryBuilder()->update('menu_links')
                ->directValues(['code' => null])
                ->where(Query\Operator::equals(['code' => $label]))
                ->execute();

            $selected_page = getVal($label, $data);
            if ($selected_page) {
                sqlQueryBuilder()->update('menu_links')
                    ->directValues(['code' => $label])
                    ->where(Query\Operator::equals(['id' => $selected_page]))
                    ->execute();
            }
        }

        $this->returnOK();
    }

    public function handleSendUserData()
    {
        $email = getVal('email');
        $email = strtolower(trim($email));
        if (!empty($email)) {
            $user_data = $this->getUserData($email);
            $contextManager = ServiceContainer::getService(ContextManager::class);
            $emailService = ServiceContainer::getService(UserDataEmail::class);
            $message = null;
            $contextManager->activateContexts(
                [LanguageContext::class => $user_data['user']['id_language'] ?? null],
                function () use (&$message, $emailService, $email) {
                    $message = $emailService->getEmail(['EMAIL' => $email]);
                }
            );
            $message['to'] = $email;
            $settings = Settings::getDefault();
            $order_shopkeeper_mail = $settings->order_shopkeeper_mail;
            $data = json_encode($user_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

            $message['attachments'][] = ['text' => $data, 'filename' => 'user_data.txt'];
            $message['template']['attachments'] = $message['attachments'];

            $sent = $emailService->sendEmail($message);
            if ($sent) {
                if ($order_shopkeeper_mail) {
                    $message = ['body' => "<p>údaje o zákazníkovi byly úspěšně odeslány na e-mail <strong>{$email}</strong></p>", 'subject' => 'Potvrzení odeslání údajů o zákazníkovi'];
                    $shopkeeperMessage = $emailService->renderEmail($message);
                    $shopkeeperMessage['to'] = $order_shopkeeper_mail;
                    $emailService->sendEmail($shopkeeperMessage);
                }

                $this->returnOK("Odesláno na email {$email}");
            } else {
                $this->returnError("Nepodařilo se odeslat na email {$email}");
            }
        } else {
            $this->returnError('Zadejte e-mail');
        }
    }

    public function getUserData($email)
    {
        $user_data['email'] = $email;
        $user = sqlQueryBuilder()->select('*')
            ->from('users')
            ->where('LOWER(email) = :email')
            ->setParameter('email', $email)
            ->execute()->fetch();
        if ($user) {
            // removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
            $user = array_filter($user, 'strlen');
        }
        $user_data['user'] = $user;

        $orders = sqlQueryBuilder()->select('*')
            ->from('orders')
            ->where('LOWER(invoice_email) = :email')
            ->setParameter('email', $email)
            ->execute()->fetchAll();
        foreach ($orders as $key => $order) {
            $orders[$key] = array_filter($order, 'strlen');
        }
        $user_data['orders'] = $orders;

        return $user_data;
    }

    public function handleUpdateStatus()
    {
        $data = getVal('data');
        if (!empty($data)) {
            $settings = Settings::getDefault();

            if ($data['cookie_bar']['focus'] != $settings->cookie_bar['focus']) {
                getRaven()->captureMessage('GDPR: měněná cookie lišta / vyskakovací okno');
            }

            $settings->loadFromArray($data);

            addActivityLog(ActivityLog::SEVERITY_NOTICE, ActivityLog::TYPE_SECURITY, 'GDPR nastavení aktualizováno.', $data);

            foreach ($settings as $key => $value) {
                $saved = $settings->saveValue($key, $value);
            }
            Settings::clearCache();
            if ($saved) {
                $this->returnOK();
            } else {
                $this->returnError('Chyba při ukládání');
            }
        }
    }
}
