<?php
/**
 * Divine Forms Integration
 * 
 * Handles automatic agreement creation from Divine Forms submissions
 * 
 * @package Divine_Agreement_System
 * @author Aditya Singh
 */

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

class Divine_Form_Integration {
    
    /**
     * Initialize integration
     */
    public static function init() {
        // Hook into Divine Forms submission
        add_action('divine_forms_after_submit', array(__CLASS__, 'handle_form_submission'), 10, 3);
        
        // Register settings page
        add_action('admin_menu', array(__CLASS__, 'register_settings_page'));
        
        // Register AJAX handlers
        add_action('wp_ajax_divine_get_form_fields', array(__CLASS__, 'ajax_get_form_fields'));
        add_action('wp_ajax_divine_get_template_placeholders', array(__CLASS__, 'ajax_get_template_placeholders'));
        add_action('wp_ajax_divine_save_form_integration', array(__CLASS__, 'ajax_save_integration'));
        add_action('wp_ajax_divine_delete_form_integration', array(__CLASS__, 'ajax_delete_integration'));
        add_action('wp_ajax_divine_test_form_mapping', array(__CLASS__, 'ajax_test_mapping'));
        add_action('wp_ajax_divine_get_integration_config', array(__CLASS__, 'ajax_get_integration_config'));
        
        // Enqueue admin assets
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_admin_assets'));
    }
    
    /**
     * Handle form submission - AUTOMATION ENTRY POINT
     */
    public static function handle_form_submission($entry_id, $store_data, $form) {
        // FIXED: $form is a stdClass object, not an array
        $form_id = isset($form->id) ? intval($form->id) : 0;
        
        if (!$form_id) {
            return;
        }
        
        // Check if this form has integration configured
        $config = get_option('divine_form_integration_' . $form_id, array());
        
        if (empty($config) || !isset($config['enabled']) || !$config['enabled']) {
            return;
        }
        
        // Validate configuration
        if (empty($config['template_id']) || empty($config['field_mapping'])) {
            return;
        }
        
        // Get template
        $template = get_post($config['template_id']);
        if (!$template || $template->post_type !== 'divine_template') {
            return;
        }
        
        // Get email field
        $email_field = isset($config['email_field']) ? sanitize_text_field($config['email_field']) : '';
        $collaborator_email = '';
        
        if ($email_field && isset($store_data[$email_field])) {
            $collaborator_email = sanitize_email($store_data[$email_field]);
        }
        
        if (!$collaborator_email) {
            return;
        }
        
        // Prepare agreement data
        $agreement_data = self::prepare_agreement_data($template, $store_data, $config, $form);
        
        // Create agreement (REUSE EXISTING FUNCTION)
        $agreement_id = self::create_agreement_from_template($agreement_data);
        
        if (!$agreement_id) {
            return;
        }
        
        // Send email if enabled (REUSE EXISTING FUNCTION)
        if (isset($config['send_email']) && $config['send_email']) {
            Divine_Email::divine_send_agreement_email($agreement_id);
        }
        
        // Log the automation
        update_post_meta($agreement_id, '_divine_automation_source', 'divine_forms');
        update_post_meta($agreement_id, '_divine_automation_form_id', $form_id);
        update_post_meta($agreement_id, '_divine_automation_entry_id', $entry_id);
        update_post_meta($agreement_id, '_divine_automation_date', current_time('mysql'));
        
        do_action('divine_agreement_auto_created', $agreement_id, $form_id, $entry_id, $store_data);
    }
    
    /**
     * Prepare agreement data from form submission
     */
    private static function prepare_agreement_data($template, $store_data, $config, $form) {
        $template_content = $template->post_content;
        $field_mapping = $config['field_mapping'];
        
        // Replace placeholders with form data
        $agreement_content = $template_content;
        
        foreach ($field_mapping as $placeholder => $form_field) {
            $value = isset($store_data[$form_field]) ? $store_data[$form_field] : '';
            // Handle array values (checkboxes, etc)
            if (is_array($value)) {
                $value = implode(', ', $value);
            }

            // Sanitize value
            $value = wp_kses_post($value);

            // FIXED: Replace both [PLACEHOLDER] and {{placeholder}} formats
            $square_pattern = '[' . strtoupper($placeholder) . ']';
            $curly_pattern = '{{' . $placeholder . '}}';

            $agreement_content = str_replace($square_pattern, $value, $agreement_content);
            $agreement_content = str_replace($curly_pattern, $value, $agreement_content);
        }
        
        // Get collaborator details
        $collaborator_name = '';
        $collaborator_email = '';
        $collaborator_address = '';
        $compensation = '';
        
        // Extract from mapped fields
        foreach ($field_mapping as $placeholder => $form_field) {
            $value = isset($store_data[$form_field]) ? $store_data[$form_field] : '';
            
            if (is_array($value)) {
                $value = implode(', ', $value);
            }
            
            if ($placeholder === 'collaborator_name' || $placeholder === 'name') {
                $collaborator_name = sanitize_text_field($value);
            } elseif ($placeholder === 'collaborator_email' || $placeholder === 'email') {
                $collaborator_email = sanitize_email($value);
            } elseif ($placeholder === 'address' || $placeholder === 'collaborator_address') {
                $collaborator_address = sanitize_textarea_field($value);
            } elseif ($placeholder === 'compensation' || $placeholder === 'compensation_details') {
                $compensation = sanitize_text_field($value);
            }
        }
        
        // Fallback to email field from config
        if (!$collaborator_email && isset($config['email_field'])) {
            $email_field = $config['email_field'];
            if (isset($store_data[$email_field])) {
                $collaborator_email = sanitize_email($store_data[$email_field]);
            }
        }

        $agreement_title = sprintf(
            '%s - %s - %s',
            $template->post_title,
            $collaborator_name ? $collaborator_name : 'Collaborator',
            current_time('mysql')
        );
        
        return array(
            'title' => $agreement_title,
            'content' => $agreement_content,
            'template_id' => $template->ID,
            'collaborator_name' => $collaborator_name,
            'collaborator_email' => $collaborator_email,
            'collaborator_address' => $collaborator_address,
            'compensation' => $compensation,
        );
    }
    
    /**
     * Create agreement from template (REUSES EXISTING LOGIC)
     */
    private static function create_agreement_from_template($data) {
        // Create agreement post
        $agreement_id = wp_insert_post(array(
            'post_type' => 'divine_agreement',
            'post_title' => sanitize_text_field($data['title']),
            'post_content' => wp_kses_post($data['content']),
            'post_status' => 'publish', // Auto-publish
            'post_author' => 1,
        ));
        
        if (is_wp_error($agreement_id)) {
            return false;
        }
        
        // Save meta data
        update_post_meta($agreement_id, '_divine_template_id', intval($data['template_id']));
        update_post_meta($agreement_id, '_divine_collaborator_name', sanitize_text_field($data['collaborator_name']));
        update_post_meta($agreement_id, '_divine_collaborator_email', sanitize_email($data['collaborator_email']));
        update_post_meta($agreement_id, '_divine_collaborator_address', sanitize_textarea_field($data['collaborator_address']));
        update_post_meta($agreement_id, '_divine_compensation', sanitize_textarea_field($data['compensation']));
        
        // Generate token (REUSE EXISTING FUNCTION)
        $token = Divine_Token::divine_generate_token($agreement_id);
        update_post_meta($agreement_id, '_divine_token', $token);
        
        // Set initial status
        update_post_meta($agreement_id, '_divine_status', 'pending');
        
        return $agreement_id;
    }
    
    /**
     * Register settings page
     */
    public static function register_settings_page() {
        add_submenu_page(
            'edit.php?post_type=divine_agreement',
            __('Form Integration', 'divine-agreement-system'),
            __('Form Integration', 'divine-agreement-system'),
            'manage_options',
            'divine-form-integration',
            array(__CLASS__, 'render_settings_page')
        );
    }
    
    /**
     * Render settings page
     */
    public static function render_settings_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'divine-agreement-system'));
        }
        
        // Get all Divine Forms
        $forms = self::get_divine_forms();
        
        // Get all templates
        $templates = get_posts(array(
            'post_type' => 'divine_template',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        // Get existing integrations
        $integrations = self::get_all_integrations($forms);
        
        include dirname(__FILE__) . '/views/integration-settings.php';
    }
    
    /**
     * Get all Divine Forms
     */
    private static function get_divine_forms() {
        global $wpdb;
        
        $forms = wp_cache_get('divine_forms', 'divine_agreement_system');

        if (false !== $forms) {
            return $forms;
        }

        $forms = array();
        
        // Query wp_divine_forms table
        $table_name = sanitize_key($wpdb->prefix) . 'divine_forms';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom plugin table lookup cached via wp_cache_*.
        $table_exists = $wpdb->get_var(
            $wpdb->prepare('SHOW TABLES LIKE %s', $table_name)
        );

        if ($table_exists === $table_name) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom plugin table lookup cached via wp_cache_*.
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Custom table name is derived from the sanitized WordPress table prefix and checked for existence above.
                    'SELECT id, title AS form_title, fields AS form_fields FROM ' . $table_name . ' WHERE %d = %d ORDER BY title ASC',
                    1,
                    1
                )
            );
            
            foreach ($results as $row) {
                $forms[] = array(
                    'id' => $row->id,
                    'title' => $row->form_title,
                    'fields' => json_decode($row->form_fields, true)
                );
            }
        }

        wp_cache_set('divine_forms', $forms, 'divine_agreement_system', MINUTE_IN_SECONDS);

        return $forms;
    }
    
    /**
     * Get all integrations
     */
    private static function get_all_integrations($forms = array()) {
        $integrations = array();

        foreach ($forms as $form) {
            if (!isset($form['id'])) {
                continue;
            }

            $form_id = absint($form['id']);
            $config = get_option('divine_form_integration_' . $form_id, array());

            if (!empty($config) && is_array($config)) {
                $integrations[$form_id] = $config;
            }
        }
        
        return $integrations;
    }
    
    /**
     * AJAX: Get form fields
     */
    public static function ajax_get_form_fields() {
        check_ajax_referer('divine_integration_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
        
        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        
        if (!$form_id) {
            wp_send_json_error(array('message' => esc_html__('Invalid form ID', 'divine-agreement-system')));
        }
        
        global $wpdb;
        $table_name = sanitize_key($wpdb->prefix) . 'divine_forms';
        $cache_key = 'divine_form_fields_' . $form_id;
        $form = wp_cache_get($cache_key, 'divine_agreement_system');

        if (false === $form) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom plugin table lookup cached via wp_cache_*.
            $form = $wpdb->get_row(
                $wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Custom table name is derived from the sanitized WordPress table prefix.
                    'SELECT fields AS form_fields FROM ' . $table_name . ' WHERE id = %d',
                    $form_id
                )
            );
            wp_cache_set($cache_key, $form, 'divine_agreement_system', MINUTE_IN_SECONDS);
        }
        
        if (!$form) {
            wp_send_json_error(array('message' => esc_html__('Form not found', 'divine-agreement-system')));
        }
        
        $fields = json_decode($form->form_fields, true);
        
        if (!is_array($fields)) {
            wp_send_json_error(array('message' => esc_html__('Invalid form fields', 'divine-agreement-system')));
        }
        
        // Format fields for dropdown
        $formatted_fields = array();
        foreach ($fields as $field) {
            if (isset($field['id']) && isset($field['label'])) {
                $formatted_fields[] = array(
                    'id' => $field['id'],
                    'label' => $field['label'],
                    'type' => isset($field['type']) ? $field['type'] : 'text'
                );
            }
        }
        
        wp_send_json_success(array('fields' => $formatted_fields));
    }
    
    /**
     * AJAX: Get template placeholders
     */
    public static function ajax_get_template_placeholders() {
    check_ajax_referer('divine_integration_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
    
    $template_id = isset($_POST['template_id']) ? absint(wp_unslash($_POST['template_id'])) : 0;
    
    if (!$template_id) {
        wp_send_json_error(array('message' => esc_html__('Invalid template ID', 'divine-agreement-system')));
    }
    
    $template = get_post($template_id);
    
    if (!$template || $template->post_type !== 'divine_template') {
        wp_send_json_error(array('message' => esc_html__('Template not found', 'divine-agreement-system')));
    }
    
    // Extract placeholders from template content
    $content = $template->post_content;
    
    // FIXED: Support both [PLACEHOLDER] and {{placeholder}} formats
    preg_match_all('/\[([A-Z_]+)\]/', $content, $square_matches);
    preg_match_all('/\{\{([^}]+)\}\}/', $content, $curly_matches);
    
    $placeholders = array();
    
    // Merge both types of placeholders
    if (!empty($square_matches[1])) {
        $placeholders = array_merge($placeholders, $square_matches[1]);
    }
    if (!empty($curly_matches[1])) {
        $placeholders = array_merge($placeholders, $curly_matches[1]);
    }
    
    if (!empty($placeholders)) {
        $placeholders = array_unique($placeholders);
        $placeholders = array_map('trim', $placeholders);
        $placeholders = array_values($placeholders); // Re-index array
    }
    
    wp_send_json_success(array('placeholders' => $placeholders));
}
    
    /**
     * AJAX: Save integration
     */
    public static function ajax_save_integration() {
        check_ajax_referer('divine_integration_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
        
        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        $enabled = isset($_POST['enabled']) && '1' === sanitize_text_field(wp_unslash($_POST['enabled']));
        $template_id = isset($_POST['template_id']) ? absint(wp_unslash($_POST['template_id'])) : 0;
        $send_email = isset($_POST['send_email']) && '1' === sanitize_text_field(wp_unslash($_POST['send_email']));
        $email_field = isset($_POST['email_field']) ? sanitize_text_field(wp_unslash($_POST['email_field'])) : '';
        $field_mapping = array();

        if (isset($_POST['field_mapping']) && is_array($_POST['field_mapping'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop immediately below.
            $field_mapping = wp_unslash($_POST['field_mapping']);
        }
        
        if (!$form_id) {
            wp_send_json_error(array('message' => esc_html__('Invalid form ID', 'divine-agreement-system')));
        }
        
        if ($enabled && (!$template_id || empty($email_field))) {
            wp_send_json_error(array('message' => esc_html__('Template and email field are required', 'divine-agreement-system')));
        }
        
        // Sanitize field mapping
        $sanitized_mapping = array();
        if (is_array($field_mapping)) {
            foreach ($field_mapping as $placeholder => $form_field) {
                $sanitized_mapping[sanitize_text_field($placeholder)] = sanitize_text_field($form_field);
            }
        }
        
        // Save configuration
        $config = array(
            'enabled' => $enabled,
            'template_id' => $template_id,
            'send_email' => $send_email,
            'email_field' => $email_field,
            'field_mapping' => $sanitized_mapping,
            'updated_at' => current_time('mysql')
        );
        
        update_option('divine_form_integration_' . $form_id, $config, false);
        
        wp_send_json_success(array('message' => esc_html__('Integration saved successfully', 'divine-agreement-system')));
    }
    
    /**
     * AJAX: Delete integration
     */
    public static function ajax_delete_integration() {
        check_ajax_referer('divine_integration_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
        
        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        
        if (!$form_id) {
            wp_send_json_error(array('message' => esc_html__('Invalid form ID', 'divine-agreement-system')));
        }
        
        delete_option('divine_form_integration_' . $form_id);
        
        wp_send_json_success(array('message' => esc_html__('Integration deleted successfully', 'divine-agreement-system')));
    }
    
    /**
     * AJAX: Test mapping
     */
    public static function ajax_test_mapping() {
        check_ajax_referer('divine_integration_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
        
        $template_id = isset($_POST['template_id']) ? absint(wp_unslash($_POST['template_id'])) : 0;
        $field_mapping = array();

        if (isset($_POST['field_mapping']) && is_array($_POST['field_mapping'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop immediately below.
            $field_mapping = wp_unslash($_POST['field_mapping']);
        }
        
        if (!$template_id) {
            wp_send_json_error(array('message' => esc_html__('Invalid template ID', 'divine-agreement-system')));
        }
        
        $template = get_post($template_id);
        if (!$template) {
            wp_send_json_error(array('message' => esc_html__('Template not found', 'divine-agreement-system')));
        }
        
        $sanitized_field_mapping = array();

        if (is_array($field_mapping)) {
            foreach ($field_mapping as $placeholder => $form_field) {
                $sanitized_field_mapping[sanitize_text_field($placeholder)] = sanitize_text_field($form_field);
            }
        }

        // Create sample preview
        $content = $template->post_content;
        
        foreach ($sanitized_field_mapping as $placeholder => $form_field) {
            $sample_value = '[Sample: ' . $form_field . ']';
            $content = str_replace('{{' . $placeholder . '}}', $sample_value, $content);
        }
        
        wp_send_json_success(array(
            'preview' => wp_kses_post($content),
            'message' => esc_html__('Mapping test successful', 'divine-agreement-system')
        ));
    }
    
    /**
     * AJAX: Get integration config
     */
    public static function ajax_get_integration_config() {
        check_ajax_referer('divine_integration_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Unauthorized', 'divine-agreement-system')));
        }
        
        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        
        if (!$form_id) {
            wp_send_json_error(array('message' => esc_html__('Invalid form ID', 'divine-agreement-system')));
        }
        
        $config = get_option('divine_form_integration_' . $form_id, array());
        
        if (empty($config)) {
            wp_send_json_error(array('message' => esc_html__('Configuration not found', 'divine-agreement-system')));
        }
        
        wp_send_json_success(array('config' => $config));
    }
    
    /**
     * Enqueue admin assets
     */
    public static function enqueue_admin_assets($hook) {
        if ($hook !== 'divine_agreement_page_divine-form-integration') {
            return;
        }
        
        wp_enqueue_style(
            'divine-integration-css',
            DIVINE_AGREEMENT_PLUGIN_URL . 'includes/integrations/assets/integration.css',
            array(),
            DIVINE_AGREEMENT_VERSION
        );
        
        wp_enqueue_script(
            'divine-integration-js',
            DIVINE_AGREEMENT_PLUGIN_URL . 'includes/integrations/assets/integration.js',
            array('jquery'),
            DIVINE_AGREEMENT_VERSION,
            true
        );
        
        wp_localize_script('divine-integration-js', 'divineIntegration', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('divine_integration_nonce'),
            'strings' => array(
                'confirm_delete' => __('Are you sure you want to delete this integration?', 'divine-agreement-system'),
                'saving' => __('Saving...', 'divine-agreement-system'),
                'saved' => __('Saved!', 'divine-agreement-system'),
                'error' => __('Error saving integration', 'divine-agreement-system'),
                'testing' => __('Testing...', 'divine-agreement-system'),
                'test_success' => __('Mapping test successful!', 'divine-agreement-system')
            )
        ));
    }
}

// Initialize
Divine_Form_Integration::init();
