<?php
/**
 * Pro Options Migration for Easy Invoice
 *
 * @package     EasyInvoice
 * @subpackage  Migration
 * @since       2.0.0
 */

namespace EasyInvoice\Migration\Src;

/**
 * Pro Options Migration Class
 *
 * Migrates pro-specific options from old pro plugin to new pro plugin.
 *
 * @since 2.0.0
 */
class ProOptionsMigration extends AbstractMigration {

    /**
     * Migration description.
     *
     * @since 2.0.0
     * @var string
     */
    protected $description = 'Migrate pro-specific options from old pro plugin';

    /**
     * Option mappings.
     *
     * @since 2.0.0
     * @var array
     */
    private $option_mappings = [
        // Profile/Restriction settings
        'easy_invoice_restrict_invoice' => 'easy_invoice_pro_restrict_invoice_to_client',
        'easy_invoice_restrict_quote' => 'easy_invoice_pro_restrict_quote_to_client',

        // Permalink settings
        'easy_invoice_permalink_for_invoice' => 'easy_invoice_pro_secure_invoice_slug',
        'easy_invoice_permalink_for_quotes' => 'easy_invoice_pro_secure_quote_slug',
        'easy_invoice_protect_invoice' => 'easy_invoice_pro_enable_secure_links',
        'easy_invoice_protect_quote' => 'easy_invoice_pro_enable_secure_links',

        // PDF Header settings
        'easy_invoice_pdf_header_background_color' => 'easy_invoice_pro_pdf_header_background_color',
        'easy_invoice_pdf_header_padding_left' => 'easy_invoice_pro_pdf_header_padding_left',
        'easy_invoice_pdf_header_padding_right' => 'easy_invoice_pro_pdf_header_padding_right',
        'easy_invoice_pdf_header_padding_top' => 'easy_invoice_pro_pdf_header_padding_top',
        'easy_invoice_pdf_header_padding_bottom' => 'easy_invoice_pro_pdf_header_padding_bottom',

        // PDF Body settings
        'easy_invoice_pdf_content_area_background_color' => 'easy_invoice_pro_pdf_content_background_color',
        'easy_invoice_pdf_content_area_padding_left' => 'easy_invoice_pro_pdf_content_padding_left',
        'easy_invoice_pdf_content_area_padding_right' => 'easy_invoice_pro_pdf_content_padding_right',
        'easy_invoice_pdf_content_area_padding_top' => 'easy_invoice_pro_pdf_content_padding_top',
        'easy_invoice_pdf_content_area_padding_bottom' => 'easy_invoice_pro_pdf_content_padding_bottom',

        // PDF Footer settings
        'easy_invoice_pdf_footer_background_color' => 'easy_invoice_pro_pdf_footer_background_color',
        'easy_invoice_pdf_footer_padding_left' => 'easy_invoice_pro_pdf_footer_padding_left',
        'easy_invoice_pdf_footer_padding_right' => 'easy_invoice_pro_pdf_footer_padding_right',
        'easy_invoice_pdf_footer_padding_top' => 'easy_invoice_pro_pdf_footer_padding_top',
        'easy_invoice_pdf_footer_padding_bottom' => 'easy_invoice_pro_pdf_footer_padding_bottom',
        'easy_invoice_pdf_footer_show_page_number' => 'easy_invoice_pro_pdf_show_page_number',

        // PDF Watermark settings
        'easy_invoice_pdf_text_watermark' => 'easy_invoice_pro_text_watermark',
        'easy_invoice_pdf_show_invoice_status_watermark' => 'easy_invoice_pro_status_watermark_enable',
        'easy_invoice_pdf_show_quote_status_watermark' => 'easy_invoice_pro_status_watermark_enable',
        'easy_invoice_pdf_text_watermark_alpha' => 'easy_invoice_pro_watermark_opacity',
        'easy_invoice_pdf_text_watermark_angle' => 'easy_invoice_pro_text_watermark_angle',
        'easy_invoice_pdf_image_watermark' => 'easy_invoice_pro_image_watermark',
        'easy_invoice_pdf_image_watermark_alpha' => 'easy_invoice_pro_image_watermark_opacity',
        'easy_invoice_pdf_image_watermark_size_x' => 'easy_invoice_pro_image_watermark_size',
        'easy_invoice_pdf_image_watermark_size_y' => 'easy_invoice_pro_image_watermark_size',
        'easy_invoice_pdf_image_watermark_position_x' => 'easy_invoice_pro_image_watermark_position_x',
        'easy_invoice_pdf_image_watermark_position_y' => 'easy_invoice_pro_image_watermark_position_y',

        // PDF General settings
        'easy_invoice_pdf_page_orientation' => 'easy_invoice_pro_orientation',
        'easy_invoice_pdf_download_preview' => 'easy_invoice_pro_pdf_download_preview',
        'easy_invoice_pdf_page_margin_left' => 'easy_invoice_pro_margins_left',
        'easy_invoice_pdf_page_margin_right' => 'easy_invoice_pro_margins_right',
        'easy_invoice_pdf_page_margin_top' => 'easy_invoice_pro_margins_top',
        'easy_invoice_pdf_page_margin_bottom' => 'easy_invoice_pro_margins_bottom',
        'easy_invoice_pdf_page_margin_header' => 'easy_invoice_pro_margins_header',
        'easy_invoice_pdf_page_margin_footer' => 'easy_invoice_pro_margins_footer',

        // PDF Protection settings
        'easy_invoice_pdf_page_enable_protection' => 'easy_invoice_pro_pdf_enable_protection',
        'easy_invoice_pdf_page_protected_permissions' => 'easy_invoice_pro_pdf_protected_permissions',
        'easy_invoice_pdf_page_user_password' => 'easy_invoice_pro_pdf_user_password',
        'easy_invoice_pdf_page_owner_password' => 'easy_invoice_pro_pdf_owner_password'
    ];

    /**
     * Check if migration is needed.
     *
     * @since 2.0.0
     * @return bool
     */
    public function is_needed(): bool {
        // Check if any old pro options exist
        foreach (array_keys($this->option_mappings) as $old_option) {
            if ($this->option_exists($old_option)) {
                $this->log(sprintf('Found old pro option: %s', $old_option));
                return true;
            }
        }

        return false;
    }

    /**
     * Run the migration.
     *
     * @since 2.0.0
     * @return array
     */
    public function migrate(): array {
        $this->log('Starting pro options migration');

        try {
            $migrated_count = 0;
            $errors = [];

            foreach ($this->option_mappings as $old_option => $new_option) {
                try {
                    $old_value = get_option($old_option);

                    if ($old_value !== false) {
                        // Transform the value
                        $new_value = $this->transform_option_value($old_option, $old_value);

                        // Save to new option
                        $result = $this->update_option_safe($new_option, $new_value);

                        if ($result) {
                            $migrated_count++;

                            // Delete old option after successful migration
                            delete_option($old_option);
                        } else {
                            $errors[] = sprintf('Failed to update option %s', $new_option);
                        }
                    }
                } catch (\Exception $e) {
                    $errors[] = sprintf('Failed to migrate option %s: %s', $old_option, $e->getMessage());
                }
            }

            $this->log(sprintf('Pro options migration completed. Migrated: %d, Errors: %d', $migrated_count, count($errors)));

            return [
                'success' => empty($errors),
                'migrated' => $migrated_count,
                'errors' => $errors
            ];

        } catch (\Exception $e) {
            $this->log('Pro options migration failed: ' . $e->getMessage());
            return [
                'success' => false,
                'migrated' => 0,
                'errors' => [$e->getMessage()]
            ];
        }
    }

    /**
     * Transform option value based on key.
     *
     * @since 2.0.0
     * @param string $old_option Old option name
     * @param mixed $old_value Old option value
     * @return mixed
     */
    private function transform_option_value(string $old_option, $old_value) {
        // Handle boolean values
        if (strpos($old_option, 'protect_') !== false ||
            strpos($old_option, 'restrict_') !== false ||
            strpos($old_option, 'show_') !== false ||
            strpos($old_option, 'enable_') !== false) {
            return ValueTransformer::transform_boolean($old_value);
        }

        // Handle orientation
        if ($old_option === 'easy_invoice_pdf_page_orientation') {
            return $old_value === 'vertical' ? 'portrait' : 'landscape';
        }

        // Handle download/preview mode
        if ($old_option === 'easy_invoice_pdf_download_preview') {
            return $old_value === 'download' ? 'download' : 'preview';
        }

        // Handle opacity values
        if (strpos($old_option, '_alpha') !== false) {
            return min(100, max(0, intval($old_value * 100)));
        }

        // Handle watermark size
        if (strpos($old_option, '_watermark_size_') !== false) {
            return max(50, min(500, intval($old_value)));
        }

        // Handle watermark angle
        if ($old_option === 'easy_invoice_pdf_text_watermark_angle') {
            return max(0, min(360, intval($old_value)));
        }

        // Handle padding and margin values
        if (strpos($old_option, '_padding_') !== false ||
            strpos($old_option, '_margin_') !== false) {
            return max(0, min(100, intval($old_value)));
        }

        // Handle color values
        if (strpos($old_option, '_color') !== false) {
            return preg_match('/^#[a-f0-9]{6}$/i', $old_value) ? $old_value : '#FFFFFF';
        }

        return $old_value;
    }
}
