<?php

declare(strict_types=1);

/*
 * This file is part of modal bundle for Contao.
 *
 * (c) Benjamin Roth
 *
 * @license LGPL-3.0-or-later
 */

namespace vonRotenberg\ModalBundle\EventListener\DataContainer;

use Contao\Backend;
use Contao\BackendUser;
use Contao\CoreBundle\Exception\AccessDeniedException;
use Contao\CoreBundle\ServiceAnnotation\Callback;
use Contao\DataContainer;
use Contao\Image;
use Contao\Input;
use Contao\StringUtil;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use vonRotenberg\ModalBundle\Security\ModalPermissions;

class ModalDataContainerListener
{
    private Security $security;
    private SessionInterface $session;

    public function __construct(Security $security, SessionInterface $session)
    {
        $this->security = $security;
        $this->session = $session;
    }

    /**
     * @Callback(table="tl_vr_modal", target="config.onload")
     */
    public function checkPermission(DataContainer $dc = null): void
    {
        $user = $this->security->getUser();
        $userId = $user instanceof BackendUser ? (int)$user->id : 0;

        if ($user->isAdmin)
        {
            return;
        }

        // Check permissions to add modals
        if (!$this->security->isGranted(ModalPermissions::USER_CAN_CREATE_MODALS))
        {
            $GLOBALS['TL_DCA']['tl_vr_modal']['config']['closed'] = true;
            $GLOBALS['TL_DCA']['tl_vr_modal']['config']['notCreatable'] = true;
            $GLOBALS['TL_DCA']['tl_vr_modal']['config']['notCopyable'] = true;
        }

        // Check permissions to delete modals
        if (!$this->security->isGranted(ModalPermissions::USER_CAN_DELETE_MODALS))
        {
            $GLOBALS['TL_DCA']['tl_vr_modal']['config']['notDeletable'] = true;
        }

        // Check current action
        switch (Input::get('act'))
        {
            case 'overrideAll':
            case 'editAll':
            case 'show':
            case 'edit':
            case 'select':
                // Allow
                break;

            case 'copy':
            case 'create':
                if (!$this->security->isGranted(ModalPermissions::USER_CAN_CREATE_MODALS))
                {
                    throw new AccessDeniedException('Not enough permissions to ' . Input::get('act') . ' modals.');
                }
                break;

            case 'delete':
                if (!$this->security->isGranted(ModalPermissions::USER_CAN_DELETE_MODALS))
                {
                    throw new AccessDeniedException('Not enough permissions to ' . Input::get('act') . ' modal ID ' . Input::get('id') . '.');
                }
                break;

            case 'deleteAll':
            case 'copyAll':
                $session = $this->session->all();

                if (Input::get('act') == 'deleteAll' && !$this->security->isGranted(ModalPermissions::USER_CAN_DELETE_MODALS))
                {
                    $session['CURRENT']['IDS'] = array();
                } else
                {
                    if (Input::get('act') == 'copyAll' && !$this->security->isGranted(ModalPermissions::USER_CAN_CREATE_MODALS))
                    {
                        $session['CURRENT']['IDS'] = array();
                    }
                }
                $this->session->replace($session);
                break;

            default:
                if (Input::get('act'))
                {
                    throw new AccessDeniedException('Not enough permissions to ' . Input::get('act') . ' modals.');
                }
                break;
        }
    }

    /**
     * @Callback(table="tl_vr_modal", target="list.operations.copy.button")
     */
    public function copyModal($row, $href, $label, $title, $icon, $attributes): string
    {
        return $this->security->isGranted(ModalPermissions::USER_CAN_CREATE_MODALS) ? '<a href="' . Backend::addToUrl($href . '&amp;id=' . $row['id']) . '" title="' . StringUtil::specialchars($title) . '"' . $attributes . '>' . Image::getHtml($icon, $label) . '</a> ' : Image::getHtml(preg_replace('/\.svg$/i', '_.svg', $icon)) . ' ';
    }

    /**
     * @Callback(table="tl_vr_modal", target="list.operations.delete.button")
     */
    public function deleteModal($row, $href, $label, $title, $icon, $attributes): string
    {
        return $this->security->isGranted(ModalPermissions::USER_CAN_DELETE_MODALS) ? '<a href="' . Backend::addToUrl($href . '&amp;id=' . $row['id']) . '" title="' . StringUtil::specialchars($title) . '"' . $attributes . '>' . Image::getHtml($icon, $label) . '</a> ' : Image::getHtml(preg_replace('/\.svg$/i', '_.svg', $icon)) . ' ';
    }
}