<?php

namespace Bricksforge\ProForms\Actions;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class Mailerpress
{
    /**
     * Get all Mailerpress lists for builder select options
     *
     * @return array
     */
    public static function get_list_options()
    {
        if (!class_exists('\\MailerPress\\Models\\Lists')) {
            return [];
        }

        $lists = \MailerPress\Models\Lists::getLists();
        $options = [];

        if (!empty($lists) && is_array($lists)) {
            foreach ($lists as $list) {
                $list_id = isset($list['list_id']) ? $list['list_id'] : (isset($list['id']) ? $list['id'] : null);
                $name = isset($list['name']) ? $list['name'] : '';

                if ($list_id && $name) {
                    $options[$list_id] = $name;
                }
            }
        }

        return $options;
    }

    /**
     * Get all Mailerpress custom fields for builder select options
     *
     * @return array
     */
    public static function get_custom_field_options()
    {
        if (!class_exists('\\MailerPress\\Models\\CustomFields')) {
            return [];
        }

        $customFieldsModel = new \MailerPress\Models\CustomFields();
        $fields = $customFieldsModel->all();
        $options = [];

        if (!empty($fields) && is_array($fields)) {
            foreach ($fields as $field) {
                $field_key = isset($field->field_key) ? $field->field_key : (isset($field['field_key']) ? $field['field_key'] : null);
                $label = isset($field->label) ? $field->label : (isset($field['label']) ? $field['label'] : '');

                if ($field_key && $label) {
                    $options[$field_key] = $label;
                }
            }
        }

        return $options;
    }

    /**
     * Get all Mailerpress tags for builder select options
     *
     * @return array
     */
    public static function get_tag_options()
    {
        if (!class_exists('\\MailerPress\\Core\\Enums\\Tables')) {
            return [];
        }

        global $wpdb;

        $table_name = \MailerPress\Core\Enums\Tables::get(\MailerPress\Core\Enums\Tables::MAILERPRESS_TAGS);

        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name;

        if (!$table_exists) {
            return [];
        }

        $tags = $wpdb->get_results("SELECT tag_id, name FROM {$table_name}", ARRAY_A);
        $options = [];

        if (!empty($tags) && is_array($tags)) {
            foreach ($tags as $tag) {
                $tag_id = isset($tag['tag_id']) ? $tag['tag_id'] : null;
                $name = isset($tag['name']) ? $tag['name'] : '';

                if ($tag_id && $name) {
                    $options[$tag_id] = $name;
                }
            }
        }

        return $options;
    }

    /**
     * Subscribe contact to Mailerpress newsletter
     *
     * @since 3.1.8
     */
    public function run($form)
    {
        // Check if Mailerpress is active
        if (!function_exists('add_mailerpress_contact')) {
            $form->set_result(
                [
                    'action'  => 'mailerpress',
                    'type'    => 'error',
                    'message' => esc_html__('Mailerpress plugin is not active.', 'bricksforge')
                ]
            );
            return;
        }

        $form_settings = $form->get_settings();
        $form_fields   = $form->get_fields();

        // Get email address (required)
        $email_address = isset($form_settings['mailerpressEmail']) ? $form_settings['mailerpressEmail'] : false;

        if ($email_address) {
            $email_address = $form->get_form_field_by_id($email_address);
        }

        // Validate email
        if (!$email_address || !is_email($email_address)) {
            $form->set_result(
                [
                    'action'  => 'mailerpress',
                    'type'    => 'error',
                    'message' => esc_html__('No valid email address provided.', 'bricksforge')
                ]
            );
            return;
        }

        // Get optional fields
        $first_name = isset($form_settings['mailerpressFirstName']) ? $form_settings['mailerpressFirstName'] : '';
        $last_name = isset($form_settings['mailerpressLastName']) ? $form_settings['mailerpressLastName'] : '';
        $status = isset($form_settings['mailerpressStatus']) ? $form_settings['mailerpressStatus'] : 'subscribed';
        $opt_in_source = isset($form_settings['mailerpressOptInSource']) ? $form_settings['mailerpressOptInSource'] : '';
        $optin_details = isset($form_settings['mailerpressOptInDetails']) ? $form_settings['mailerpressOptInDetails'] : '';
        $lists = isset($form_settings['mailerpressLists']) ? $form_settings['mailerpressLists'] : [];
        $tags = isset($form_settings['mailerpressTags']) ? $form_settings['mailerpressTags'] : [];
        $custom_fields = isset($form_settings['mailerpressCustomFields']) ? $form_settings['mailerpressCustomFields'] : [];

        // Process first name
        if ($first_name) {
            $first_name = $form->get_form_field_by_id($first_name);
        }

        // Process last name
        if ($last_name) {
            $last_name = $form->get_form_field_by_id($last_name);
        }

        // Process opt-in source (render dynamic data for non-form-field values)
        if ($opt_in_source) {
            $opt_in_source = $form->get_form_field_by_id($opt_in_source);
        }

        // Process opt-in details (render dynamic data for non-form-field values)
        if ($optin_details) {
            $optin_details = $form->get_form_field_by_id($optin_details);
        }

        // Build contact data array
        $contact_data = [
            'contactEmail' => sanitize_email($email_address),
        ];

        if (!empty($first_name)) {
            $contact_data['contactFirstName'] = sanitize_text_field($first_name);
        }

        if (!empty($last_name)) {
            $contact_data['contactLastName'] = sanitize_text_field($last_name);
        }

        if (!empty($status)) {
            $contact_data['contactStatus'] = sanitize_text_field($status);
        }

        if (!empty($opt_in_source)) {
            $contact_data['opt_in_source'] = sanitize_text_field($opt_in_source);
        }

        if (!empty($optin_details)) {
            $contact_data['optin_details'] = sanitize_text_field($optin_details);
        }

        // Process lists - convert to format expected by Mailerpress
        if (!empty($lists)) {
            // Lists can be an array (from select) or string (for backwards compatibility)
            if (!is_array($lists)) {
                $lists = array_map('trim', explode(',', $lists));
            }

            $list_ids = array_filter($lists, function ($id) {
                return is_numeric($id) && intval($id) > 0;
            });

            if (!empty($list_ids)) {
                $contact_data['lists'] = array_map(function ($list_id) {
                    return ['id' => intval($list_id)];
                }, array_values($list_ids));
            }
        }

        // Process tags - convert to format expected by Mailerpress
        if (!empty($tags)) {
            // Tags can be an array (from select) or string (for backwards compatibility)
            if (!is_array($tags)) {
                $tags = array_map('trim', explode(',', $tags));
            }

            $tag_ids = array_filter($tags, function ($id) {
                return is_numeric($id) && intval($id) > 0;
            });

            if (!empty($tag_ids)) {
                $contact_data['tags'] = array_map(function ($tag_id) {
                    return ['id' => intval($tag_id)];
                }, array_values($tag_ids));
            }
        }

        // Process custom fields
        if (!empty($custom_fields) && is_array($custom_fields)) {
            $processed_custom_fields = [];

            foreach ($custom_fields as $custom_field) {
                $field_key = isset($custom_field['field_key']) ? $custom_field['field_key'] : '';
                $field_value = isset($custom_field['field_value']) ? $custom_field['field_value'] : '';

                if (!empty($field_key)) {
                    // Process field value (may contain form field reference)
                    $field_value = $form->get_form_field_by_id($field_value);
                    $processed_custom_fields[$field_key] = sanitize_text_field($field_value);
                }
            }

            if (!empty($processed_custom_fields)) {
                $contact_data['custom_fields'] = $processed_custom_fields;
            }
        }

        // Add the contact using Mailerpress function
        $result = add_mailerpress_contact($contact_data);

        // Handle result
        if (isset($result['success']) && $result['success'] === true) {
            $type = 'success';
        } else {
            $type = 'error';
        }

        $form->set_result(
            [
                'action'  => 'mailerpress',
                'type'    => $type,
                'body'    => $result,
            ]
        );
    }
}
