<?php

/**
 * The core plugin class.
 *
 * @version    1.1.3
 * @package    SEOFlow
 * @subpackage SEOFlow/includes
 * @author     Trinco Ingels <info@trincoingels.nl>
 */
class Linknetwerk {

    protected $loader;
    static $plugin_name = 'LupsOnlineLinkNetwerk';
    static $version = '2.0.6';
    static $dbTableNameInstellingen;

    /**
     * Define the core functionality of the plugin.
     */
    public function __construct() {

        self::$dbTableNameInstellingen = strtolower(self::$plugin_name) . "_instellingen";

        $this->load_dependencies();
        $this->define_admin_hooks();
        $this->define_api_endpoints();
        $this->plugin_update();
    }

    /**
     * Load the required dependencies for this plugin.
     *
     * @access   private
     */
    private function load_dependencies() {

        /**
         * The class responsible for orchestrating the actions and filters of the
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-linknetwerk-loader.php';

        /**
         * The class responsible for the communication with linknetwerk
         * of the plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-linknetwerk-api.php';

        /**
         * The class responsible for defining all actions that occur in the admin area.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-linknetwerk-admin.php';

        /**
         * The class responsible for defining all actions that occur in the admin area.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-linknetwerk-adminnotice.php';

        $this->loader = new LinkNetwerk_Loader();
    }

    /**
     * Register all of the hooks related to the admin area functionality
     * of the plugin.
     *
     * @access   private
     */
    private function define_admin_hooks() {

        $plugin_admin = new LinkNetwerk_Admin($this->get_plugin_name(), $this->get_version());

        $this->loader->add_action('admin_menu', $plugin_admin, 'action_admin_menu');
        $this->loader->add_action('admin_notices', new LinkNetwerk_AdminNotice(), 'displayAdminNotice');

        add_shortcode('lupsonline_linknetwerk', array($plugin_admin, 'getLinks'));
		add_shortcode('seoflow_links', array($plugin_admin, 'getLinks'));

        $this->loader->add_action('plugins_loaded', $this, 'plugin_update');

        $this->loader->add_action( 'woocommerce_order_status_changed', $plugin_admin, 'exportOrder' );
		
		$this->loader->add_filter( 'auto_update_plugin', $this, 'linknetwerk_enable_plugin_auto_updates', 10, 2 );
    }
	
	public function linknetwerk_enable_plugin_auto_updates( $value, $item )
    {
        if ('lupsonline-link-netwerk' === $item->slug && get_option("lupsOnlineLinkNetwerkAutoUpdate")) {
            return true; // Enable auto-updates for the specified plugin
        }

        return $value; // Preserve auto-update status for other plugins
    }

    /**
     * Create custom api endpoints
     *
     * @access   private
     */
    private function define_api_endpoints(){

        // General endpoints
        add_action('rest_api_init', function () {
            // GET Link
            register_rest_route( 'lupsonlinelinknetwerk', 'version',array(
                'methods'  => 'GET',
                'callback' => array(new LinkNetwerk_API,'getVersion'),
                'permission_callback' => '__return_true'
            ));

        });

        // Link(s)
        add_action('rest_api_init', function () {
            // GET Link
            register_rest_route( 'lupsonlinelinknetwerk', 'link',array(
                'methods'  => 'GET',
                'callback' => array(new LinkNetwerk_API,'getLink'),
                'permission_callback' => '__return_true'
            ));

            // ADD Link
            register_rest_route( 'lupsonlinelinknetwerk', 'link',array(
                'methods'  => 'POST',
                'callback' => array(new LinkNetwerk_API,'addLink'),
                'permission_callback' => '__return_true'
            ));

            // CHANGE Link
            register_rest_route( 'lupsonlinelinknetwerk', 'link',array(
                'methods'  => 'PUT',
                'callback' => array(new LinkNetwerk_API,'changeLink'),
                'permission_callback' => '__return_true'
            ));

            // DELETE Link
            register_rest_route( 'lupsonlinelinknetwerk', 'link',array(
                'methods'  => 'DELETE',
                'callback' => array(new LinkNetwerk_API,'deleteLink'),
                'permission_callback' => '__return_true'
            ));

            register_rest_route( 'lupsonlinelinknetwerk', 'link-all',array(
                'methods'  => 'DELETE',
                'callback' => array(new LinkNetwerk_API,'deleteAllLinks'),
                'permission_callback' => '__return_true'
            ));
        });

        // Categories
        add_action('rest_api_init', function () {
            register_rest_route( 'lupsonlinelinknetwerk', 'category',array(
                'methods'  => 'GET',
                'callback' => array(new LinkNetwerk_API,'getCategories'),
                'permission_callback' => '__return_true'
            ));
            register_rest_route( 'lupsonlinelinknetwerk', 'category',array(
                'methods'  => 'POST',
                'callback' => array(new LinkNetwerk_API,'addCategory'),
                'permission_callback' => '__return_true'
            ));
        });

        // BLOG
        add_action('rest_api_init', function () {
            // GET BLOG
            register_rest_route( 'lupsonlinelinknetwerk', 'blog',array(
                'methods'  => 'GET',
                'callback' => array(new LinkNetwerk_API,'getBlog'),
                'permission_callback' => '__return_true'
            ));

            // ADD BLOG
            register_rest_route( 'lupsonlinelinknetwerk', 'blog',array(
                'methods'  => 'POST',
                'callback' => array(new LinkNetwerk_API,'addBlog'),
                'permission_callback' => '__return_true'
            ));

            // CHANGE BLOG
            register_rest_route( 'lupsonlinelinknetwerk', 'blog',array(
                'methods'  => 'PUT',
                'callback' => array(new LinkNetwerk_API,'changeBlog'),
                'permission_callback' => '__return_true'
            ));

            // DELETE BLOG
            register_rest_route( 'lupsonlinelinknetwerk', 'blog',array(
                'methods'  => 'DELETE',
                'callback' => array(new LinkNetwerk_API,'deleteBlog'),
                'permission_callback' => '__return_true'
            ));
        });
    }

    /**
     * Run after plugin activation
     *
     */
    public static function run_on_activate() {
       add_option(self::get_plugin_name().'_version', self::get_version());
       self::initDatabase();
    }

    /**
     * Run after plugin deactivation
     */
    public static function run_on_deactivate() {

    }

    /**
     * Run after plugin is uninstalled
     *
     */
    public static function run_on_uninstall() {
        self::deleteDatabase();
    }

    public function plugin_update() {
        $version = get_option(self::get_plugin_name().'_version');
        if(!$version) $version = '1.1.0';

        if ( $version != self::get_version() )
            self::plugin_updates(self::get_version());
    }

    public static function plugin_updates($version) {
        global $wpdb;

        $table = $wpdb->prefix . strtolower(self::$plugin_name);

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

        $charset_collate = $wpdb->get_charset_collate();

        $version = str_replace(".", "", $version);
        if($version >= 110){
            $dbTableNameInstellingen = $wpdb->prefix .self::$dbTableNameInstellingen;
            if($wpdb->get_var( "show tables like '$dbTableNameInstellingen'" ) != $dbTableNameInstellingen )
            {
                   $sql = "CREATE TABLE $dbTableNameInstellingen (
                            id int(11) NOT NULL auto_increment,
                            `key` varchar(75) NOT NULL,
                            `value` varchar(75) NOT NULL,
                            createdAt datetime NOT NULL default now(),
                            updatedAt datetime NOT NULL default now(),
                            UNIQUE KEY id (id)
                    ) $charset_collate;";

               dbDelta( $sql );
            }
        }
        if($version >= 122 && $version <= 123){

            $currentValues = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);
            // Clear table
            $wpdb->query( "TRUNCATE $table" );
            // Update table
            $wpdb->query("ALTER TABLE $table ADD UNIQUE `Unique` (`post_id`, `website_link_id`);");

            // Re-insert current values

            foreach($currentValues as $currentValue){
                $sql = $wpdb->prepare("INSERT IGNORE INTO $table (`id`, `post_id`, `website_link_id`, `link`, `createdAt`, `updatedAt`)
                    VALUES( %d, %d, %d, %s, %s, %s)", $currentValue['id'], $currentValue['post_id'], $currentValue['website_link_id'], $currentValue['link'], $currentValue['createdAt'],  $currentValue['updatedAt']);
                $result = $wpdb->query($sql);
            }
        }
        if($version >= 123 && $version <= 124){
            if($wpdb->get_var( "show tables like '$table'" ) == $table ) {
                $wpdb->query("ALTER TABLE $table ADD `visibleFrom` DATETIME NULL AFTER `updatedAt`, ADD `visibleTill` DATETIME NULL AFTER `visibleFrom`;");
            }
        }
        if($version >= 125){
            if($wpdb->get_var( "show tables like '$table'" ) == $table ) {
                try {
                    $wpdb->query("ALTER TABLE $table ADD `visibleFrom` DATETIME NULL AFTER `updatedAt`, ADD `visibleTill` DATETIME NULL AFTER `visibleFrom`;");
                } catch (Exception $e) {

                }
            }
        }



        // update option
        update_option(self::get_plugin_name().'_version', self::get_version());
    }

    /**
     * Run the loader to execute all of the hooks with WordPress.
     *
     */
    public function run() {
        $this->loader->run();
    }

    /**
     * The name of the plugin used to uniquely identify it within the context of
     * WordPress and to define internationalization functionality.
     *
     * @return    string    The name of the plugin.
     */
    public static function get_plugin_name() {
        return self::$plugin_name;
    }

    /**
     * The reference to the class that orchestrates the hooks with the plugin.
     *
     * @return    Plugin_Name_Loader    Orchestrates the hooks of the plugin.
     */
    public function get_loader() {
        return $this->loader;
    }

    /**
     * Retrieve the version number of the plugin.
     *
     * @return    string    The version number of the plugin.
     */
    public static function get_version() {
        return self::$version;
    }

    private static function initDatabase(){
        global $wpdb;
        $db_table_name = $wpdb->prefix . strtolower('LupsOnlineLinkNetwerk');  // table name
        $charset_collate = $wpdb->get_charset_collate();

        //Check to see if the table exists already, if not, then create it
        if($wpdb->get_var( "show tables like '$db_table_name'" ) != $db_table_name )
        {
               $sql = "CREATE TABLE $db_table_name (
                        id int(11) NOT NULL auto_increment,
                        post_id int(11) NOT NULL,
                        website_link_id int(11) NOT NULL,
                        link text NOT NULL,
                        createdAt datetime NOT NULL default now(),
                        updatedAt datetime NOT NULL default now(),
                        UNIQUE KEY id (id)
                ) $charset_collate;";

           require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
           dbDelta( $sql );
        }

    }

    private static function deleteDatabase(){
        global $wpdb;
        $db_table_name = $wpdb->prefix . strtolower('LupsOnlineLinkNetwerk');

        $wpdb->query( "DROP TABLE IF EXISTS $db_table_name" );
        delete_option($db_table_name);

    }

}
