<?php

add_filter( 'adfoin_action_providers', 'adfoin_pabbly_actions', 10, 1 );

function adfoin_pabbly_actions( $actions ) {

    $actions['pabbly'] = array(
        'title' => __( 'Pabbly', 'advanced-form-integration' ),
        'tasks' => array(
            'subscribe'   => __( 'Add Contact To List', 'advanced-form-integration' )
        )
    );

    return $actions;
}

/**
 * Get Pabbly credentials by ID
 * 
 * @param string $cred_id Credential ID (optional, can be from $_POST)
 * @return array Array with 'api_key' key, or empty string if not found
 */
function adfoin_pabbly_get_credentials( $cred_id = '' ) {
    // If no cred_id provided, try to get from POST
    if ( empty( $cred_id ) && isset( $_POST['credId'] ) ) {
        $cred_id = sanitize_text_field( wp_unslash( $_POST['credId'] ) );
    }

    $api_key = '';

    if ( $cred_id ) {
        $credentials = adfoin_read_credentials( 'pabbly' );
        foreach( $credentials as $single ) {
            if( $single['id'] == $cred_id ) {
                $api_key = $single['api_key'];
                break;
            }
        }
    } else {
        // Fallback to old options if no cred_id provided
        $api_key = get_option( 'adfoin_pabbly_api_key' ) ? get_option( 'adfoin_pabbly_api_key' ) : '';
    }

    return array(
        'api_key' => $api_key
    );
}

add_filter( 'adfoin_settings_tabs', 'adfoin_pabbly_settings_tab', 10, 1 );

function adfoin_pabbly_settings_tab( $providers ) {
    $providers['pabbly'] = __( 'Pabbly', 'advanced-form-integration' );

    return $providers;
}

add_action( 'adfoin_settings_view', 'adfoin_pabbly_settings_view', 10, 1 );

function adfoin_pabbly_settings_view( $current_tab ) {
    if( $current_tab != 'pabbly' ) {
        return;
    }

    // Load Account Manager
    if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) {
        require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php';
    }

    // Migrate old settings if they exist and no new credentials exist
    $old_api_key = get_option( 'adfoin_pabbly_api_key' ) ? get_option( 'adfoin_pabbly_api_key' ) : '';
    
    $existing_creds = adfoin_read_credentials( 'pabbly' );

    if ( $old_api_key && empty( $existing_creds ) ) {
        $new_cred = array(
            'id' => wp_generate_uuid4(),
            'title' => 'Default Account (Legacy)',
            'api_key' => $old_api_key
        );
        adfoin_save_credentials( 'pabbly', array( $new_cred ) );
    }

    $fields = array(
        array(
            'name'          => 'api_key',
            'label'         => __( 'Pabbly Bearer Token', 'advanced-form-integration' ),
            'type'          => 'text',
            'required'      => true,
            'placeholder'   => __( 'Please enter Bearer Token', 'advanced-form-integration' ),
            'mask'          => true,
            'show_in_table' => true,
        ),
    );

    $instructions = '<ol class="afi-instructions-list">
            <li>' . __( 'Go to your Pabbly Email Marketing account.', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Navigate to Integrations > Developer API.', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Copy your Bearer Token.', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Enter the Bearer Token in the field above.', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Click "Add Account" and save your credentials.', 'advanced-form-integration' ) . '</li>
        </ol>';

    ADFOIN_Account_Manager::render_settings_view( 'pabbly', 'Pabbly', $fields, $instructions );
}

// AJAX Hooks for Account Manager
add_action( 'wp_ajax_adfoin_get_pabbly_credentials', 'adfoin_get_pabbly_credentials' );
function adfoin_get_pabbly_credentials() {
    if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) {
        require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php';
    }
    ADFOIN_Account_Manager::ajax_get_credentials( 'pabbly' );
}

add_action( 'wp_ajax_adfoin_save_pabbly_credentials', 'adfoin_save_pabbly_credentials' );
function adfoin_save_pabbly_credentials() {
    if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) {
        require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php';
    }
    ADFOIN_Account_Manager::ajax_save_credentials( 'pabbly', array( 'api_key' ) );
}

add_action( 'wp_ajax_adfoin_get_pabbly_credentials_list', 'adfoin_pabbly_get_credentials_list_ajax' );
function adfoin_pabbly_get_credentials_list_ajax() {
    adfoin_verify_nonce();

    if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) {
        require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php';
    }

    $fields = array(
        array( 'name' => 'api_key', 'mask' => true ),
    );

    ADFOIN_Account_Manager::ajax_get_credentials_list( 'pabbly', $fields );
}

add_action( 'admin_post_adfoin_save_pabbly_api_key', 'adfoin_save_pabbly_api_key', 10, 0 );

function adfoin_save_pabbly_api_key() {
    // Security Check
    // Authorization check
    adfoin_require_manage_options();

    if (! wp_verify_nonce( $_POST['_nonce'], 'adfoin_pabbly_settings' ) ) {
        die( __( 'Security check Failed', 'advanced-form-integration' ) );
    }

    $api_key = sanitize_text_field( wp_unslash( $_POST["adfoin_pabbly_api_key"] ) );

    // Save tokens
    update_option( "adfoin_pabbly_api_key", $api_key );

    advanced_form_integration_redirect( "admin.php?page=advanced-form-integration-settings&tab=pabbly" );
}

add_action( 'adfoin_add_js_fields', 'adfoin_pabbly_js_fields', 10, 1 );

function adfoin_pabbly_js_fields( $field_data ) { }

add_action( 'adfoin_action_fields', 'adfoin_pabbly_action_fields' );

function adfoin_pabbly_action_fields() {
?>
    <script type="text/template" id="pabbly-action-template">
        <table class="form-table">
            <tr valign="top" v-if="action.task == 'subscribe'">
                <th scope="row"><?php esc_html_e( 'Pabbly Account', 'advanced-form-integration' ); ?></th>
                <td>
                    <select name="fieldData[credId]" v-model="fielddata.credId" @change="handleAccountChange">
                        <option value=""> <?php _e( 'Select Account...', 'advanced-form-integration' ); ?> </option>
                        <option v-for="cred in credentialsList" :value="cred.id">{{ cred.title }}</option>
                    </select>
                    <a href="<?php echo admin_url( 'admin.php?page=advanced-form-integration-settings&tab=pabbly' ); ?>" 
                       target="_blank" 
                       style="margin-left: 10px; text-decoration: none;">
                        <span class="dashicons dashicons-admin-settings" style="margin-top: 3px;"></span>
                        <?php esc_html_e( 'Manage Accounts', 'advanced-form-integration' ); ?>
                    </a>
                    <span v-if="credentialLoading"><img src="<?php echo admin_url( 'images/spinner.gif' ); ?>" /></span>
                </td>
            </tr>

            <tr valign="top" v-if="action.task == 'subscribe'">
                <th scope="row">
                    <?php esc_attr_e( 'Map Fields', 'advanced-form-integration' ); ?>
                </th>
                <td scope="row">

                </td>
            </tr>

            <tr valign="top" class="alternate" v-if="action.task == 'subscribe'">
                <td scope="row-title">
                    <label for="tablecell">
                        <?php esc_attr_e( 'List', 'advanced-form-integration' ); ?>
                    </label>
                </td>
                <td>
                    <select name="fieldData[listId]" v-model="fielddata.listId">
                        <option value=""> <?php _e( 'Select List...', 'advanced-form-integration' ); ?> </option>
                        <option v-for="(item, index) in fielddata.list" :value="index" > {{item}}  </option>
                    </select>
                    <div class="afi-spinner" v-bind:class="{'is-active': listLoading}"></div>
                </td>
            </tr>

            <editable-field v-for="field in fields" v-bind:key="field.value" v-bind:field="field" v-bind:trigger="trigger" v-bind:action="action" v-bind:fielddata="fielddata"></editable-field>
            <?php adfoin_pro_feature_notice( 'subscribe', 'Pabbly [PRO]', 'custom fields' ); ?>

        </table>
    </script>


<?php
}

add_action( 'wp_ajax_adfoin_get_pabbly_list', 'adfoin_get_pabbly_list', 10, 0 );

/*
 * Get Pabbly subscriber lists
 */
function adfoin_get_pabbly_list() {
    adfoin_verify_nonce();

    $cred_id     = isset( $_POST['credId'] ) ? sanitize_text_field( wp_unslash( $_POST['credId'] ) ) : '';
    $credentials = adfoin_get_credentials_by_id( 'pabbly', $cred_id );
    $api_key     = isset( $credentials['api_key'] ) ? $credentials['api_key'] : '';

    if ( ! $api_key ) {
        wp_send_json_error();
        return;
    }

    $url  = 'https://emails.pabbly.com/api/subscribers-list';
    $args = array(
        'timeout' => 30,
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ),
    );

    $data = wp_remote_request( $url, $args );

    if ( is_wp_error( $data ) ) {
        wp_send_json_error();
        return;
    }

    $body = json_decode( wp_remote_retrieve_body( $data ) );

    if ( ! isset( $body->subscribers_list ) || ! is_array( $body->subscribers_list ) ) {
        wp_send_json_error();
        return;
    }

    $lists = wp_list_pluck( $body->subscribers_list, 'list_name', 'list_id' );

    wp_send_json_success( $lists );
}

add_action( 'adfoin_pabbly_job_queue', 'adfoin_pabbly_job_queue', 10, 1 );

function adfoin_pabbly_job_queue( $data ) {
    adfoin_pabbly_send_data( $data['record'], $data['posted_data'] );
}

/*
 * Handles sending data to Pabbly API
 */
function adfoin_pabbly_send_data( $record, $posted_data ) {

    $record_data = json_decode( $record['data'], true );

    if ( adfoin_check_conditional_logic( $record_data['action_data']['cl'] ?? array(), $posted_data ) ) {
        return;
    }

    $data    = $record_data['field_data'];
    $list_id = isset( $data['listId'] ) ? $data['listId'] : '';
    $task    = $record['task'];
    $cred_id = isset( $data['credId'] ) ? $data['credId'] : '';

    $credentials = adfoin_get_credentials_by_id( 'pabbly', $cred_id );
    $api_key     = isset( $credentials['api_key'] ) ? $credentials['api_key'] : '';

    if ( ! $api_key ) {
        return;
    }

    if ( $task == 'subscribe' ) {
        $email    = empty( $data['email'] ) ? '' : adfoin_get_parsed_values( $data['email'], $posted_data );
        $name     = empty( $data['name'] ) ? '' : adfoin_get_parsed_values( $data['name'], $posted_data );
        $mobile   = empty( $data['mobile'] ) ? '' : adfoin_get_parsed_values( $data['mobile'], $posted_data );
        $city     = empty( $data['city'] ) ? '' : adfoin_get_parsed_values( $data['city'], $posted_data );
        $country  = empty( $data['country'] ) ? '' : adfoin_get_parsed_values( $data['country'], $posted_data );
        $website  = empty( $data['website'] ) ? '' : adfoin_get_parsed_values( $data['website'], $posted_data );
        $facebook = empty( $data['facebook'] ) ? '' : adfoin_get_parsed_values( $data['facebook'], $posted_data );
        $google   = empty( $data['google'] ) ? '' : adfoin_get_parsed_values( $data['google'], $posted_data );
        $age      = empty( $data['age'] ) ? '' : adfoin_get_parsed_values( $data['age'], $posted_data );

        $body = array(
            'list_id'  => $list_id,
            'import'   => 'single',
            'email'    => $email,
            'name'     => $name,
            'mobile'   => $mobile,
            'city'     => $city,
            'country'  => $country,
            'website'  => $website,
            'facebook' => $facebook,
            'google'   => $google,
            'age'      => $age,
        );

        $url  = 'https://emails.pabbly.com/api/subscribers';
        $args = array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ),
            'body' => wp_json_encode( $body ),
        );

        $return = wp_remote_post( $url, $args );

        adfoin_add_to_log( $return, $url, $args, $record );
    }
}