<?php

namespace Sibs\DB\Seeds\Version_2_1_0;

use Configuration;
use Db;
use Exception;
use Sibs\Models\SibsModels;
use Sibs\SibsLogger;

trait SibsSeedVersion_2_1_0
{
    /**
     * Seed.
     *
     * @param SibsModels $model
     * @return bool
     */
    public static function seed(SibsModels $model): bool
    {
        $seedName   = self::getStaticSeedName();
        $configName = self::getStaticConfigName();

        if (Configuration::get($configName) == '1') {
            return true;
        }

        try {
            SibsLogger::info('Seeding ' . $seedName . ' seed');

            $tableName   = $model::$definition['table'];
            $tableFields = array_keys($model::$definition['fields']); // Get the field names

            // Verify that the new table exists before seeding
            $newTableExists = Db::getInstance()->executeS("SHOW TABLES LIKE '" . _DB_PREFIX_ . "$tableName'");

            if (! $newTableExists) {
                throw new Exception('New Table ' . _DB_PREFIX_ . "$tableName not found");
            }

            // Check if data is already seeded
            $existingData = Db::getInstance()->getValue('SELECT COUNT(*) FROM `' . _DB_PREFIX_ . "$tableName`");

            if ($existingData == 0) {
                // Get data from the old table
                $oldTableExists = Db::getInstance()->executeS("SHOW TABLES LIKE '$tableName'");

                if (! $oldTableExists) {
                    SibsLogger::warning("Old Table $tableName not found, seed not needed");

                    return true;
                }

                // Get data from the old table
                $oldData = Db::getInstance()->executeS("SELECT * FROM `$tableName`");

                // Seed data into new table
                foreach ($oldData as $row) {
                    $tableFieldsFilled = array_combine($tableFields, array_map(function ($field) use ($row) {
                        return pSQL($row[$field] ?? null);
                    }, $tableFields));

                    Db::getInstance()->insert($tableName, $tableFieldsFilled);
                }
            }

            SibsLogger::info('Seeded ' . $seedName . ' seed');

            Configuration::updateValue($configName, '1');

            return true;
        } catch (Exception $e) {
            SibsLogger::error('Error on Seeding ' . $seedName . ' seed: ' . $e->getMessage());

            Configuration::updateValue($configName, '0');

            return false;
        }
    }
}
