<?php
namespace PrimeLink\Modules\Customers;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class CustomerImportService {
    /**
     * Find an existing customer by a given field (email, username, customer_id)
     * 
     * @param array $customer_data Customer data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return int User ID or 0 if not found
     */
    public static function find_existing_customer_id( $customer_data, $match_by, $batch_lookups = null ) {
        if ( $match_by === 'email' && !empty($customer_data['email']) ) {
            $email = sanitize_email( $customer_data['email'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['users_by_email'][ strtolower( $email ) ] ) ) {
                return absint( $batch_lookups['users_by_email'][ strtolower( $email ) ] );
            }
            
            // Fallback to individual lookup
            $user = get_user_by( 'email', $email );
            return $user ? $user->ID : 0;
        }
        if ( $match_by === 'username' && !empty($customer_data['username']) ) {
            $user = get_user_by( 'login', sanitize_user($customer_data['username']) );
            return $user ? $user->ID : 0;
        }
        if ( $match_by === 'customer_id' && !empty($customer_data['customer_id']) ) {
            $user_id = absint($customer_data['customer_id']);
            $user = get_user_by( 'ID', $user_id );
            return $user ? $user->ID : 0;
        }
        return 0;
    }

    /**
     * Create a new WooCommerce customer from mapped data
     */
    public static function create_customer( $customer_data, $import_id = 0 ) {
        // Email is required - check both 'email' and 'billing_email'
        $email = '';
        if ( !empty($customer_data['email']) ) {
            $email = sanitize_email($customer_data['email']);
        } elseif ( !empty($customer_data['billing_email']) ) {
            $email = sanitize_email($customer_data['billing_email']);
        }
        
        if ( empty($email) ) {
            return 0;
        }
        
        // Validate email
        if ( ! \PrimeLink\Helpers\ValidatorHelper::is_email( $email ) ) {
            return 0;
        }
        
        // Check if user already exists
        $existing_user = get_user_by( 'email', $email );
        if ( $existing_user ) {
            // Update existing user
            $user_id = $existing_user->ID;
        } else {
            // Create new user
            $username = !empty($customer_data['username']) 
                ? sanitize_user($customer_data['username']) 
                : self::generate_username_from_email($email);
            
            // Ensure username is unique
            $username = self::ensure_unique_username($username);
            
            // Validate username
            if ( empty($username) || !validate_username($username) ) {
                return 0;
            }
            
            $password = !empty($customer_data['password']) 
                ? $customer_data['password'] 
                : wp_generate_password(12, false);
            
            $user_id = wp_create_user( $username, $password, $email );
            
            if ( is_wp_error($user_id) ) {
                // Log the error for debugging
                \PrimeLink\Helpers\LoggerHelper::error(
                    'Customer Import Error: ' . $user_id->get_error_message(),
                    array(
                        'email'    => $email,
                        'username' => $username,
                    )
                );
                return 0;
            }
        }
        
        // Update user data
        $user_data = array();
        
        if ( !empty($customer_data['first_name']) ) {
            $user_data['first_name'] = sanitize_text_field($customer_data['first_name']);
        }
        if ( !empty($customer_data['last_name']) ) {
            $user_data['last_name'] = sanitize_text_field($customer_data['last_name']);
        }
        if ( !empty($customer_data['display_name']) ) {
            $user_data['display_name'] = sanitize_text_field($customer_data['display_name']);
        }
        if ( !empty($customer_data['role']) ) {
            $role = sanitize_text_field($customer_data['role']);
            // Validate role exists
            if ( get_role($role) ) {
                $user = get_user_by( 'ID', $user_id );
                if ( $user ) {
                    $user->set_role($role);
                }
            }
        } else {
            // Default to customer role if not set
            $user = get_user_by( 'ID', $user_id );
            if ( $user && empty($user->roles) ) {
                $user->set_role('customer');
            }
        }
        
        if ( !empty($user_data) ) {
            $user_data['ID'] = $user_id;
            wp_update_user($user_data);
        }
        
        // Set registration date if provided
        if ( !empty($customer_data['user_registered']) ) {
            $registered = self::parse_date($customer_data['user_registered']);
            if ( $registered ) {
                wp_update_user(array(
                    'ID' => $user_id,
                    'user_registered' => date('Y-m-d H:i:s', $registered)
                ));
            }
        }
        
        // Billing address
        if ( !empty($customer_data['billing_first_name']) ) {
            update_user_meta( $user_id, 'billing_first_name', sanitize_text_field($customer_data['billing_first_name']) );
        }
        if ( !empty($customer_data['billing_last_name']) ) {
            update_user_meta( $user_id, 'billing_last_name', sanitize_text_field($customer_data['billing_last_name']) );
        }
        if ( !empty($customer_data['billing_company']) ) {
            update_user_meta( $user_id, 'billing_company', sanitize_text_field($customer_data['billing_company']) );
        }
        if ( !empty($customer_data['billing_address_1']) ) {
            update_user_meta( $user_id, 'billing_address_1', sanitize_text_field($customer_data['billing_address_1']) );
        }
        if ( !empty($customer_data['billing_address_2']) ) {
            update_user_meta( $user_id, 'billing_address_2', sanitize_text_field($customer_data['billing_address_2']) );
        }
        if ( !empty($customer_data['billing_city']) ) {
            update_user_meta( $user_id, 'billing_city', sanitize_text_field($customer_data['billing_city']) );
        }
        if ( !empty($customer_data['billing_state']) ) {
            update_user_meta( $user_id, 'billing_state', sanitize_text_field($customer_data['billing_state']) );
        }
        if ( !empty($customer_data['billing_postcode']) ) {
            update_user_meta( $user_id, 'billing_postcode', sanitize_text_field($customer_data['billing_postcode']) );
        }
        if ( !empty($customer_data['billing_country']) ) {
            update_user_meta( $user_id, 'billing_country', sanitize_text_field($customer_data['billing_country']) );
        }
        if ( !empty($customer_data['billing_email']) ) {
            update_user_meta( $user_id, 'billing_email', sanitize_email($customer_data['billing_email']) );
        }
        if ( !empty($customer_data['billing_phone']) ) {
            update_user_meta( $user_id, 'billing_phone', sanitize_text_field($customer_data['billing_phone']) );
        }
        
        // Shipping address
        if ( !empty($customer_data['shipping_first_name']) ) {
            update_user_meta( $user_id, 'shipping_first_name', sanitize_text_field($customer_data['shipping_first_name']) );
        }
        if ( !empty($customer_data['shipping_last_name']) ) {
            update_user_meta( $user_id, 'shipping_last_name', sanitize_text_field($customer_data['shipping_last_name']) );
        }
        if ( !empty($customer_data['shipping_company']) ) {
            update_user_meta( $user_id, 'shipping_company', sanitize_text_field($customer_data['shipping_company']) );
        }
        if ( !empty($customer_data['shipping_address_1']) ) {
            update_user_meta( $user_id, 'shipping_address_1', sanitize_text_field($customer_data['shipping_address_1']) );
        }
        if ( !empty($customer_data['shipping_address_2']) ) {
            update_user_meta( $user_id, 'shipping_address_2', sanitize_text_field($customer_data['shipping_address_2']) );
        }
        if ( !empty($customer_data['shipping_city']) ) {
            update_user_meta( $user_id, 'shipping_city', sanitize_text_field($customer_data['shipping_city']) );
        }
        if ( !empty($customer_data['shipping_state']) ) {
            update_user_meta( $user_id, 'shipping_state', sanitize_text_field($customer_data['shipping_state']) );
        }
        if ( !empty($customer_data['shipping_postcode']) ) {
            update_user_meta( $user_id, 'shipping_postcode', sanitize_text_field($customer_data['shipping_postcode']) );
        }
        if ( !empty($customer_data['shipping_country']) ) {
            update_user_meta( $user_id, 'shipping_country', sanitize_text_field($customer_data['shipping_country']) );
        }
        
        // Custom meta fields
        if ( !empty($customer_data['meta']) && is_array($customer_data['meta']) ) {
            foreach ( $customer_data['meta'] as $key => $value ) {
                update_user_meta( $user_id, sanitize_key($key), $value );
            }
        }
        
        return $user_id;
    }

    /**
     * Update an existing customer
     */
    public static function update_customer( $user_id, $customer_data, $update_fields = array() ) {
        if ( empty($update_fields) || in_array('profile', $update_fields) ) {
            $user_data = array('ID' => $user_id);
            
            if ( !empty($customer_data['first_name']) ) {
                $user_data['first_name'] = sanitize_text_field($customer_data['first_name']);
            }
            if ( !empty($customer_data['last_name']) ) {
                $user_data['last_name'] = sanitize_text_field($customer_data['last_name']);
            }
            if ( !empty($customer_data['display_name']) ) {
                $user_data['display_name'] = sanitize_text_field($customer_data['display_name']);
            }
            if ( !empty($customer_data['email']) ) {
                $user_data['user_email'] = sanitize_email($customer_data['email']);
            }
            
            if ( count($user_data) > 1 ) {
                wp_update_user($user_data);
            }
            
            if ( !empty($customer_data['role']) ) {
                $role = sanitize_text_field($customer_data['role']);
                if ( get_role($role) ) {
                    $user = get_user_by( 'ID', $user_id );
                    if ( $user ) {
                        $user->set_role($role);
                    }
                }
            }
        }
        
        if ( empty($update_fields) || in_array('billing', $update_fields) ) {
            // Update billing fields
            $billing_fields = array(
                'billing_first_name', 'billing_last_name', 'billing_company',
                'billing_address_1', 'billing_address_2', 'billing_city',
                'billing_state', 'billing_postcode', 'billing_country',
                'billing_email', 'billing_phone'
            );
            
            foreach ( $billing_fields as $field ) {
                if ( isset($customer_data[$field]) ) {
                    update_user_meta( $user_id, $field, sanitize_text_field($customer_data[$field]) );
                }
            }
        }
        
        if ( empty($update_fields) || in_array('shipping', $update_fields) ) {
            // Update shipping fields
            $shipping_fields = array(
                'shipping_first_name', 'shipping_last_name', 'shipping_company',
                'shipping_address_1', 'shipping_address_2', 'shipping_city',
                'shipping_state', 'shipping_postcode', 'shipping_country'
            );
            
            foreach ( $shipping_fields as $field ) {
                if ( isset($customer_data[$field]) ) {
                    update_user_meta( $user_id, $field, sanitize_text_field($customer_data[$field]) );
                }
            }
        }
        
        if ( (empty($update_fields) || in_array('custom_fields', $update_fields)) && !empty($customer_data['meta']) && is_array($customer_data['meta']) ) {
            foreach ( $customer_data['meta'] as $key => $value ) {
                update_user_meta( $user_id, sanitize_key($key), $value );
            }
        }
    }

    /**
     * Generate username from email
     */
    private static function generate_username_from_email( $email ) {
        $at_pos = strpos($email, '@');
        if ( $at_pos === false || $at_pos === 0 ) {
            // If no @ or @ is at start, use a sanitized version of the email
            $username = sanitize_user( str_replace(array('@', '.', '+'), '_', $email) );
        } else {
            $username = sanitize_user( substr($email, 0, $at_pos) );
        }
        
        // Ensure username is not empty and has valid length
        if ( empty($username) || strlen($username) < 1 ) {
            $username = 'user_' . wp_generate_password(8, false, false);
        }
        
        // Limit username length (WooCommerce max is 60)
        if ( strlen($username) > 60 ) {
            $username = substr($username, 0, 60);
        }
        
        return self::ensure_unique_username($username);
    }

    /**
     * Ensure username is unique
     */
    private static function ensure_unique_username( $username ) {
        if ( empty($username) ) {
            $username = 'user_' . wp_generate_password(8, false, false);
        }
        
        // Validate username first
        if ( !validate_username($username) ) {
            // If invalid, generate a new one
            $username = 'user_' . wp_generate_password(12, false, false);
        }
        
        $original_username = $username;
        $counter = 1;
        $max_attempts = 1000; // Prevent infinite loop
        
        while ( username_exists($username) && $counter < $max_attempts ) {
            // Try to append counter, but keep total length under 60
            $suffix = '_' . $counter;
            $max_base_length = 60 - strlen($suffix);
            if ( strlen($original_username) > $max_base_length ) {
                $base = substr($original_username, 0, $max_base_length);
            } else {
                $base = $original_username;
            }
            $username = $base . $suffix;
            $counter++;
        }
        
        // If we hit max attempts, generate a random username
        if ( $counter >= $max_attempts || username_exists($username) ) {
            $username = 'user_' . wp_generate_password(12, false, false);
            // Ensure this random one is also unique
            while ( username_exists($username) ) {
                $username = 'user_' . wp_generate_password(12, false, false);
            }
        }
        
        return $username;
    }

    /**
     * Parse date string to timestamp.
     *
     * @param string $date_string Date string.
     * @return int|false Timestamp or false on failure.
     */
    private static function parse_date( $date_string ) {
        return \PrimeLink\Helpers\DateHelper::parse_to_timestamp( $date_string );
    }
}

