<?php
/**
 * Google Chat Integration
 *
 * @package SPAI_Contact_Form
 */

// Load the base integration class
require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/class-spai-integration-base.php';

class SPAI_GChat_Integration extends SPAI_Integration_Base {
    
    /**
     * Webhook URL
     */
    private $webhook_url;
    
    /**
     * Constructor
     */
    public function __construct($webhook_url = '') {
        $this->webhook_url = $webhook_url;
    }
    
    /**
     * Get integration name
     */
    public function get_name() {
        return 'Google Chat';
    }
    
    /**
     * Get integration description
     */
    public function get_description() {
        return __('Send notifications to Google Chat when forms are submitted', 'spai-contact-form');
    }
    
    /**
     * Get settings fields for this integration
     */
    public function get_settings_fields() {
        return array(
            'enabled' => array(
                'type' => 'checkbox',
                'label' => __('Enable Google Chat Notifications', 'spai-contact-form'),
                'description' => __('Send form submissions to Google Chat', 'spai-contact-form'),
                'default' => false
            ),
            'webhook_url' => array(
                'type' => 'text',
                'label' => __('Webhook URL', 'spai-contact-form'),
                'description' => __('Your Google Chat webhook URL', 'spai-contact-form'),
                'required' => true,
                'placeholder' => 'https://chat.googleapis.com/v1/spaces/...'
            )
        );
    }
    
    /**
     * Get field mapping configuration
     */
    public function get_fields_config() {
        // Google Chat doesn't need field mapping - it sends all data
        return array();
    }
    
    /**
     * Process submission
     */
    public function process_submission($data, $mapping) {
        if (empty($this->webhook_url)) {
            $this->log('Missing webhook URL', 'error');
            return array(
                'success' => false,
                'error' => 'Google Chat webhook URL is not configured'
            );
        }
        
        // Extract Monday.com data if present
        $monday_item_id = isset($data['monday_item_id']) ? $data['monday_item_id'] : '';
        $monday_board_id = isset($data['monday_board_id']) ? $data['monday_board_id'] : '';
        
        // Format and send the message
        $message = $this->format_message($data, $monday_item_id, $monday_board_id);
        
        $args = array(
            'method' => 'POST',
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode($message),
            'timeout' => 15,
            'httpversion' => '1.1'
        );
        
        $response = wp_remote_post($this->webhook_url, $args);
        
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            $this->log('HTTP request failed: ' . $error_message, 'error');
            return array(
                'success' => false,
                'error' => 'Failed to send notification: ' . $error_message
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        if ($response_code >= 300) {
            $error_body = wp_remote_retrieve_body($response);
            $this->log('API returned error. Code: ' . $response_code . ' Body: ' . $error_body, 'error');
            return array(
                'success' => false,
                'error' => 'Google Chat API error (Code: ' . $response_code . ')'
            );
        }
        
        $this->log('Notification sent successfully', 'info');
        return array(
            'success' => true,
            'notification_id' => uniqid('gchat_', true)
        );
    }
    
    /**
     * Test connection
     */
    public function test_connection() {
        if (empty($this->webhook_url)) {
            return array(
                'success' => false,
                'message' => __('Please enter a webhook URL', 'spai-contact-form')
            );
        }
        
        // Send a test message
        $test_message = array(
            'text' => 'Test connection from SPAI Contact Form plugin'
        );
        
        $args = array(
            'method' => 'POST',
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode($test_message),
            'timeout' => 10,
            'httpversion' => '1.1'
        );
        
        $response = wp_remote_post($this->webhook_url, $args);
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => sprintf(__('Connection failed: %s', 'spai-contact-form'), $response->get_error_message())
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        if ($response_code >= 200 && $response_code < 300) {
            return array(
                'success' => true,
                'message' => __('Connection successful! Test message sent.', 'spai-contact-form')
            );
        } else {
            return array(
                'success' => false,
                'message' => sprintf(__('Connection failed with code: %d', 'spai-contact-form'), $response_code)
            );
        }
    }
    
    /**
     * Format the message for Google Chat
     */
    private function format_message($data, $monday_item_id = '', $monday_board_id = '') {
        // Build the form data text
        $form_fields = array();
        
        // Common fields to display
        $display_fields = array(
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'email' => 'Email',
            'phone' => 'Phone',
            'company' => 'Company',
            'message' => 'Message'
        );
        
        foreach ($display_fields as $field_key => $field_label) {
            if (isset($data[$field_key]) && !empty($data[$field_key])) {
                $form_fields[] = array(
                    'keyValue' => array(
                        'topLabel' => $field_label,
                        'content' => $data[$field_key]
                    )
                );
            }
        }
        
        // Add any other non-system fields
        $skip_fields = array_merge(
            array_keys($display_fields),
            array('monday_item_id', 'monday_board_id', 'form_id', 'submission_id')
        );
        
        foreach ($data as $key => $value) {
            // Less restrictive filtering - only skip if truly empty/null or in skip list
            if (!in_array($key, $skip_fields) && $value !== null && $value !== '') {
                $label = str_replace('_', ' ', ucfirst($key));
                $form_fields[] = array(
                    'keyValue' => array(
                        'topLabel' => $label,
                        'content' => is_array($value) ? implode(', ', $value) : $value
                    )
                );
            }
        }
        
        // Build the full name for the header
        $full_name = '';
        if (isset($data['first_name'])) {
            $full_name = $data['first_name'];
        }
        if (isset($data['last_name'])) {
            $full_name .= ' ' . $data['last_name'];
        }
        $full_name = trim($full_name);
        
        // Create the card structure
        $message = array(
            'cards' => array(
                array(
                    'header' => array(
                        'title' => 'New Form Submission',
                        'subtitle' => !empty($full_name) ? $full_name : 'Contact Form'
                    ),
                    'sections' => array(
                        array(
                            'widgets' => $form_fields
                        )
                    )
                )
            )
        );
        
        // Add Monday.com button if we have the item ID
        if (!empty($monday_item_id) && !empty($monday_board_id)) {
            $monday_settings = get_option('spai_contact_form_monday_settings', array());
            $monday_domain = isset($monday_settings['domain']) ? $monday_settings['domain'] : '';
            
            if (!empty($monday_domain)) {
                $monday_url = "https://{$monday_domain}.monday.com/boards/{$monday_board_id}/pulses/{$monday_item_id}";
                
                $message['cards'][0]['sections'][] = array(
                    'widgets' => array(
                        array(
                            'buttons' => array(
                                array(
                                    'textButton' => array(
                                        'text' => 'VIEW IN MONDAY.COM',
                                        'onClick' => array(
                                            'openLink' => array(
                                                'url' => $monday_url
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                );
            }
        }
        
        return $message;
    }
}
