<?php
/**
 * SalesPartnerAI Integration
 *
 * @package SPAI_Contact_Form
 */

class SPAI_SalesPartner_Integration extends SPAI_Integration_Base {

    /**
     * Production API URL (hardcoded for customer distribution)
     */
    private const PRODUCTION_API_URL = 'https://api.salespartnerai.com/api/v1/forms/public/contact-form';

    /**
     * API URL
     */
    private $api_url;

    /**
     * Constructor
     * Note: $api_url parameter kept for backward compatibility but ignored
     */
    public function __construct($api_url = '') {
        $this->api_url = self::PRODUCTION_API_URL;
    }
    
    /**
     * Get integration name
     */
    public function get_name() {
        return 'SalesPartnerAI';
    }
    
    /**
     * Get integration description
     */
    public function get_description() {
        return __('Send form submissions to SalesPartnerAI CRM', 'spai-contact-form');
    }
    
    /**
     * Get settings fields
     */
    public function get_settings_fields() {
        return array(
            'company_id' => array(
                'type' => 'text',
                'label' => __('Company ID', 'spai-contact-form'),
                'required' => true
            ),
            'campaign_id' => array(
                'type' => 'text',
                'label' => __('Campaign ID', 'spai-contact-form'),
                'required' => false
            ),
            'tags' => array(
                'type' => 'text',
                'label' => __('Tags', 'spai-contact-form'),
                'required' => false,
                'description' => __('Comma-separated tags', 'spai-contact-form')
            )
        );
    }
    
    /**
     * Get field configuration
     */
    public function get_fields_config() {
        return array(
            'firstName' => array(
                'type' => 'text',
                'label' => __('First Name', 'spai-contact-form'),
                'required' => true
            ),
            'lastName' => array(
                'type' => 'text',
                'label' => __('Last Name', 'spai-contact-form'),
                'required' => true
            ),
            'email' => array(
                'type' => 'email',
                'label' => __('Email', 'spai-contact-form'),
                'required' => true
            ),
            'phone' => array(
                'type' => 'phone',
                'label' => __('Phone', 'spai-contact-form'),
                'required' => false
            )
        );
    }
    
    /**
     * Process submission
     */
    public function process_submission($data, $mapping) {
        // Map fields
        $mapped_data = $this->map_fields($data, $mapping);
        
        // Send to SalesPartnerAI
        return $this->send_contact($mapped_data, array(), $mapping);
    }
    
    /**
     * Send contact to SalesPartnerAI
     */
    public function send_contact($form_data, $file_data, $settings) {
        // Get integration settings
        $integration_settings = get_option('spai_contact_form_salespartner_settings', array());
        
        // Get browser data
        $browser_data = $this->get_browser_data();
        
        // Build payload matching the expected format
        $payload = array(
            'companyId' => $integration_settings['company_id'] ?? '',
            'firstName' => $form_data['first_name'] ?? '',
            'lastName' => $form_data['last_name'] ?? '',
            'email' => $form_data['email'] ?? '',
            'phone' => $form_data['phone'] ?? '',
            'timezone' => $this->get_user_timezone(),
            'address' => array(
                'street' => $form_data['street'] ?? '',
                'city' => $form_data['city'] ?? '',
                'state' => $form_data['state'] ?? '',
                'zipCode' => $form_data['zip'] ?? '',
                'country' => $form_data['country'] ?? 'USA'
            ),
            'engagement' => array(
                'preferredContactMethod' => 'email',
                'preferredTimes' => array('morning', 'afternoon')
            ),
            'metadata' => array(
                'source' => 'Website Form',
                'campaignId' => $integration_settings['campaign_id'] ?? '',
                'tags' => !empty($integration_settings['tags']) ? explode(',', $integration_settings['tags']) : array('Website', 'Contact Form'),
                'marketing_data' => $form_data['marketing_data'] ?? '',
                'browserData' => array_merge($browser_data, array(
                    'language' => isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5) : 'en-US',
                    'screenResolution' => '1920x1080' // This would need JavaScript to capture properly
                ))
            )
        );
        
        // Check for SMS consent field and handle opt-out
        $sms_consent_field = null;
        foreach ($form_data as $key => $value) {
            if (strpos($key, 'sms_consent') !== false || strpos($key, 'consent_sms') !== false) {
                $sms_consent_field = $key;
                break;
            }
        }
        
        if ($sms_consent_field !== null && empty($form_data[$sms_consent_field])) {
            // User did NOT check the consent box - they are opting out
            $payload['engagement']['optOut'] = array(
                'isOptedOut' => true,
                'reason' => 'Unchecked consent box on form submission',
                'timestamp' => gmdate('c')
            );
        }
        
        // Add custom form fields to metadata if present
        $onlineForm = array(
            'submittedAt' => gmdate('c')
        );
        
        if (!empty($form_data['message'])) {
            $onlineForm['message'] = $form_data['message'];
        }
        
        // Add all additional form fields to onlineForm
        $standardFields = array('first_name', 'last_name', 'email', 'phone', 'street', 'city', 'state', 'zip', 'country', 'message');
        foreach ($form_data as $key => $value) {
            // Skip standard fields that are already mapped to main payload
            if (in_array($key, $standardFields)) {
                continue;
            }
            
            // Skip address fields that are already mapped
            if (strpos($key, 'address.') === 0) {
                continue;
            }
            
            // Add all other fields including multichoice fields
            $onlineForm[$key] = $value;
        }
        
        $payload['metadata']['onlineForm'] = $onlineForm;
        
        // Add sms consent to online form data
        if ($sms_consent_field !== null) {
            $payload['metadata']['onlineForm']['smsConsent'] = !empty($form_data[$sms_consent_field]);
        }
        
        // Add Monday.com data if available
        if (!empty($form_data['monday_item_id'])) {
            $payload['integrations'] = array(
                'monday' => array(
                    'itemId' => $form_data['monday_item_id'],
                    'boardId' => $form_data['monday_board_id'] ?? '',
                    'createdAt' => gmdate('c')
                )
            );
        }
        
        // Send request
        $response = wp_remote_post($this->api_url, array(
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($payload),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            $this->log('API request failed', 'error', $response->get_error_message());
            return array(
                'success' => false,
                'message' => __('Failed to send to SalesPartnerAI', 'spai-contact-form'),
                'error' => $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code === 200 || $status_code === 201) {
            return array(
                'success' => true,
                'contact_id' => $data['id'] ?? null,
                'message' => __('Contact sent to SalesPartnerAI successfully', 'spai-contact-form')
            );
        }
        
        return array(
            'success' => false,
            'message' => __('Failed to send to SalesPartnerAI', 'spai-contact-form'),
            'error' => $data['message'] ?? 'HTTP ' . $status_code
        );
    }
    
    /**
     * Test connection
     */
    public function test_connection() {
        // Send a test payload
        $test_payload = array(
            'test' => true,
            'source' => 'spai-contact-form'
        );
        
        $response = wp_remote_get($this->api_url, array(
            'timeout' => 10
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Failed to connect to SalesPartnerAI', 'spai-contact-form')
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200 || $status_code === 404) {
            // 404 is ok as the endpoint might not accept GET
            return array(
                'success' => true,
                'message' => __('Connection to SalesPartnerAI successful', 'spai-contact-form')
            );
        }
        
        return array(
            'success' => false,
            'message' => sprintf(__('Connection failed (HTTP %d)', 'spai-contact-form'), $status_code)
        );
    }
    
    /**
     * Get user timezone
     */
    private function get_user_timezone() {
        // Get WordPress timezone
        $timezone_string = get_option('timezone_string');
        
        if ($timezone_string) {
            return $timezone_string;
        }
        
        // Try to determine timezone from offset
        $offset = get_option('gmt_offset');
        if ($offset !== false) {
            // Common timezone mappings
            $timezone_map = array(
                '-5' => 'America/New_York',
                '-6' => 'America/Chicago',
                '-7' => 'America/Denver',
                '-8' => 'America/Los_Angeles',
                '0' => 'Europe/London',
                '1' => 'Europe/Paris',
                '2' => 'Europe/Berlin'
            );
            
            if (isset($timezone_map[$offset])) {
                return $timezone_map[$offset];
            }
        }
        
        return 'America/Chicago'; // Default to Chicago
    }
    
    /**
     * Get browser data
     */
    private function get_browser_data() {
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        
        return array(
            'ipAddress' => $this->get_client_ip(),
            'userAgent' => $user_agent,
            'browser' => $this->get_browser_from_user_agent($user_agent),
            'os' => $this->get_os_from_user_agent($user_agent),
            'deviceType' => wp_is_mobile() ? 'mobile' : 'desktop',
            'referrer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
            'landingPage' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''
        );
    }
    
    /**
     * Get client IP
     */
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    
                    if (filter_var($ip, FILTER_VALIDATE_IP,
                        FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
    }
    
    /**
     * Parse browser from user agent
     */
    private function get_browser_from_user_agent($user_agent) {
        if (preg_match('/MSIE/i', $user_agent)) {
            return 'Internet Explorer';
        } elseif (preg_match('/Firefox/i', $user_agent)) {
            return 'Firefox';
        } elseif (preg_match('/Chrome/i', $user_agent)) {
            return 'Chrome';
        } elseif (preg_match('/Safari/i', $user_agent)) {
            return 'Safari';
        } elseif (preg_match('/Opera/i', $user_agent)) {
            return 'Opera';
        }
        
        return 'Unknown';
    }
    
    /**
     * Parse OS from user agent
     */
    private function get_os_from_user_agent($user_agent) {
        if (preg_match('/Windows/i', $user_agent)) {
            return 'Windows';
        } elseif (preg_match('/Mac/i', $user_agent)) {
            return 'macOS';
        } elseif (preg_match('/Linux/i', $user_agent)) {
            return 'Linux';
        } elseif (preg_match('/Android/i', $user_agent)) {
            return 'Android';
        } elseif (preg_match('/iOS|iPhone|iPad/i', $user_agent)) {
            return 'iOS';
        }
        
        return 'Unknown';
    }
}
