<?php

declare(strict_types=1);

namespace BrandCrockAquaTheme;

use Shopware\Core\Framework\Plugin;
use Doctrine\DBAL\Connection;
use Shopware\Storefront\Framework\ThemeInterface;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;


class BrandCrockAquaTheme extends Plugin implements ThemeInterface
{
    public function getThemeConfigPath(): string
    {
        return 'theme.json';
    }

    public function install(InstallContext $context): void
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');
        $connection = $this->container->get(Connection::class);

        $this->productPdfCustomField($customFieldSetRepository, $connection, $context);
        $this->productCustomTabField($customFieldSetRepository, $connection, $context);
        $this->categoryBannerCustomField($customFieldSetRepository, $connection, $context);
        $this->categoryWidgetImageCustomField($customFieldSetRepository, $connection, $context);
        $this->createCategoryMediaFolder($context->getContext());
        $this->addShortDescriptionCustomField($context);

        parent::install($context);
    }

    public function uninstall(UninstallContext $context): void
    {
        if (!$context->keepUserData()) {
            $this->removeCustomFieldSets($context->getContext());
            $this->deleteDefaultMediaFolder($context->getContext());
        }

        parent::uninstall($context);
    }

    public function update(UpdateContext $context): void
    {
        $this->addShortDescriptionCustomField($context);
    }

    public function createCategoryMediaFolder(Context $context): void
    {

        $this->checkForThumbnailSizes($context);

        /** @var EntityRepositoryInterface $mediaFolderRepository */
        $mediaFolderRepository = $this->container->get('media_default_folder.repository');
        $connection = $this->container->get(Connection::class);

        $bcMediaFolderQuery = $connection->executeQuery("select count(*) as bc_default_folder FROM media_default_folder WHERE entity =  'AquaThemeWidgetMedia'");
        $bcMediaFolderResults = $bcMediaFolderQuery->fetchAssociative();

        if ($bcMediaFolderResults['bc_default_folder'] < 1) {
            $mediaFolderRepository->create([
                [
                    'entity' => 'AquaThemeWidgetMedia',
                    'associationFields' => ['media'],
                    'folder' => [
                        'name' => 'AquaThemeWidgetMedia',
                        'useParentConfiguration' => false,
                        'configuration' => [
                            'createThumbnails' => true,
                            'mediaThumbnailSizes' => [
                                [
                                    'width' => 650,
                                    'height' => 330,
                                ],
                            ],
                        ],
                    ],
                ],
            ], $context);
        }
    }

    private function checkForThumbnailSizes(Context $context): void
    {
        $criteria = new Criteria();
        $criteria->addFilter(
            new MultiFilter(
                MultiFilter::CONNECTION_AND,
                [
                    new EqualsFilter('width', 650),
                    new EqualsFilter('height', 330),
                ]
            )
        );

        /** @var EntityRepositoryInterface $thumbnailSizeRepository */
        $thumbnailSizeRepository = $this->container->get('media_thumbnail_size.repository');

        $thumbnailIds = $thumbnailSizeRepository->searchIds($criteria, $context)->getIds();

        if (!empty($thumbnailIds)) {
            $ids = array_map(static function ($id) {
                return ['id' => $id];
            }, $thumbnailIds);
            $thumbnailSizeRepository->delete($ids, $context);
        }
    }

    private function deleteDefaultMediaFolder(Context $context): void
    {
        $criteria = new Criteria();
        $criteria->addFilter(
            new EqualsAnyFilter('entity', [
                'AquaThemeWidgetMedia',
            ])
        );

        /** @var EntityRepositoryInterface $mediaDefaultFolderRepository */
        $mediaDefaultFolderRepository = $this->container->get('media_default_folder.repository');

        $mediaDefaultFolderIds = $mediaDefaultFolderRepository->searchIds($criteria, $context)->getIds();

        if (!empty($mediaDefaultFolderIds)) {
            $ids = array_map(static function ($id) {
                return ['id' => $id];
            }, $mediaDefaultFolderIds);
            $mediaDefaultFolderRepository->delete($ids, $context);
        }

        $mfCriteria = new Criteria();
        $mfCriteria->addFilter(
            new EqualsAnyFilter('name', [
                'AquaThemeWidgetMedia',
            ])
        );

        /** @var EntityRepositoryInterface $mediaFolderRepository */
        $mediaFolderRepository = $this->container->get('media_folder.repository');

        $mediaFolderIds = $mediaFolderRepository->searchIds($mfCriteria, $context)->getIds();

        if (!empty($mediaFolderIds)) {
            $ids = array_map(static function ($id) {
                return ['id' => $id];
            }, $mediaFolderIds);
            $mediaFolderRepository->delete($ids, $context);
        }
    }

    public function addShortDescriptionCustomField($context)
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');

        $connection = $this->container->get(Connection::class);
        $query = $connection->executeQuery("select count(*) as bcshortDescription FROM custom_field_set WHERE name =  'bc_aqua_short_desc'");
        $result = $query->fetchAssociative();

        if ($result['bcshortDescription'] < 1) {
            $customFieldSetRepository->create(
                [
                    [
                        'name' => 'bc_aqua_short_desc',
                        'config' => [
                            'label' => [
                                'de-DE' => 'Aqua Produktfelder',
                                'en-GB' => 'Aqua Product Fields',
                            ],
                        ],
                        'customFields' => [
                            [
                                'name' => 'bc_aqua_short_description',
                                'type' => CustomFieldTypes::TEXT,
                                'config' => [
                                    'label' => [
                                        'de-DE' => 'Kurzbeschreibung',
                                        'en-GB' => 'Short Description',
                                    ],
                                    'componentName' => 'sw-text-editor',
                                    'customFieldType' => 'textEditor',
                                    'customFieldPosition' => 1,
                                    'type' => 'text'
                                ],
                            ]
                        ],
                        'relations' => [
                            [
                                'entityName' => 'product',
                            ],
                        ],
                    ]
                ],
                $context->getContext()
            );
        }
    }

    public function productPdfCustomField($repository, $connection, $context)
    {
        $pdfTabExists = (int) $connection->fetchOne(
            'SELECT COUNT(*) FROM custom_field_set WHERE name = :name',
            ['name' => 'custom_bc_pdf']
        );

        if ($pdfTabExists >= 1) return;

        $repository->create([
            [
                'name' => 'custom_bc_pdf',
                'config' => [
                    'label' => [
                        'de-DE' => 'Aqua PDF-Tab',
                        'en-GB' => 'Aqua PDF Tab'
                    ]
                ],
                /** PDF Embed field */
                'customFields' => [
                    [
                        'name' => 'custom_bc_pdf_tab1',
                        'type' => CustomFieldTypes::MEDIA,
                        'config' => [
                            'label' => [
                                'de-DE' => 'PDF hochladen 1',
                                'en-GB' => 'Upload PDF 1'
                            ],
                            'placeholder' => [
                                'de-DE' => 'PDF hochladen 1',
                                'en-GB' => 'Upload PDF 1'
                            ],
                            'componentName' => 'sw-media-field',
                            'customFieldType' => 'media',
                            'customFieldPosition' => 1,
                            'type' => 'media',
                            'defaultFolder' => 'AquaThemeWidgetMedia'

                        ]
                    ],
                    [
                        'name' => 'custom_bc_pdf_tab2',
                        'type' => CustomFieldTypes::MEDIA,
                        'config' => [
                            'label' => [
                                'de-DE' => 'PDF hochladen 2',
                                'en-GB' => 'Upload PDF 2'
                            ],
                            'placeholder' => [
                                'de-DE' => 'PDF hochladen 2',
                                'en-GB' => 'Upload PDF 2'
                            ],
                            'componentName' => 'sw-media-field',
                            'customFieldType' => 'media',
                            'customFieldPosition' => 1,
                            'type' => 'media',
                            'defaultFolder' => 'AquaThemeWidgetMedia'

                        ]
                    ],
                    [
                        'name' => 'custom_bc_pdf_tab3',
                        'type' => CustomFieldTypes::MEDIA,
                        'config' => [
                            'label' => [
                                'de-DE' => 'PDF hochladen 3',
                                'en-GB' => 'Upload PDF 3'
                            ],
                            'placeholder' => [
                                'de-DE' => 'PDF hochladen 3',
                                'en-GB' => 'Upload PDF 3'
                            ],
                            'componentName' => 'sw-media-field',
                            'customFieldType' => 'media',
                            'customFieldPosition' => 1,
                            'type' => 'media',
                            'defaultFolder' => 'AquaThemeWidgetMedia'

                        ]
                    ],

                ],
                'relations' => [
                    ['entityName' => 'product']
                ],

            ],
        ], $context->getContext());
    }

    public function productCustomTabField($repository, $connection, $context)
    {
        $customTabExists = (int) $connection->fetchOne(
            'SELECT COUNT(*) FROM custom_field_set WHERE name = :name',
            ['name' => 'custom_bc_product_title']
        );

        if ($customTabExists >= 1) return;

        $repository->create([[
            'name' => 'custom_bc_product_title',
            'config' => [
                'label' => [
                    'de-DE' => 'Aqua Eigene Registerkarte',
                    'en-GB' => 'Aqua Custom-Tab'
                ]
            ],
            'customFields' => [
                [
                    'name' => 'custom_bc_product_title_text',
                    'type' => CustomFieldTypes::TEXT,
                    'config' => [
                        'label' => [
                            'de-DE' => 'Titel',
                            'en-GB' => 'Title'
                        ],
                        'helpText' => [
                            'de-DE' => 'Titel',
                            'en-GB' => 'Title'
                        ],
                        'componentName' => 'sw-field',
                        'customFieldType' => 'text',
                        'customFieldPosition' => 1,
                        'type' => 'text'
                    ]
                ],
                //Custom Field content
                [
                    'name' => 'custom_bc_product_title_desc',
                    'type' => CustomFieldTypes::HTML,
                    'config' => [
                        'label' => [
                            'de-DE' => 'Beschreibung',
                            'en-GB' => 'Description'
                        ],
                        'helpText' => [
                            'de-DE' => 'Beschreibung',
                            'en-GB' => 'Description'
                        ],
                        'componentName' => 'sw-text-editor',
                        'customFieldType' => 'textEditor',
                        'customFieldPosition' => 2,
                        'type' => 'textEditor'
                    ]
                ]
            ],
            'relations' => [
                ['entityName' => 'product']
            ]
        ]], $context->getContext());
    }

    public function categoryBannerCustomField($repository, $connection, $context)
    {
        $customBannerExists = (int) $connection->fetchOne(
            'SELECT COUNT(*) FROM custom_field_set WHERE name = :name',
            ['name' => 'bc_category_banner']
        );

        if ($customBannerExists >= 1) return;

        $repository->create([[
            'name' => 'bc_category_banner',
            'config' => [
                'label' => [
                    'de-DE' => 'Kategorie Banner',
                    'en-GB' => 'Category Banner',
                ],
            ],
            'customFields' => [
                [
                    'name' => 'bc_category_banner_img',
                    'type' => CustomFieldTypes::MEDIA,
                    'config' => [
                        'label' => [
                            'de-DE' => 'Hintergrundbild',
                            'en-GB' => 'Background Image',
                        ],
                        'componentName' => 'sw-media-field',
                        'customFieldType' => 'media',
                        'customFieldPosition' => '1',
                        'type' => 'media',
                        'defaultFolder' => 'AquaThemeWidgetMedia'
                    ],
                ]
            ],
            'relations' => [['entityName' => 'category']],
        ]], $context->getContext());
    }

    public function categoryWidgetImageCustomField($repository, $connection, $context)
    {
        $customWidgetExists = (int) $connection->fetchOne(
            'SELECT COUNT(*) FROM custom_field_set WHERE name = :name',
            ['name' => 'bc_aqua_category_widget_images']
        );

        if ($customWidgetExists >= 1) return;

        $repository->create([[
            'name' => 'bc_aqua_category_widget_images',
            'config' => [
                'label' => [
                    'de-DE' => 'Aqua Kategorie Boxen Bild',
                    'en-GB' => 'Aqua Category Boxes Image'
                ]
            ],
            'customFields' => [
                [
                    'name' => 'bc_aqua_category_box_image',
                    'type' => CustomFieldTypes::MEDIA,
                    'config' => [
                        'label' => [
                            'de-DE' => 'Bild',
                            'en-GB' => 'Image'
                        ],
                        'helpText' => [
                            'de-DE' => 'Dieses Bild wird im Widget der Obere Kategorie Box angezeigt',
                            'en-GB' => 'This image will be shown in Top Category Box widget'
                        ],
                        'componentName' => 'sw-media-field',
                        'customFieldType' => 'media',
                        'customFieldPosition' => '1',
                        'type' => 'media',
                        'defaultFolder' => 'AquaThemeWidgetMedia'
                    ]
                ]
            ],
            'relations' => [
                ['entityName' => 'category']
            ]
        ]], $context->getContext());
    }

    public function removeCustomFieldSets($context): void
    {
        $repository = $this->container->get('custom_field_set.repository');

        $fieldSetNames = [
            'custom_bc_product_title',
            'bc_aqua_category_widget_images',
            'bc_category_banner',
            'custom_bc_pdf',
            'bc_aqua_short_desc'
        ];

        $criteria = new Criteria();
        $criteria->addFilter(new EqualsAnyFilter('name', $fieldSetNames));
        $idsResult = $repository->searchIds($criteria, $context);

        if ($idsResult->getTotal() === 0) return;

        $repository->delete(
            array_map(static fn (string $id) => ['id' => $id], $idsResult->getIds()),
            $context
        );
    }
}
