<?php

class DXInstaller
{
    public function executePluginInitialization()
    {
        $script0 = file_get_contents(DANCE_X_PLUGIN_PATH . "installer/0_drop_dx_tables.sql");
        $result0 =  $this->executeMultipleQueries($script0);

        $script1 = file_get_contents(DANCE_X_PLUGIN_PATH . "installer/1_create_dx_and_jetengine_tables.sql");
        $result1 = $this->executeMultipleQueries($script1);

        $script2 = file_get_contents(DANCE_X_PLUGIN_PATH . "installer/2_delete_dx_jet_post_types.sql");
        $result2 = $this->executeSingleQuery($script2);

        $script3 = file_get_contents(DANCE_X_PLUGIN_PATH . "installer/3_create_dx_jet_post_types.sql");
        $result3 = $this->executeSingleQuery($script3);

        $result4 =  $this->updateAutoIncrementOfJetPostTypesIfNeeded();

        return $result0 && $result1 && $result2 && $result3 && $result4;
    }

    private function updateAutoIncrementOfJetPostTypesIfNeeded(): bool
    {
        $result = true;

        global $wpdb;
        $dbname = $wpdb->dbname;
        $prefix = $wpdb->prefix; // Get WP table prefix

        $jetPostTypesTable = "{$prefix}jet_post_types";

        $getCurrentAutoIncSql = <<<SQL
SELECT AUTO_INCREMENT
   FROM information_schema.TABLES
   WHERE TABLE_SCHEMA = '{$dbname}'
     AND TABLE_NAME = '{$jetPostTypesTable}'
SQL;

        $results = $wpdb->get_results($getCurrentAutoIncSql);
        $autoIncValue =  (int) $results[0]->AUTO_INCREMENT;

        if ($autoIncValue < 1000) {

            $result = $wpdb->query("ALTER TABLE {$jetPostTypesTable} AUTO_INCREMENT = 1000;");
        }

        return $result;
    }

    private function executeSingleQuery($script): bool
    {
        if (empty($script))
            return false;

        global $wpdb;
        $prefix = $wpdb->prefix; // Get WP table prefix
        $script = trim($script);

        $scriptWithCorrectTableName = str_replace('{WPTablePrefix}', $prefix, $script);

        // Execute the SQL query
        $result = $wpdb->query($scriptWithCorrectTableName);

        // Check for errors
        if ($result === false) {
            // Log or display the error if the query failed
            error_log('SQL Error (executeSingleQuery): ' . $wpdb->last_error);
            return false;
        }

        return true;
    }

    private function executeMultipleQueries($script): bool
    {
        $result = true;

        // Split the SQL script into individual queries based on semicolon delimiter
        $queries = explode(';', $script);

        foreach ($queries as $query) {

            if (!empty($query)) {
                $ret = $this->executeSingleQuery($query);

                //result is false if at least one of the queries returns false
                if ($ret === false) {
                    $result = false;
                }
            }
        }

        return $result;
    }
}
