<?php

namespace AdvancedBlockControls;

// Exit if the file is accessed directly
if ( !defined('ABSPATH') ) {
    exit; 
}

/**
 * Class Upgrader
 * 
 * This class is responsible for handling plugin upgrades when version updates are needed.
 * It manages version-specific upgrades and ensures smooth transitions between plugin versions
 * when structural changes or data migrations are required.
 * 
 * @package AdvancedBlockControls
 */
class Upgrader
{
    /**
     * Current plugin version from stored option
     *
     * @var string
     */
    private $stored_version;

    /**
     * Latest plugin version from constant
     *
     * @var string
     */
    private $latest_version;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->stored_version = get_option('abcon_upgrade_version', false);
        $this->latest_version = ABCON_VERSION;
        
        // Register the upgrade check for both activation and updates
        register_activation_hook(ABCON_FILE, array($this, 'check_version'));
        add_action('init', array($this, 'check_version'), 5);
    }

    /**
     * Check if an upgrade is needed
     */
    public function check_version()
    {
        // Run upgrade if version is not set or if it's lower than current version
        if ($this->stored_version === false || version_compare($this->stored_version, $this->latest_version, '<')) {
            $this->perform_upgrade();
        }
    }

    /**
     * Perform the upgrade process
     */
    private function perform_upgrade()
    {

        if (get_transient('abcon_upgrading')) {
            return;
        }

        // upgrade process for version 1.9.0
        if ($this->stored_version === false || version_compare($this->stored_version, '1.9.0', '<')) {
            set_transient('abcon_upgrading', true, 300); // Lock upgrade for 5 minutes
            $this->upgrade_to_1_9_0();
            delete_transient('abcon_upgrading');
        }

        // Update the stored version to match current plugin version
        update_option('abcon_upgrade_version', $this->latest_version);
    }

    /**
     * Upgrade to version 1.9
     */
    private function upgrade_to_1_9_0()
    {
        global $wpdb;

        // Check if any of the new control types already exist
        $check_sql = $wpdb->prepare(
            "SELECT type FROM {$wpdb->prefix}abcon_controls 
            WHERE type IN ('sizing', 'position', 'layout') 
            LIMIT 1"
        );
        
        $existing_control = $wpdb->get_row($check_sql);
        
        if ($existing_control) {
            error_log(sprintf(
                '[Advanced Block Controls] It seems that database upgrade for version 1.9.0 has already been handled, we found the control type: %s',
                $existing_control->type
            ));
            return;
        }
        
        // Get the SQL file content
        $sql_file = plugin_dir_path(dirname(__FILE__)) . 'upgrades/1.9.0.sql';
        if (!file_exists($sql_file)) {
            return;
        }

        $sql = file_get_contents($sql_file);
        if (!$sql) {
            return;
        }

        // Replace the prefix placeholder with actual prefix
        $sql = str_replace('{prefix}_', $wpdb->prefix, $sql);

        // Split SQL by semicolon to execute multiple queries
        $queries = explode(';', $sql);
        
        foreach ($queries as $query) {
            $query = trim($query);
            if (!empty($query)) {
                $wpdb->query($query);
            }
        }
    }
} 