<?php
/**
 * Version Checker for Easy Invoice
 *
 * @package     EasyInvoice
 * @subpackage  Migration
 * @since       2.0.0
 */

namespace EasyInvoice\Migration;

/**
 * Version Checker Class
 * 
 * Handles version checking and comparison.
 * 
 * @since 2.0.0
 */
class VersionChecker {
    
    /**
     * Target version.
     * 
     * @since 2.0.0
     * @var string
     */
    private $target_version = '2.0.0';
    
    /**
     * Singleton instance.
     * 
     * @since 2.0.0
     * @var VersionChecker
     */
    private static $instance = null;
    
    /**
     * Get singleton instance.
     * 
     * @since 2.0.0
     * @return VersionChecker
     */
    public static function get_instance(): VersionChecker {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Get stored version.
     * 
     * @since 2.0.0
     * @return string
     */
    public function get_stored_version(): string {
        // First check the new option name
        $version = get_option('easy_invoice_version');
        if ($version !== false) {
            return $this->sanitize_version($version);
        }
        
        // Check old option name
        $version = get_option('easy_invoice_db_version');
        if ($version !== false) {
            return $this->sanitize_version($version);
        }
        
        // Check if old plugin exists
        if ($this->old_plugin_exists()) {
            return '1.0.0';
        }
        
        // Default to current version if no old version found
        return $this->target_version;
    }
    
    /**
     * Get target version.
     * 
     * @since 2.0.0
     * @return string
     */
    public function get_target_version(): string {
        return $this->target_version;
    }
    
    /**
     * Check if migration is needed.
     * 
     * @since 2.0.0
     * @return bool
     */
    public function is_migration_needed(): bool {
        // If migration was skipped, don't show it again
        if (get_option('easy_invoice_migration_skipped', false)) {
            return false;
        }
        
        // If migration is completed, no need to migrate
        if ($this->is_migration_completed()) {
            return false;
        }
        
        // Check if old plugin exists
        if ($this->old_plugin_exists()) {
            return true;
        }
        
        // Check version comparison
        $current_version = $this->get_stored_version();
        
        // If current version is already 2.0.0 or higher and no old data exists,
        // this is likely a fresh installation, so no migration needed
        if (version_compare($current_version, $this->target_version, '>=')) {
            return false;
        }
        
        return version_compare($current_version, $this->target_version, '<');
    }
    
    /**
     * Check if migration is completed.
     * 
     * @since 2.0.0
     * @return bool
     */
    public function is_migration_completed(): bool {
        // Check if migration completed flag is set
        $is_completed = get_option('easy_invoice_migration_completed', false);
        
        // Also verify version is up to date
        if ($is_completed) {
            $current_version = $this->get_stored_version();
            return version_compare($current_version, $this->target_version, '>=');
        }
        
        return false;
    }
    
    /**
     * Check if migration is running.
     * 
     * @since 2.0.0
     * @return bool
     */
    public function is_migration_running(): bool {
        return get_option('easy_invoice_migration_running', false);
    }
    
    /**
     * Get migration status.
     * 
     * @since 2.0.0
     * @return string Status: 'needed', 'running', 'completed', or 'not_needed'
     */
    public function get_migration_status(): string {
        if ($this->is_migration_running()) {
            return 'running';
        }
        
        if ($this->is_migration_completed()) {
            return 'completed';
        }
        
        if ($this->is_migration_needed()) {
            return 'needed';
        }
        
        return 'not_needed';
    }
    
    /**
     * Check if old plugin exists.
     * 
     * @since 2.0.0
     * @return bool
     */
    private function old_plugin_exists(): bool {
        global $wpdb;
        
        // Check if old post types exist
        $old_post_types = ['easy-invoice', 'easy-invoice-quotes', 'easy-invoice-payment'];
        foreach ($old_post_types as $post_type) {
            $count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s LIMIT 1",
                    $post_type
                )
            );
            
            if ($count > 0) {
                return true;
            }
        }
        
        // Check if old options exist
        $old_options = [
            'easy_invoice_business_name',
            'easy_invoice_business_address',
            'easy_invoice_currency',
            'easy_invoice_tax_rate',
            'easy_invoice_invoice_number',
            'easy_invoice_quote_number'
        ];
        
        foreach ($old_options as $option) {
            if (get_option($option) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Mark migration as completed for fresh installations.
     * 
     * @since 2.0.0
     * @return void
     */
    public function mark_fresh_installation_completed(): void {
        update_option('easy_invoice_version', $this->target_version);
        update_option('easy_invoice_migration_completed', true);
    }
    
    /**
     * Check if this is a fresh installation (no old data and version is current).
     * 
     * @since 2.0.0
     * @return bool
     */
    public function is_fresh_installation(): bool {
        // If migration is already completed, it's not a fresh installation
        if ($this->is_migration_completed()) {
            return false;
        }
        
        // If old plugin data exists, it's not a fresh installation
        if ($this->old_plugin_exists()) {
            return false;
        }
        
        // Check if current version is already up to date
        $current_version = $this->get_stored_version();
        return version_compare($current_version, $this->target_version, '>=');
    }
    

    
    /**
     * Sanitize version string.
     * 
     * @since 2.0.0
     * @param string $version Version string
     * @return string
     */
    private function sanitize_version(string $version): string {
        // Remove any non-version characters
        $version = preg_replace('/[^0-9.]/', '', $version);
        
        // Ensure at least major.minor.patch format
        $parts = explode('.', $version);
        while (count($parts) < 3) {
            $parts[] = '0';
        }
        
        return implode('.', array_slice($parts, 0, 3));
    }
}