<?php
/**
 * Admin integrations template
 *
 * @package SPAI_Contact_Form
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get saved settings
$monday_settings = get_option('spai_contact_form_monday_settings', array());
$salespartner_settings = get_option('spai_contact_form_salespartner_settings', array());
$chat_widget_settings = get_option('spai_contact_form_chat_widget_settings', array('enabled' => true));
$gchat_settings = get_option('spai_contact_form_gchat_settings', array());
?>

<div class="wrap spai-admin-wrapper">
    <div class="spai-admin-header">
        <h1><?php _e('Integrations', 'spai-contact-form'); ?></h1>
    </div>

    <div class="spai-admin-content">
        <!-- SalesPartner Integration -->
        <div class="spai-integration-card">
            <div class="spai-integration-header">
                <h2><?php _e('SalesPartner Integration', 'spai-contact-form'); ?></h2>
                <div class="spai-integration-toggle">
                    <label>
                        <input type="checkbox" id="salespartner_enabled" <?php checked(!empty($salespartner_settings['enabled'])); ?>>
                        <?php _e('Enable', 'spai-contact-form'); ?>
                    </label>
                </div>
            </div>

            <div id="salespartner-settings">
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="salespartner_company_id"><?php _e('Company ID', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="salespartner_company_id" name="salespartner_company_id"
                                   value="<?php echo esc_attr($salespartner_settings['company_id'] ?? ''); ?>"
                                   class="regular-text">
                            <p class="description">
                                <?php _e('Your SalesPartner company ID. Find this in your SalesPartner dashboard under Settings.', 'spai-contact-form'); ?>
                            </p>
                        </td>
                    </tr>
                </table>

                <button type="button" class="button test-integration" data-integration="salespartner">
                    <?php _e('Test Connection', 'spai-contact-form'); ?>
                </button>

                <!-- Features Section -->
                <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #ddd;">
                    <h4 style="margin: 0 0 10px 0;"><?php _e('Features', 'spai-contact-form'); ?></h4>

                    <p style="margin: 8px 0; color: #50575e;">
                        <span class="dashicons dashicons-yes-alt" style="color: #00a32a; font-size: 16px; vertical-align: middle;"></span>
                        <?php _e('Form Submissions', 'spai-contact-form'); ?>
                        <span style="color: #888; font-size: 12px; margin-left: 5px;"><?php _e('(included)', 'spai-contact-form'); ?></span>
                    </p>

                    <p style="margin: 8px 0;">
                        <label style="display: inline-flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="chat_widget_enabled" <?php checked(!empty($chat_widget_settings['enabled'])); ?>>
                            <?php _e('Chat Widget', 'spai-contact-form'); ?>
                        </label>
                        <a href="https://app.salespartnerai.com/company/channels/chatwidget" target="_blank" rel="noopener" style="margin-left: 10px; text-decoration: none;">
                            <?php _e('Configure', 'spai-contact-form'); ?>
                            <span class="dashicons dashicons-external" style="font-size: 14px; vertical-align: middle;"></span>
                        </a>
                    </p>
                </div>
            </div>
        </div>

        <!-- Monday.com Integration -->
        <div class="spai-integration-card">
            <div class="spai-integration-header">
                <h2><?php _e('Monday.com Integration', 'spai-contact-form'); ?></h2>
                <div class="spai-integration-toggle">
                    <label>
                        <input type="checkbox" id="monday_enabled" <?php checked(!empty($monday_settings['enabled'])); ?>>
                        <?php _e('Enable', 'spai-contact-form'); ?>
                    </label>
                </div>
            </div>

            <div id="monday-settings">
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="monday_api_key"><?php _e('API Key', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <input type="password" id="monday_api_key" name="monday_api_key"
                                   value="<?php echo esc_attr($monday_settings['api_key'] ?? ''); ?>"
                                   class="regular-text">
                            <p class="description">
                                <?php _e('Your Monday.com API v2 key', 'spai-contact-form'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label><?php _e('Board Selection', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <fieldset>
                                <label>
                                    <input type="radio" name="monday_board_mode" value="browse" <?php checked(($monday_settings['board_mode'] ?? 'browse') === 'browse'); ?>>
                                    <?php _e('Browse Boards', 'spai-contact-form'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="radio" name="monday_board_mode" value="manual" <?php checked(($monday_settings['board_mode'] ?? 'browse') === 'manual'); ?>>
                                    <?php _e('Enter Board ID Manually', 'spai-contact-form'); ?>
                                </label>
                            </fieldset>
                        </td>
                    </tr>
                    <tr class="monday-board-browse" <?php echo (($monday_settings['board_mode'] ?? 'browse') === 'manual') ? 'style="display:none;"' : ''; ?>>
                        <th scope="row">
                            <label for="monday_board_id"><?php _e('Select Board', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <select id="monday_board_id" name="monday_board_id">
                                <option value=""><?php _e('Select a board', 'spai-contact-form'); ?></option>
                                <?php if (!empty($monday_settings['board_id']) && ($monday_settings['board_mode'] ?? 'browse') === 'browse'): ?>
                                    <option value="<?php echo esc_attr($monday_settings['board_id']); ?>" selected>
                                        <?php echo esc_html($monday_settings['board_name'] ?? 'Board ' . $monday_settings['board_id']); ?>
                                    </option>
                                <?php endif; ?>
                            </select>
                            <button type="button" id="get-monday-boards" class="button">
                                <?php _e('Get Boards', 'spai-contact-form'); ?>
                            </button>
                        </td>
                    </tr>
                    <tr class="monday-board-manual" <?php echo (($monday_settings['board_mode'] ?? 'browse') !== 'manual') ? 'style="display:none;"' : ''; ?>>
                        <th scope="row">
                            <label for="monday_board_id_manual"><?php _e('Board ID', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="monday_board_id_manual" name="monday_board_id_manual"
                                   value="<?php echo esc_attr((($monday_settings['board_mode'] ?? 'browse') === 'manual') ? ($monday_settings['board_id'] ?? '') : ''); ?>"
                                   class="regular-text">
                            <p class="description">
                                <?php _e('Enter the Monday.com board ID directly. You can find this in the board URL.', 'spai-contact-form'); ?>
                            </p>
                        </td>
                    </tr>
                </table>

                <button type="button" class="button test-integration" data-integration="monday">
                    <?php _e('Test Connection', 'spai-contact-form'); ?>
                </button>
            </div>
        </div>

        <!-- Google Chat Integration -->
        <div class="spai-integration-card">
            <div class="spai-integration-header">
                <h2><?php _e('Google Chat Notifications', 'spai-contact-form'); ?></h2>
                <div class="spai-integration-toggle">
                    <label>
                        <input type="checkbox" id="gchat_enabled" <?php checked(!empty($gchat_settings['enabled'])); ?>>
                        <?php _e('Enable', 'spai-contact-form'); ?>
                    </label>
                </div>
            </div>
            
            <div id="gchat-settings">
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="gchat_webhook_url"><?php _e('Webhook URL', 'spai-contact-form'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="gchat_webhook_url" name="gchat_webhook_url" 
                                   value="<?php echo esc_attr($gchat_settings['webhook_url'] ?? ''); ?>" 
                                   class="regular-text">
                            <p class="description">
                                <?php _e('Your Google Chat webhook URL. You can get this from your Google Chat space settings.', 'spai-contact-form'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <button type="button" class="button test-integration" data-integration="gchat">
                    <?php _e('Test Connection', 'spai-contact-form'); ?>
                </button>
            </div>
        </div>
        
        <p class="submit">
            <button type="button" id="save-integrations" class="button button-primary">
                <?php _e('Save Settings', 'spai-contact-form'); ?>
            </button>
        </p>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Handle board mode switching
    $('input[name="monday_board_mode"]').on('change', function() {
        var mode = $(this).val();
        if (mode === 'browse') {
            $('.monday-board-browse').show();
            $('.monday-board-manual').hide();
        } else {
            $('.monday-board-browse').hide();
            $('.monday-board-manual').show();
        }
    });
    
    // Test integration
    $('.test-integration').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var integration = $button.data('integration');
        var settings = {};
        
        // Collect settings based on integration type
        if (integration === 'monday') {
            settings = {
                api_key: $('#monday_api_key').val()
            };
        } else if (integration === 'salespartner') {
            settings = {
                company_id: $('#salespartner_company_id').val()
            };
        } else if (integration === 'gchat') {
            settings = {
                webhook_url: $('#gchat_webhook_url').val()
            };
        }
        
        $button.prop('disabled', true).text('Testing...');
        
        $.post(ajaxurl, {
            action: 'spai_test_integration',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            integration: integration,
            settings: settings
        }, function(response) {
            if (response.success) {
                alert(response.data.message || 'Connection successful!');
            } else {
                alert(response.data || 'Connection failed!');
            }
            $button.prop('disabled', false).text('Test Connection');
        });
    });
    
    // Save integrations
    $('#save-integrations').on('click', function() {
        var boardMode = $('input[name="monday_board_mode"]:checked').val();
        var boardId = '';
        var boardName = '';
        
        if (boardMode === 'browse') {
            boardId = $('#monday_board_id').val();
            boardName = $('#monday_board_id option:selected').text();
        } else {
            boardId = $('#monday_board_id_manual').val();
            boardName = 'Board ' + boardId;
        }
        
        var mondaySettings = {
            enabled: $('#monday_enabled').is(':checked'),
            api_key: $('#monday_api_key').val(),
            board_mode: boardMode,
            board_id: boardId,
            board_name: boardName
        };
        
        var salespartnerSettings = {
            enabled: $('#salespartner_enabled').is(':checked'),
            company_id: $('#salespartner_company_id').val()
        };

        var chatWidgetSettings = {
            enabled: $('#chat_widget_enabled').is(':checked')
        };

        var gchatSettings = {
            enabled: $('#gchat_enabled').is(':checked'),
            webhook_url: $('#gchat_webhook_url').val()
        };

        // Save settings via AJAX
        $.post(ajaxurl, {
            action: 'spai_save_integrations',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            monday_settings: mondaySettings,
            salespartner_settings: salespartnerSettings,
            chat_widget_settings: chatWidgetSettings,
            gchat_settings: gchatSettings
        }, function(response) {
            if (response.success) {
                alert('Settings saved successfully!');
            } else {
                alert('Failed to save settings');
            }
        });
    });
});
</script>
