<?php

namespace DZ\ImageShield;

use XF\AddOn\AbstractSetup;
use XF\AddOn\StepRunnerInstallTrait;
use XF\AddOn\StepRunnerUninstallTrait;
use XF\AddOn\StepRunnerUpgradeTrait;
use XF\Db\Schema\Alter;
use XF\Db\Schema\Create;
use XF\Util\File;

class Installer extends AbstractSetup
{
    use StepRunnerInstallTrait;
    use StepRunnerUpgradeTrait;
    use StepRunnerUninstallTrait;

    public function installStep1(): void
    {
        $sm = $this->schemaManager();

        if (!$sm->tableExists('xf_dz_imageshield_data')) {
            $sm->createTable('xf_dz_imageshield_data', function (Create $table) {
                $table->addColumn('data_id', 'int')->unsigned();
                $table->addColumn('watermark_date', 'int')->setDefault(0);
                $table->addPrimaryKey('data_id');
            });
        }

        if (!$sm->columnExists('xf_user_option', 'dz_is_enabled')) {
            $sm->alterTable('xf_user_option', function (Alter $table) {
                $table->addColumn('dz_is_enabled', 'tinyint')->unsigned()->setDefault(0);
            });
        }

        $registry = $this->app()->registry()->get(Shield::KEY_REGISTRY_USER_SIGNATURES);
        if (!is_array($registry)) {
            $this->app()->registry()->set(Shield::KEY_REGISTRY_USER_SIGNATURES, []);
        }
    }

    public function uninstallStep1(): void
    {
        $sm = $this->schemaManager();

        if ($sm->tableExists('xf_dz_imageshield_data')) {
            $sm->dropTable('xf_dz_imageshield_data');
        }

        if ($sm->columnExists('xf_user_option', 'dz_is_enabled')) {
            $sm->alterTable('xf_user_option', function (Alter $table) {
                $table->dropColumns(['dz_is_enabled']);
            });
        }

        File::deleteAbstractedDirectory('internal-data://dz_imageshield');
        $this->app()->registry()->delete(Shield::KEY_REGISTRY_USER_SIGNATURES);
    }
}
