<?php

declare(strict_types=1);

namespace vonRotenberg\MemberfilesBundle\Migration;

use Contao\CoreBundle\Migration\AbstractMigration;
use Contao\CoreBundle\Migration\MigrationResult;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;

class MemberfilesConfigMigration extends AbstractMigration
{
    private Connection $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    public function shouldRun(): bool
    {
        $schemaManager = $this->connection->createSchemaManager();

        // Prüfen ob die Quelltabelle existiert
        if (!$schemaManager->tablesExist(['tl_page'])) {
            return false;
        }

        // Prüfen ob die notwendige Spalte in tl_page existiert
        $columns = $schemaManager->listTableColumns('tl_page');
        if (!isset($columns['securedownloadsenabled'])) {
            return false;
        }

        // Prüfen ob es Einträge gibt, die migriert werden müssen
        $result = $this->connection->fetchOne(
            "SELECT COUNT(*) FROM tl_page WHERE secureDownloadsEnabled='1'"
        );

        return $result > 0;
    }

    public function run(): MigrationResult
    {
        $schemaManager = $this->connection->createSchemaManager();

        // Erstelle die Zieltabelle, falls sie nicht existiert
        if (!$schemaManager->tablesExist(['tl_memberfiles_config'])) {
            $this->createMemberfilesConfigTable();
        }

        $pages = $this->connection->fetchAllAssociative(
            "SELECT id, title, secureDownloadsSRC, secureDownloadsTarget, " .
            "secureDownloadsRegExp, secureDownloadsFields, sd_nc_enable, sd_nc_notification " .
            "FROM tl_page WHERE secureDownloadsEnabled='1'"
        );

        foreach ($pages as $page) {
            $this->connection->insert('tl_memberfiles_config', [
                'tstamp' => time(),
                'title' => $page['title'] . ' (migriert von Seite ID ' . $page['id'] . ')',
                'source' => $page['secureDownloadsSRC'],
                'target' => $page['secureDownloadsTarget'],
                '`regexp`' => $page['secureDownloadsRegExp'],
                'fields' => $page['secureDownloadsFields'],
                'hasNotification' => $page['sd_nc_enable'],
                'notification' => $page['sd_nc_notification'],
                'enabled' => '1'
            ]);

            $this->connection->update('tl_page', ['secureDownloadsEnabled' => ''], ['id' => $page['id']]);
        }



        return new MigrationResult(
            true,
            sprintf('Erfolgreich %d Secure Downloads Konfigurationen von tl_page nach tl_memberfiles_config migriert.', count($pages))
        );
    }

    private function createMemberfilesConfigTable(): void
    {
        $schema = new Schema();
        $table = $schema->createTable('tl_memberfiles_config');

        // Pflichtfelder
        $table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
        $table->addColumn('tstamp', 'integer', ['unsigned' => true, 'default' => 0]);
        $table->addColumn('title', 'string', ['length' => 255, 'default' => '']);
        $table->addColumn('source', 'binary', ['length' => 16, 'fixed' => true, 'notnull' => false]);
        $table->addColumn('target', 'binary', ['length' => 16, 'fixed' => true, 'notnull' => false]);
        $table->addColumn('regexp', 'string', ['length' => 64, 'notnull' => true, 'default' => '']);
        $table->addColumn('fields', 'blob', ['notnull' => false]);
        $table->addColumn('hasNotification', 'string', ['length' => 1, 'fixed' => true, 'default' => '']);
        $table->addColumn('notification', 'integer', ['unsigned' => true, 'default' => 0]);
        $table->addColumn('enabled', 'string', ['length' => 1, 'fixed' => true, 'default' => '']);

        // Primary Key
        $table->setPrimaryKey(['id']);

        // Schema anwenden
        $queries = $schema->toSql($this->connection->getDatabasePlatform());
        foreach ($queries as $query) {
            $this->connection->executeStatement($query);
        }
    }
}