<?php

defined( 'ABSPATH' ) or exit( 'Hey, what are you doing here? You silly human!' );

class Dusky_Update {

    private static $instance = null;

    /**
     * Upgrade versions
     *
     * @var array
     */
    private static $versions = [
        '1.0.2',
    ];

    private $installed_version = null;

    public function __construct() {
        $this->installed_version = get_option( 'dusky_version' );
    }

    /**
     * Check if the plugin needs version update
     *
     * @return boolean
     */
    public function needs_update() {

        if ( empty( $this->installed_version ) ) {
            return false;
        }

        //if previous version is lower
        if ( version_compare( $this->installed_version, DUSKY_VERSION, '<' ) ) {
            return true;
        }

        return false;
    }

    /**
     * Perform all the necessary upgrade routines
     *
     * @return void
     */
    public function perform_updates() {

        foreach ( self::$versions as $version ) {

            if ( version_compare( $this->installed_version, $version, '<' ) ) {
                $file = DUSKY_INC . "/updates/class-update-$version.php";

                if ( file_exists( $file ) ) {
                    include_once $file;
                }

                update_option( 'dusky_version', $version );
            }
        }

        delete_option( 'dusky_version' );
        update_option( 'dusky_version', DUSKY_VERSION );
        $this->installed_version = get_option( 'dusky_version' );
    }

    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

}
