<?php
/**
 * Value Transformer for Easy Invoice Migration
 *
 * @package     EasyInvoice
 * @subpackage  Migration
 * @since       2.0.0
 */

namespace EasyInvoice\Migration\Src;

/**
 * Value transformer class.
 *
 * Provides shared transformation logic for all migration classes.
 *
 * @since 2.0.0
 */
class ValueTransformer {

    /**
     * Transform date value to MySQL format.
     *
     * @since 2.0.0
     * @param mixed $date_value Date value
     * @return string MySQL formatted date
     */
    public static function transform_date($date_value): string {
        if (empty($date_value)) {
            return current_time('mysql');
        }

        // If it's already a MySQL date format, return as is
        if (preg_match('/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/', $date_value)) {
            return $date_value;
        }

        // Try to parse the date
        $timestamp = strtotime($date_value);
        if ($timestamp === false) {
            return current_time('mysql');
        }

        return date('Y-m-d H:i:s', $timestamp);
    }

    /**
     * Transform currency value to standard code.
     *
     * @since 2.0.0
     * @param mixed $currency Currency value
     * @return string Currency code
     */
    public static function transform_currency($currency): string {
        if (empty($currency)) {
            return 'USD';
        }

        $currency = strtoupper(trim($currency));

        // Common currency mappings
        $mappings = [
            '$' => 'USD',
            '£' => 'GBP',
            '€' => 'EUR',
            '¥' => 'JPY',
            'USD' => 'USD',
            'EUR' => 'EUR',
            'GBP' => 'GBP',
            'JPY' => 'JPY',
            'DOLLAR' => 'USD',
            'EURO' => 'EUR',
            'POUND' => 'GBP',
            'YEN' => 'JPY'
        ];

        return $mappings[$currency] ?? 'USD';
    }

    /**
     * Transform boolean value.
     *
     * @since 2.0.0
     * @param mixed $value Boolean value
     * @return bool
     */
    public static function transform_boolean($value): bool {
        if (is_bool($value)) {
            return $value;
        }

        if (is_string($value)) {
            return in_array(strtolower($value), ['true', '1', 'yes', 'on'], true);
        }

        if (is_numeric($value)) {
            return (bool)$value;
        }

        return false;
    }

    /**
     * Transform payment method value.
     *
     * @since 2.0.0
     * @param mixed $method Payment method value
     * @return string
     */
    public static function transform_payment_method($method): string {
        if (empty($method)) {
            return 'bank_transfer';
        }

        $method = strtolower(trim($method));

        $mappings = [
            'bank' => 'bank_transfer',
            'bank_transfer' => 'bank_transfer',
            'wire' => 'bank_transfer',
            'wire_transfer' => 'bank_transfer',
            'cash' => 'cash',
            'check' => 'check',
            'cheque' => 'check',
            'paypal' => 'paypal',
            'stripe' => 'stripe',
            'credit_card' => 'credit_card',
            'debit_card' => 'credit_card',
            'card' => 'credit_card',
            'other' => 'other'
        ];

        return $mappings[$method] ?? 'other';
    }

    /**
     * Transform payment methods array.
     *
     * @since 2.0.0
     * @param mixed $methods Payment methods array
     * @return array
     */
    public static function transform_payment_methods($methods): array {
        if (!is_array($methods)) {
            return [];
        }

        $transformed = [];
        foreach ($methods as $method) {
            if (is_array($method)) {
                $transformed[] = [
                    'id' => $method['id'] ?? '',
                    'name' => $method['name'] ?? '',
                    'description' => $method['description'] ?? '',
                    'enabled' => isset($method['enabled']) ? self::transform_boolean($method['enabled']) : true,
                    'settings' => $method['settings'] ?? []
                ];
            }
        }

        return $transformed;
    }

    /**
     * Transform invoice/quote status.
     *
     * @since 2.0.0
     * @param string $type Document type (invoice/quote)
     * @param mixed $status Status value
     * @return string
     */
    public static function transform_status(string $type, $status): string {
        if (empty($status)) {
            return 'draft';
        }

        $status = strtolower(trim($status));

        // Status mappings
        $mappings = [
            'invoice' => [
                'draft' => 'draft',
                'pending' => 'pending',
                'published' => 'published',
                'paid' => 'paid',
                'partially_paid' => 'partially_paid',
                'overdue' => 'overdue',
                'cancelled' => 'cancelled',
                'unpaid' => 'pending',
                'complete' => 'paid',
                'partial' => 'partially_paid',
                'void' => 'cancelled'
            ],
            'quote' => [
                'draft' => 'draft',
                'pending' => 'pending',
                'sent' => 'sent',
                'accepted' => 'accepted',
                'declined' => 'declined',
                'expired' => 'expired',
                'cancelled' => 'cancelled',
                'approved' => 'accepted',
                'rejected' => 'declined',
                'void' => 'cancelled'
            ],
            'payment' => [
                'pending' => 'pending',
                'completed' => 'completed',
                'failed' => 'failed',
                'refunded' => 'refunded',
                'processing' => 'pending',
                'success' => 'completed',
                'error' => 'failed',
                'cancelled' => 'failed',
                'void' => 'failed'
            ]
        ];

        return $mappings[$type][$status] ?? 'draft';
    }

    /**
     * Transform tax type value.
     *
     * @since 2.0.0
     * @param mixed $tax_type Tax type value
     * @return string
     */
    public static function transform_tax_type($tax_type): string {
        if (empty($tax_type)) {
            return 'exclusive';
        }

        $tax_type = strtolower(trim($tax_type));

        $mappings = [
            'inclusive' => 'inclusive',
            'exclusive' => 'exclusive',
            'none' => 'none',
            'included' => 'inclusive',
            'excluded' => 'exclusive',
            'disabled' => 'none',
            'yes' => 'exclusive',
            'no' => 'none',
            '1' => 'exclusive',
            '0' => 'none'
        ];

        return $mappings[$tax_type] ?? 'exclusive';
    }

    /**
     * Transform currency position value.
     *
     * @since 2.0.0
     * @param mixed $position Currency position value
     * @return string
     */
    public static function transform_currency_position($position): string {
        if (empty($position)) {
            return 'before';
        }

        $position = strtolower(trim($position));

        $mappings = [
            'left' => 'before',
            'right' => 'after',
            'left_space' => 'before_space',
            'right_space' => 'after_space',
            'before' => 'before',
            'after' => 'after',
            'before_space' => 'before_space',
            'after_space' => 'after_space'
        ];

        return $mappings[$position] ?? 'before';
    }

    /**
     * Transform amount value.
     *
     * @since 2.0.0
     * @param mixed $amount Amount value
     * @return float
     */
    public static function transform_amount($amount): float {
        if (empty($amount)) {
            return 0.00;
        }

        // If it's already a float or int, just return it
        if (is_float($amount) || is_int($amount)) {
            return (float)$amount;
        }

        // If it's a string, clean it up first
        if (is_string($amount)) {
            // Remove any currency symbols and thousands separators
            $amount = preg_replace('/[^0-9.-]/', '', $amount);

            // Convert to float
            return (float)$amount;
        }

        return 0.00;
    }

    /**
     * Transform template value.
     *
     * @since 2.0.0
     * @param mixed $template Template value
     * @param string $type Document type (invoice/quote)
     * @return string
     */
    public static function transform_template($template, string $type = 'invoice'): string {
        if (empty($template)) {
            return 'minimal';
        }

        $template = strtolower(trim($template));

        $mappings = [
            'invoice' => [
                'minimal' => 'minimal',
                'modern' => 'modern',
                'classic' => 'classic',
                'professional' => 'professional',
                'business' => 'business',
                'simple' => 'minimal',
                'basic' => 'minimal',
                'standard' => 'classic',
                'default' => 'minimal'
            ],
            'quote' => [
                'minimal' => 'minimal',
                'modern' => 'modern',
                'classic' => 'classic',
                'professional' => 'professional',
                'simple' => 'minimal',
                'basic' => 'minimal',
                'standard' => 'classic',
                'default' => 'minimal'
            ]
        ];

        return $mappings[$type][$template] ?? 'minimal';
    }

    /**
     * Transform watermark type value.
     *
     * @since 2.0.0
     * @param mixed $type Watermark type value
     * @return string
     */
    public static function transform_watermark_type($type): string {
        if (empty($type)) {
            return 'text';
        }

        $type = strtolower(trim($type));

        $mappings = [
            'text' => 'text',
            'image' => 'image',
            'none' => 'none',
            'disabled' => 'none',
            'off' => 'none',
            'on' => 'text'
        ];

        return $mappings[$type] ?? 'text';
    }
}
