<?php
/**
 * Update class to skip onboarding for existing installations
 *
 * @package SAAI\Updates
 */

namespace SAAI\Updates;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Actions\Activation;
use SAAI\Classes\Onboarding_Wizard;

defined( 'ABSPATH' ) || exit;

/**
 * Skip_Onboarding_For_Updates update class.
 *
 * This update ensures that existing users who are updating the plugin
 * don't see the onboarding wizard. The wizard should only show for
 * fresh installations.
 *
 * @since 1.1.2
 */
class Skip_Onboarding_For_Updates extends Abstract_Class {

    /**
     * Run the update.
     *
     * This script checks if the plugin is being updated (not freshly installed)
     * and sets the onboarding status to 'skipped' for existing users.
     *
     * Detection logic:
     * - Fresh install: PLUGIN_INSTALLED_TIMESTAMP is set during this activation
     * - Update: PLUGIN_INSTALLED_TIMESTAMP already exists from previous installation
     *
     * @since 1.1.2
     * @return void
     */
    public function run() {
        $plugin_installed_timestamp = get_option( Activation::PLUGIN_INSTALLED_TIMESTAMP );
        $stored_version             = get_option( SAAI_INSTALLED_VERSION );

        // Check if this is an update (not a fresh install).
        // For fresh installs, either:
        // 1. PLUGIN_INSTALLED_TIMESTAMP was just set in this run, OR
        // 2. Both timestamp and version won't exist yet
        //
        // For updates:
        // 1. PLUGIN_INSTALLED_TIMESTAMP exists from previous installation, AND
        // 2. SAAI_INSTALLED_VERSION exists with the old version
        //
        // We use both checks for maximum reliability.
        $is_update = ! empty( $plugin_installed_timestamp ) && ! empty( $stored_version );

        if ( $is_update ) {
            // Check if onboarding status is already set.
            $onboarding_status = get_option( Onboarding_Wizard::WIZARD_STATUS_OPTION );

            // Only set to skipped if the status is not already set.
            // This prevents overwriting completed/skipped status.
            if ( empty( $onboarding_status ) ) {
                update_option( Onboarding_Wizard::WIZARD_STATUS_OPTION, Onboarding_Wizard::STATUS_SKIPPED, false );
            }
        }
    }
}
