<?php

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

/**
 * Abstract base class for version updaters
 * Provides common functionality and interface
 */
abstract class BWDCV_Base_Updater {

    protected $from_version;
    protected $to_version;
    protected $target_version;
    protected $success = false;

    public function __construct( $from_version, $to_version ) {
        $this->from_version = $from_version;
        $this->to_version   = $to_version;
    }

    /**
     * Check if this update should run
     * Override this method for custom logic
     */
    protected function should_update() {
        return version_compare( $this->from_version, $this->target_version, '<' ) &&
               version_compare( $this->to_version, $this->target_version, '>=' );
    }

    /**
     * Abstract method that must be implemented by each updater
     */
    abstract protected function perform_update();

    /**
     * Main run method
     */
    public function run() {
        if ( ! $this->should_update() ) {
            $this->success = true; // Not running is considered success
            return true;
        }

        try {
            $this->perform_update();
            $this->success = true;
            return true;
        } catch ( Exception $e ) {
            error_log( 'Updater ' . get_class( $this ) . ' failed: ' . $e->getMessage() );
            $this->success = false;
            return false;
        }
    }

    /**
     * Check if the update was successful
     */
    public function was_successful() {
        return $this->success;
    }

    /**
     * Helper method to set success notice
     */
    protected function set_success_notice( $message ) {
        set_transient( 'bwdcv_update_notice', [
            'type'    => 'success',
            'message' => $message
        ], 30 );
    }

    /**
     * Helper method to set error notice
     */
    protected function set_error_notice( $message ) {
        set_transient( 'bwdcv_update_notice', [
            'type'    => 'error',
            'message' => $message
        ], 60 );
    }

}
