<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.

/**
 * Plugin upgrade steps are defined here.
 *
 * @package     local_assign_ai
 * @category    upgrade
 * @copyright   2025 Datacurso
 * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */


/**
 * Execute local_assign_ai upgrade from the given old version.
 *
 * @param int $oldversion
 * @return bool
 */
function xmldb_local_assign_ai_upgrade($oldversion) {
    global $DB;

    $dbman = $DB->get_manager();

    // For further information please read {@link https://docs.moodle.org/dev/Upgrade_API}.
    //
    // You will also have to create the db/install.xml file by using the XMLDB Editor.
    // Documentation for the XMLDB Editor can be found at {@link https://docs.moodle.org/dev/XMLDB_editor}.

    if ($oldversion < 2025092506) {
        // Define table local_assign_ai_pending to be created.
        $table = new xmldb_table('local_assign_ai_pending');

        // Adding fields to table local_assign_ai_pending.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('assignmentid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('message', XMLDB_TYPE_TEXT, null, null, null, null, null);
        $table->add_field('status', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'pending');
        $table->add_field('approval_token', XMLDB_TYPE_CHAR, '64', null, XMLDB_NOTNULL, null, null);

        // Adding keys to table local_assign_ai_pending.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);

        // Conditionally launch create table for local_assign_ai_pending.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025092506, 'local', 'assign_ai');
    }

    if ($oldversion < 2025092600) {
        $table = new xmldb_table('local_assign_ai_pending');

        // Agregar campo grade si no existe.
        $field = new xmldb_field('grade', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'message');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Agregar campo rubric_response si no existe.
        $field = new xmldb_field('rubric_response', XMLDB_TYPE_TEXT, null, null, null, null, null, 'grade');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        upgrade_plugin_savepoint(true, 2025092600, 'local', 'assign_ai');
    }

    if ($oldversion < 2025111305) {
        // Define field usermodified to be added to local_assign_ai_pending.
        $table = new xmldb_table('local_assign_ai_pending');
        $field = new xmldb_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'approval_token');

        // Conditionally launch add field usermodified.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Define field timecreated to be added to local_assign_ai_pending.
        $table = new xmldb_table('local_assign_ai_pending');
        $field = new xmldb_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, null, null, '0', 'usermodified');

        // Conditionally launch add field timecreated.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Define field timemodified to be added to local_assign_ai_pending.
        $table = new xmldb_table('local_assign_ai_pending');
        $field = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, null, null, '0', 'timecreated');

        // Conditionally launch add field timemodified.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        $now = time();

        // Ensure timemodified always has a value.
        $DB->execute(
            "UPDATE {local_assign_ai_pending}
                SET timemodified = :now
              WHERE timemodified IS NULL OR timemodified = 0",
            ['now' => $now]
        );

        // Use timemodified when timecreated was empty.
        $DB->execute(
            "UPDATE {local_assign_ai_pending}
                SET timecreated = timemodified
              WHERE (timecreated IS NULL OR timecreated = 0)
                AND (timemodified IS NOT NULL AND timemodified > 0)"
        );

        // Fallback value for timecreated.
        $DB->execute(
            "UPDATE {local_assign_ai_pending}
                SET timecreated = :now
              WHERE timecreated IS NULL OR timecreated = 0",
            ['now' => $now]
        );

        // Populate usermodified with the originating userid when missing.
        $DB->execute(
            "UPDATE {local_assign_ai_pending}
                SET usermodified = userid
              WHERE (usermodified IS NULL OR usermodified = 0)
                AND userid IS NOT NULL"
        );

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025111305, 'local', 'assign_ai');
    }

    if ($oldversion < 2025111306) {
        $table = new xmldb_table('local_assign_ai_config');

        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('assignmentid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('autograde', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');

        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
        $table->add_key('assignmentid_uniq', XMLDB_KEY_UNIQUE, ['assignmentid']);
        $table->add_key('config_user_fk', XMLDB_KEY_FOREIGN, ['usermodified'], 'user', ['id']);

        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }

        upgrade_plugin_savepoint(true, 2025111306, 'local', 'assign_ai');
    }

    if ($oldversion < 2025111404) {
        // Define field autograde to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('autograde', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'assignmentid');

        // Conditionally launch add field autograde.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Define field graderid to be added to local_assign_ai_config.
        $field = new xmldb_field('graderid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'autograde');

        // Conditionally launch add field graderid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Define key config_grader_fk (foreign) to be added to local_assign_ai_config.
        $key = new xmldb_key('config_grader_fk', XMLDB_KEY_FOREIGN, ['graderid'], 'user', ['id']);

        // Launch add key config_grader_fk.
        $dbman->add_key($table, $key);

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025111404, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120501) {
        // Define table local_assign_ai_queue to be created.
        $table = new xmldb_table('local_assign_ai_queue');

        // Adding fields to table local_assign_ai_queue.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('tenantid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('payload', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timetoprocess', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('processed', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');

        // Adding keys to table local_assign_ai_queue.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);

        // Conditionally launch create table for local_assign_ai_queue.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025120501, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120502) {
        // Define field tenantid to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('tenantid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'assignmentid');

        // Conditionally launch add field tenantid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Normalize any legacy null values.
        $DB->execute('UPDATE {local_assign_ai_config} SET tenantid = 0 WHERE tenantid IS NULL');

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025120502, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120503) {
        $table = new xmldb_table('local_assign_ai_config');

        $oldkey = new xmldb_key(
            'assignmentid_uniq',
            XMLDB_KEY_UNIQUE,
            ['assignmentid']
        );

        if ($dbman->find_key_name($table, $oldkey) !== false) {
            $dbman->drop_key($table, $oldkey);
        }

        upgrade_plugin_savepoint(true, 2025120503, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120504) {
        $table = new xmldb_table('local_assign_ai_config');

        $newkey = new xmldb_key(
            'assignmentid_uniq',
            XMLDB_KEY_UNIQUE,
            ['assignmentid', 'tenantid']
        );

        if ($dbman->find_key_name($table, $newkey) === false) {
            $dbman->add_key($table, $newkey);
        }

        upgrade_plugin_savepoint(true, 2025120504, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120505) {
        // Define field usedelay to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('usedelay', XMLDB_TYPE_INTEGER, '1', null, null, null, '0', 'usermodified');

        // Conditionally launch add field usedelay.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025120505, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120506) {
        // Define field delayminutes to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('delayminutes', XMLDB_TYPE_INTEGER, '6', null, null, null, '0', 'usedelay');

        // Conditionally launch add field delayminutes.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Assign_ai savepoint reached.
        upgrade_plugin_savepoint(true, 2025120506, 'local', 'assign_ai');
    }

    if ($oldversion < 2025120803) {
        $table = new xmldb_table('local_assign_ai_pending');
        $field = new xmldb_field('assessment_guide_response', XMLDB_TYPE_TEXT, null, null, null, null, null, 'rubric_response');

        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        upgrade_plugin_savepoint(true, 2025120803, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032603) {
        // Define field prompt to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('prompt', XMLDB_TYPE_TEXT, null, null, null, null, null, 'delayminutes');

        // Conditionally launch add field prompt.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        upgrade_plugin_savepoint(true, 2026032603, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032604) {
        // Force the default auto-approval setting to disabled by default.
        set_config('defaultautograde', 0, 'local_assign_ai');

        upgrade_plugin_savepoint(true, 2026032604, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032605) {
        // Define field enableai to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('enableai', XMLDB_TYPE_INTEGER, '1', null, null, null, null, 'tenantid');

        // Conditionally launch add field enableai.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Ensure default value for the new global setting.
        set_config('defaultenableai', 1, 'local_assign_ai');

        upgrade_plugin_savepoint(true, 2026032605, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032606) {
        // Define field lang to be added to local_assign_ai_config.
        $table = new xmldb_table('local_assign_ai_config');
        $field = new xmldb_field('lang', XMLDB_TYPE_CHAR, '20', null, null, null, null, 'prompt');

        // Conditionally launch add field lang.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        upgrade_plugin_savepoint(true, 2026032606, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032607) {
        // Define field tenantid to be added to local_assign_ai_queue.
        $table = new xmldb_table('local_assign_ai_queue');
        $field = new xmldb_field('tenantid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');

        // Conditionally launch add field tenantid.
        if ($dbman->table_exists($table) && !$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // Normalize any legacy null values.
        if ($dbman->table_exists($table)) {
            $DB->execute('UPDATE {local_assign_ai_queue} SET tenantid = 0 WHERE tenantid IS NULL');
        }

        upgrade_plugin_savepoint(true, 2026032607, 'local', 'assign_ai');
    }

    if ($oldversion < 2026032608) {
        // Define table local_assign_ai_tenant_cfg to be created.
        $table = new xmldb_table('local_assign_ai_tenant_cfg');

        // Adding fields to table local_assign_ai_tenant_cfg.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('plugin', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('tenantid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('name', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, null, null, null, null, null);

        // Adding keys to table local_assign_ai_tenant_cfg.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
        $table->add_key('plugin_tenant_name_uniq', XMLDB_KEY_UNIQUE, ['plugin', 'tenantid', 'name']);

        // Conditionally launch create table for local_assign_ai_tenant_cfg.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }

        upgrade_plugin_savepoint(true, 2026032608, 'local', 'assign_ai');
    }

    return true;
}
