<?php declare(strict_types=1);

namespace Diamond\Modules\AdminMailingList;


use ActiveTable\ColumnTable;
use Core\Form\Control\MenuItemAction;
use Core\Form\Control\MenuItemWindow;
use Core\Form\ControlBuilder;
use Core\Template\Template;
use Diamond\Domain\MailingList\Concrete\MailingListEntityInterface;
use Diamond\Helpers\Form;
use Diamond\Repositories\MailingList\MailingListCriteria;
use Diamond\Repositories\MailingSubscriber\MailingSubscriberCriteria;
use Diamond\Repositories\MailingTemplate\MailingTemplateCriteria;
use Diamond\Application\Mailing\MailingService;
use DiamondTable\TableFactory;
use Core\ModuleController;


class AdminMailingList extends ModuleController
{

    public function __construct(
        private TableFactory   $tableFactory,
        private ControlBuilder $controlBuilder,
        private Template       $template,
        private MailingService $mailingService
    )
    {
    }


    public function process(): string
    {
        $table = $this->tableFactory->buildAdminTable($this->mailingService->getMailingListRepository(), MailingListCriteria::create());

        $this->template->addScript($this->render('javascript'));
        $this->template->addScriptLink('/_diamond/diamond-cms/assets/nifty/plugins/easy-pie-chart/jquery.easypiechart.min.js');

        $table
            ->addRowActionCommand(
                'send-selected', new SendMailingCommand($table, $this->mailingService), '<i class="demo-pli-paper-plane"></i> Запустить рассылку'
            );

        $table
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('matId', 'Наименование шаблона'))
                    ->setFormat($this, 'columnTemplate')
            )
            ->addColumn(
                (new ColumnTable('subId', 'Подписчики'))
                    ->setFormat($this, 'columnSubscribes')
            )
            ->addColumn(
                (new ColumnTable('progress', 'Прогресс'))
                    ->setFormat($this, 'columnProgress')
            )
            ->addColumn(
                (new ColumnTable('views', 'Просмотров / Отправлений'))
                    ->setFormat($this, 'columnViews')
            )
            ->addColumn(
                (new ColumnTable('views', 'Ошибки'))
                    ->setFormat($this, 'columnErrors')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this, 'columnActions')
                    ->setWidth(120)
            );

        $templates = $this->mailingService->getMailingTemplateRepository()->findByCriteria(MailingTemplateCriteria::create());
        $subscribes = $this->mailingService->getMailingSubscriberRepository()->findByCriteria(MailingSubscriberCriteria::create());

        $table
            ->addField(
                $this->controlBuilder->buildDropdownUniform('matId', Form::prepareDropdown($templates)), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('subId', Form::prepareDropdown($subscribes)), true
            );

        $table->addFilter(
            $this->controlBuilder->buildInput('filter_by_id')
        );

        return $table->render();
    }


    public function columnErrors(MailingListEntityInterface $mailing): string
    {
        if (!$progressData = $mailing->getProgressData()) {
            return '';
        }

        if (!$progressData->getErrors()) {
            $res = (string)$progressData->getErrors();
        } else {
            $res = sprintf('<span class="text-danger">%s</span>', $progressData->getErrors());
        }


        return $res;
    }

    public function columnActions(MailingListEntityInterface $listEntity): string
    {

        $items = [
            new MenuItemWindow(admin_path('/diamond/mailing/mailing_list_demo') . '?id=' . $listEntity->getId(), 'Предпросмотр', 'demo-pli-magnifi-glass'),
            new MenuItemAction($listEntity->getId(), 'send-selected', 'Запустить', 'Запустить рассылку?', 'demo-pli-paper-plane')
        ];

        $progressData = $listEntity->getProgressData();

        $request = $progressData ? $listEntity->getProgressData()->getLastRequest() : null;

        if ($request) {
            $items[] = new MenuItemWindow(admin_path('/diamond/mailing/mailing_list_report') . '?request_id=' . $request->getId(), 'Отчет', 'demo-psi-bar-chart');
        }

        return $this->controlBuilder->buildActionMenuAdmin($items, $listEntity->getId())->render();
    }

    public function columnProgress(MailingListEntityInterface $mailing): string
    {

        if (!$progressData = $mailing->getProgressData()) {
            return '';
        }

        $progress = $progressData->getProgress();
        return
            sprintf('<div class="progress"><div style="width: %s;" class="progress-bar progress-bar-success">%s</div></div>',
                $progress . '%', $progress . '%'
            );
    }

    public function columnViews(MailingListEntityInterface $mailing): string
    {
        if (!$progressData = $mailing->getProgressData()) {
            return '';
        }

        $id = 'chart-' . $mailing->getId();
        $prog = $progressData->getViews() > 0 ? round($progressData->getViews() / $progressData->getSending() * 100) : 0;

        return '<a href="javascript:;" data-toggle="popover" data-id="' . $id . '" data-container="body" data-placement="top" data-trigger="focus" data-original-title="Просмотров" data-html="true" 
 class="add-popover pie-chart-malling" data-content="<div style=\'height:100px\' id=\'' . $id . '\' class=\'pie-title-center mar-rgt text-center\' data-percent=\'' . $prog . '\'><span class=\'pie-value text-thin\'></span></div>">' . Form::buildSpriteIcon('fa fa-pie-chart') . '</a> ' . $progressData->getViews() . ' / ' . $progressData->getSending();
    }

    public function columnTemplate(MailingListEntityInterface $mailing): string
    {
        return $mailing->getMailingTemplate()->getName();
    }

    public function columnSubscribes(MailingListEntityInterface $mailing): string
    {
        $emails = $this->mailingService->getSubscribeEmails($mailing);
        return $mailing->getMailingSubscriber()->getTitle() . ' (' . count($emails) . ')';
    }
}