<?php

namespace Linksy\SearchAndReplace\Plugli\Standard\Helpers;

class Migrations
{
    private $dirpath;
    private $current_version;
    /**
     * 
     * @param [type] $dirpath The directory where the versions folder is located
     */
    public function __construct($dirpath, $current_version = 0)
    {
        $this->dirpath = $dirpath;
        $this->current_version = $current_version;
    }
    /**
     * Returns an array of migrations available in the versions folder.
     * 
     * @see version_example.php in the migrations directory at inc/
     * @return array An array of migrations
     */
    public function get()
    {
        // get migration files from versions directory
        $migrations = [];
        $migration_files = glob($this->dirpath . '/versions/version_*.php');
        foreach ($migration_files as $migration_file) {
            $version_number = preg_replace('/[^0-9]/', '', basename($migration_file));
            // get the version file
            if ($version_number > $this->current_version) {
                $migrations[] = ['version' => $version_number, 'schema' => $migration_file];
            }
        }
        return $migrations;
    }
    public function get_schema($migration_file)
    {
        global $wpdb;
        $collate = $wpdb->get_charset_collate();
        $version = require_once $migration_file;
        return $version($collate);
    }
    /** */
    public function getCurrentVersion()
    {
        return $this->current_version;
    }
    public function create()
    {
        $migrations = $this->get();
        if (count($migrations) < 1) {
            return \false;
        }
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        foreach ($migrations as $migration) {
            dbDelta($this->get_schema($migration['schema']));
            $this->current_version = $migration['version'];
        }
        return \true;
    }
}
