<?php

add_filter( 'adfoin_action_providers', 'adfoin_capsulecrm_actions', 10, 1 );
 
function adfoin_capsulecrm_actions( $actions ) {

    $actions['capsulecrm'] = array(
        'title' => __( 'Capsule CRM', 'advanced-form-integration' ),
        'tasks' => array(
            'add_party' => __( 'Add Party, Opportunity, Case, Task', 'advanced-form-integration' )
        )
    );

    return $actions;
}
 
add_filter( 'adfoin_settings_tabs', 'adfoin_capsulecrm_settings_tab', 10, 1 );

function adfoin_capsulecrm_settings_tab( $providers ) {
    $providers['capsulecrm'] = __( 'Capsule CRM', 'advanced-form-integration' );

    return $providers;
}
 
add_action( 'adfoin_settings_view', 'adfoin_capsulecrm_settings_view', 10, 1 );

function adfoin_capsulecrm_settings_view( $current_tab ) {
    if( $current_tab != 'capsulecrm' ) {
        return;
    }

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

    $fields = array(
        array( 
            'name' => 'apiToken', 
            'label' => __( 'API Authentication Token', 'advanced-form-integration' ), 
            'type' => 'text', 
            'required' => true,
            'mask' => true,
            'placeholder' => __( 'Enter your API Token', 'advanced-form-integration' ),
            'show_in_table' => true
        )
    );

    $instructions = sprintf(
        '<p>%s</p>',
        __('Go to My Preferences > API Authentication Tokens > Generate New API Token', 'advanced-form-integration')
    );

    ADFOIN_Account_Manager::render_settings_view( 'capsulecrm', __( 'Capsule CRM', 'advanced-form-integration' ), $fields, $instructions );
}

add_action( 'wp_ajax_adfoin_get_capsulecrm_credentials', 'adfoin_get_capsulecrm_credentials', 10, 0 );
/*
 * Get Capsule CRM credentials
 */
function adfoin_get_capsulecrm_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_list( 'capsulecrm' );
}

add_action( 'wp_ajax_adfoin_save_capsulecrm_credentials', 'adfoin_save_capsulecrm_credentials', 10, 0 );
/*
 * Save Capsule CRM credentials
 */
function adfoin_save_capsulecrm_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( 'capsulecrm', array( 'apiToken' ) );
}

/*
 * Capsule CRM Credentials List
 */
function adfoin_capsulecrm_get_credentials_list() {
    $credentials = adfoin_read_credentials( 'capsulecrm' );

    foreach ($credentials as $option) {
        printf('<option value="%s">%s</option>', esc_attr($option['id']), esc_html($option['title']));
    }
}

// Legacy single-account import: surfaces old `adfoin_capsulecrm_*` options
// as a Legacy Account record when the new credentials store is empty.
add_action( 'plugins_loaded', function() {
    if ( class_exists( 'ADFOIN_Account_Manager' ) ) {
        ADFOIN_Account_Manager::register_legacy_option_importer( 'capsulecrm', array(
            'apiToken' => 'adfoin_capsulecrm_api_token',
        ) );
    }
}, 20 );

// Deprecated - kept for backward compatibility
add_action( 'admin_post_adfoin_save_capsulecrm_api_token', 'adfoin_save_capsulecrm_api_token', 10, 0 );

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

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

    $api_token = sanitize_text_field( wp_unslash( $_POST["adfoin_capsulecrm_api_token"] ) );

    // Save tokens
    update_option( "adfoin_capsulecrm_api_token", $api_token );

    advanced_form_integration_redirect( "admin.php?page=advanced-form-integration-settings&tab=capsulecrm" );
}
 
add_action( 'adfoin_action_fields', 'adfoin_capsulecrm_action_fields', 10, 1 );

function adfoin_capsulecrm_action_fields() {
    ?>
    <script type="text/template" id="capsulecrm-action-template">
        <table class="form-table">
            <tr valign="top" v-if="action.task == 'add_party'">
                <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 == 'add_party'">
                <td scope="row-title">
                    <label for="tablecell">
                        <?php esc_attr_e( 'Capsule CRM Account', 'advanced-form-integration' ); ?>
                    </label>
                </td>
                <td>
                    <select name="fieldData[credId]" v-model="fielddata.credId" @change="getData">
                        <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=capsulecrm' ); ?>" target="_blank">
                        <span class="dashicons dashicons-admin-settings"></span>
                        <?php esc_html_e( 'Manage Accounts', 'advanced-form-integration' ); ?>
                    </a>

                    <div class="afi-spinner" v-bind:class="{'is-active': credentialLoading}"></div>
                </td>
            </tr>

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

            <tr valign="top" class="alternate" v-if="action.task == 'add_party'">
                <td scope="row-title">
                    <label for="tablecell">
                        <?php esc_attr_e( 'Entities', 'advanced-form-integration' ); ?>
                    </label>
                </td>
                <td>
                    <div class="object_selection" style="display: inline;">
                        <input type="checkbox" id="organisation__chosen" value="true" v-model="fielddata.organisation__chosen" name="fieldData[organisation__chosen]">
                        <label style="margin-right:10px;" for="organisation__chosen">Organisation</label>
                        <input type="checkbox" id="person__chosen" value="true" v-model="fielddata.person__chosen" name="fieldData[person__chosen]">
                        <label style="margin-right:10px;" for="person__chosen">Person</label>
                        <input type="checkbox" id="opportunity__chosen" value="true" v-model="fielddata.opportunity__chosen" name="fieldData[opportunity__chosen]">
                        <label style="margin-right:10px;" for="opportunity__chosen">Opportunity</label>
                        <input type="checkbox" id="case__chosen" value="true" v-model="fielddata.case__chosen" name="fieldData[case__chosen]">
                        <label style="margin-right:10px;" for="case__chosen">Case</label>
                        <input type="checkbox" id="task__chosen" value="true" v-model="fielddata.task__chosen" name="fieldData[task__chosen]">
                        <label style="margin-right:10px;" for="task__chosen">Task</label>
                    </div>
                    
                    <button class="button-secondary" @click.stop.prevent="getFields">Get Fields</button>
                    <div class="afi-spinner" v-bind:class="{'is-active': fieldsLoading}"></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( 'add_party', 'Capsule CRM [PRO]', 'custom fields and tags' ); ?>
        </table>
    </script>
    <?php
}

 /*
 * Capsule CRM API Request
 */
function adfoin_capsulecrm_request( $endpoint, $method = 'GET', $data = array(), $record = array(), $cred_id = '' ) {
    $credentials = adfoin_get_credentials_by_id( 'capsulecrm', $cred_id );
    $api_token = isset( $credentials['apiToken'] ) ? $credentials['apiToken'] : '';

    // Backward compatibility: fallback to old option if credentials not found
    if( empty( $api_token ) ) {
        $api_token = get_option( 'adfoin_capsulecrm_api_token' ) ? get_option( 'adfoin_capsulecrm_api_token' ) : '';
    }

    if( !$api_token ) {
        return array();
    }

    $base_url = 'https://api.capsulecrm.com/api/v2/';
    $url      = $base_url . $endpoint;

    $args = array(
        'timeout' => 30,
        'method'  => $method,
        'headers' => array(
            'Content-Type' => 'application/json; charset=utf-8',
            'Accept'        => 'application/json',
            'Authorization' => 'Bearer ' . $api_token,
        ),
    );

    if ('POST' == $method || 'PUT' == $method) {
        $args['body'] = wp_json_encode($data);
    }

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

    // Capsule limits at 4000 requests/hour and returns HTTP 429 with a
    // Retry-After header (seconds) when exceeded. The request was not
    // processed, so retry once after waiting (clamped to <=30s).
    if ( 429 == (int) wp_remote_retrieve_response_code( $response ) ) {
        $retry_after = wp_remote_retrieve_header( $response, 'retry-after' );
        $wait        = is_numeric( $retry_after ) ? (int) $retry_after : 2;

        if ( $wait < 1 ) {
            $wait = 1;
        }
        if ( $wait > 30 ) {
            $wait = 30;
        }

        sleep( $wait );
        $response = wp_remote_request( $url, $args );
    }

    if ($record) {
        adfoin_add_to_log($response, $url, $args, $record);
    }

    return $response;
}

add_action( 'wp_ajax_adfoin_get_capsulecrm_owner_list', 'adfoin_get_capsulecrm_owner_list', 10, 0 );

/*
* Get Capsulecrm Owner list
*/
function adfoin_get_capsulecrm_owner_list() {
// Security Check (capability + nonce, with isset/unslash/sanitize)
adfoin_verify_nonce();

$cred_id = isset( $_POST['credId'] ) ? sanitize_text_field( wp_unslash( $_POST['credId'] ) ) : '';

$combined = array();
$users    = adfoin_get_capsulecrm_users( $cred_id );
$teams    = adfoin_get_capsulecrm_teams( $cred_id );

foreach( $users as $user ) {
    $combined['user__' . $user['id']] = $user['name'];
}

foreach( $teams as $team ) {
    $combined['team__' . $team['id']] = $team['name'];
}

wp_send_json_success( $combined );
}


/*
* Fetch ALL items from a paginated Capsule collection.
*
* Capsule paginates list endpoints (default 50, max perPage=100). The fetchers
* previously read only the first page, silently truncating users / teams /
* milestones / custom-field definitions / tracks on larger accounts. This loops
* perPage=100 until a short page is returned, bounded to 50 pages (5000 items)
* as a runaway guard.
*/
function adfoin_capsulecrm_fetch_all( $endpoint, $key, $cred_id = '' ) {
    $items = array();
    $page  = 1;
    $sep   = ( false === strpos( $endpoint, '?' ) ) ? '?' : '&';

    do {
        $paged = $endpoint . $sep . 'perPage=100&page=' . $page;
        $data  = adfoin_capsulecrm_request( $paged, 'GET', array(), array(), $cred_id );

        if( is_wp_error( $data ) || 200 != wp_remote_retrieve_response_code( $data ) ) {
            break;
        }

        $body  = json_decode( wp_remote_retrieve_body( $data ), true );
        $batch = ( isset( $body[ $key ] ) && is_array( $body[ $key ] ) ) ? $body[ $key ] : array();
        $items = array_merge( $items, $batch );
        $page++;
    } while( count( $batch ) === 100 && $page <= 50 );

    return $items;
}

//Get users list
function adfoin_get_capsulecrm_users( $cred_id = '' ) {
    return adfoin_capsulecrm_fetch_all( 'users', 'users', $cred_id );
}

//Get team list
function adfoin_get_capsulecrm_teams( $cred_id = '' ) {
    return adfoin_capsulecrm_fetch_all( 'teams', 'teams', $cred_id );
}

 //Get Opportunity Milestones
 function adfoin_get_capsulecrm_opportunity_milestones( $cred_id = '' ) {
    $milestones = array();

    foreach( adfoin_capsulecrm_fetch_all( 'milestones', 'milestones', $cred_id ) as $milestone ) {
        $milestones[] = $milestone['pipeline']['name'] . '/' . $milestone['name'] . ': ' . $milestone['id'];
    }

    $merged = implode( ', ', $milestones );

    return $merged;
 }
 
 add_action( 'wp_ajax_adfoin_get_capsulecrm_all_fields', 'adfoin_get_capsulecrm_all_fields', 10, 0 );
 
/*
* Get Capsule CRM All Fields
*/
function adfoin_get_capsulecrm_all_fields() {
    // Security Check (capability + nonce, with isset/unslash/sanitize)
    adfoin_verify_nonce();

    $cred_id          = isset( $_POST['credId'] ) ? sanitize_text_field( wp_unslash( $_POST['credId'] ) ) : '';
    $final_data       = array();
    $selected_objects = isset( $_POST['selectedObjects'] ) ? adfoin_sanitize_text_or_array_field( $_POST['selectedObjects'] ) : array();

    if( in_array( 'organisation', $selected_objects ) ) {
        $org_fields = array(
            array( 'key' => 'org_name', 'value' => 'Name [Organization]', 'description' => 'Required if you want to create an organization, otherwise leave empty' ),
            array( 'key' => 'org_phone', 'value' => 'Phone [Organization]', 'description' => '' ),
            array( 'key' => 'org_email', 'value' => 'Email [Organization]', 'description' => '' ),
            array( 'key' => 'org_website', 'value' => 'Website [Organization]', 'description' => '' ),
            array( 'key' => 'org_twitter', 'value' => 'Twitter [Organization]', 'description' => '' ),
            array( 'key' => 'org_linkedin', 'value' => 'LinkedIn [Organization]', 'description' => '' ),
            array( 'key' => 'org_facebook', 'value' => 'Facebook [Organization]', 'description' => '' ),
            array( 'key' => 'org_youtube', 'value' => 'YouTube [Organization]', 'description' => '' ),
            array( 'key' => 'org_instagram', 'value' => 'Instagram [Organization]', 'description' => '' ),
            array( 'key' => 'org_address', 'value' => 'Address [Organization]', 'description' => '' ),
            array( 'key' => 'org_city', 'value' => 'City [Organization]', 'description' => '' ),
            array( 'key' => 'org_state', 'value' => 'State [Organization]', 'description' => '' ),
            array( 'key' => 'org_zip', 'value' => 'Zip [Organization]', 'description' => '' ),
            array( 'key' => 'org_country', 'value' => 'Country [Organization]', 'description' => '' ),
        );

        $final_data = array_merge( $final_data, $org_fields );
    }

    if( in_array( 'person', $selected_objects ) ) {
        $person_fields = array(
            array( 'key' => 'person_title', 'value' => 'Title [Person]', 'description' => '' ),
            array( 'key' => 'person_firstName', 'value' => 'First Name [Person]', 'description' => 'Required if you want to create a person, otherwise leave empty' ),
            array( 'key' => 'person_lastName', 'value' => 'Last Name [Person]', 'description' => '' ),
            array( 'key' => 'person_jobTitle', 'value' => 'Job Title [Person]', 'description' => '' ),
            array( 'key' => 'person_workPhone', 'value' => 'Work Phone [Person]', 'description' => '' ),
            array( 'key' => 'person_homePhone', 'value' => 'Home Phone [Person]', 'description' => '' ),
            array( 'key' => 'person_mobilePhone', 'value' => 'Mobile Phone [Person]', 'description' => '' ),
            array( 'key' => 'person_email', 'value' => 'Email [Person]', 'description' => '' ),
            array( 'key' => 'person_website', 'value' => 'Website [Person]', 'description' => '' ),
            array( 'key' => 'person_twitter', 'value' => 'Twitter [Person]', 'description' => '' ),
            array( 'key' => 'person_linkedin', 'value' => 'LinkedIn [Person]', 'description' => '' ),
            array( 'key' => 'person_facebook', 'value' => 'Facebook [Person]', 'description' => '' ),
            array( 'key' => 'person_youtube', 'value' => 'YouTube [Person]', 'description' => '' ),
            array( 'key' => 'person_instagram', 'value' => 'Instagram [Person]', 'description' => '' ),
            array( 'key' => 'person_addressType', 'value' => 'Address Type [Person]', 'description' => 'Home | Postal | Office | Billing | Shipping' ),
            array( 'key' => 'person_address', 'value' => 'Address [Person]', 'description' => '' ),
            array( 'key' => 'person_city', 'value' => 'City [Person]', 'description' => '' ),
            array( 'key' => 'person_state', 'value' => 'State [Person]', 'description' => '' ),
            array( 'key' => 'person_zip', 'value' => 'Zip [Person]', 'description' => '' ),
            array( 'key' => 'person_country', 'value' => 'Country [Person]', 'description' => '' ),
        );

        $final_data = array_merge( $final_data, $person_fields );
    }

    if( in_array( 'opportunity', $selected_objects ) ) {
        $milestones = adfoin_get_capsulecrm_opportunity_milestones( $cred_id );

        $opportunity_fields = array(
            array( 'key' => 'opportunity_name', 'value' => 'Name [Opportunity]', 'description' => 'Required if you want to create an opportunity, otherwise leave empty' ),
            array( 'key' => 'opportunity_description', 'value' => 'Description [Opportunity]', 'description' => '' ),
            array( 'key' => 'opportunity_milestone_id', 'value' => 'Milestone ID [Opportunity]', 'description' => $milestones ),
            array( 'key' => 'opportunity_currency', 'value' => 'Currency [Opportunity]', 'description' => 'e.g. USD, GBP' ),
            array( 'key' => 'opportunity_value', 'value' => 'Value [Opportunity]', 'description' => '' ),
            array( 'key' => 'opportunity_probability', 'value' => 'Probability [Opportunity]', 'description' => '' ),
            array( 'key' => 'opportunity_expectedCloseOn', 'value' => 'Expected Close Date [Opportunity]', 'description' => '' ),
            array( 'key' => 'opportunity_durationBasis', 'value' => 'Payment Terms [Opportunity]', 'description' => 'FIXED | HOUR | DAY | WEEK | MONTH | QUARTER | YEAR' ),
            array( 'key' => 'opportunity_duration', 'value' => 'Payment Duration [Opportunity]', 'description' => '' ),
        );

        $final_data = array_merge( $final_data, $opportunity_fields );
    }

    if( in_array( 'case', $selected_objects ) ) {

        $case_fields = array(
            array( 'key' => 'case_name', 'value' => 'Name [Case]', 'description' => 'Required if you want to create a case, otherwise leave empty' ),
            array( 'key' => 'case_description', 'value' => 'Description [Case]', 'description' => '' ),
            array( 'key' => 'case_expectedCloseOn', 'value' => 'Expected Close Date [Case]', 'description' => '' ),
        );

        $final_data = array_merge( $final_data, $case_fields );
    }

    if( in_array( 'task', $selected_objects ) ) {
        $task_fields = array(
            array( 'key' => 'task_description', 'value' => 'Description [Task]', 'description' => 'Required if you want to create a task, otherwise leave empty' ),
            array( 'key' => 'task_dueOn', 'value' => 'Due Date [Task]', 'description' => '' ),
            array( 'key' => 'task_dueTime', 'value' => 'Due Time [Task]', 'description' => '' ),
            array( 'key' => 'task_category', 'value' => 'Category [Task]', 'description' => '' ),
        );

        $final_data = array_merge( $final_data, $task_fields );
    }

    wp_send_json_success( $final_data );
}

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

function adfoin_capsulecrm_job_queue( $data ) {
    adfoin_capsulecrm_send_data( $data['record'], $data['posted_data'] );
}
  
/*
* Handles sending data to Capsule CRM API
*/
function adfoin_capsulecrm_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'];
    $task           = $record['task'];
    $cred_id        = isset( $data['credId'] ) ? $data['credId'] : '';
    $owner          = isset( $data['owner'] ) ? $data['owner'] : '';
    $org_id         = '';
    $person_id      = '';
    $opportunity_id = '';
    $case_id        = '';

    // Backward compatibility: if no cred_id, use first available credential
    if( empty( $cred_id ) ) {
        $all_credentials = adfoin_read_credentials( 'capsulecrm' );
        if( !empty( $all_credentials ) ) {
            $cred_id = $all_credentials[0]['id'];
        }
    }

    if( $task == "add_party" ) {

        $org_data         = array();
        $person_data      = array();
        $deal_data        = array();
        $opportunity_data = array();
        $case_data        = array();
        $task_data        = array();

        foreach( $data as $key => $value ) {
            if( substr( $key, 0, 4 ) == 'org_' && $value ) {
                $key = substr( $key, 4 );

                $org_data[$key] = $value;
            }

            if( substr( $key, 0, 7 ) == 'person_' && $value ) {
                $key = substr( $key, 7 );

                $person_data[$key] = $value;
            }

            if( substr( $key, 0, 12 ) == 'opportunity_' && $value ) {
                $key = substr( $key, 12 );

                $opportunity_data[$key] = $value;
            }

            if( substr( $key, 0, 5 ) == 'case_' && $value ) {
                $key = substr( $key, 5 );

                $case_data[$key] = $value;
            }

            if( substr( $key, 0, 5 ) == 'task_' && $value ) {
                $key = substr( $key, 5 );

                $task_data[$key] = $value;
            }
        }

        if( isset( $org_data['name'] ) && $org_data['name'] ) {
            $endpoint           = 'parties';
            $method             = 'POST';
            $org_holder         = array();
            $org_holder['type'] = 'organisation';
            $org_holder['name'] = adfoin_get_parsed_values( $org_data['name'], $posted_data );

            if( $owner ) {
                if( substr( $owner, 0, 6 ) == 'user__' ) {
                    $user_id = substr( $owner, 6 );
                    
                    $org_holder['owner'] = array(
                        'id' => (int)$user_id
                    );
                }

                if( substr( $owner, 0, 6 ) == 'team__' ) {
                    $team_id = substr( $owner, 6 );
                    
                    $org_holder['team'] = array(
                        'id' => (int)$team_id
                    );
                }
            }

            if( isset( $org_data['phone'] ) && $org_data['phone'] ) {
                $work_phone = adfoin_get_parsed_values( $org_data['phone'], $posted_data );

                if( $work_phone ) {
                    $org_holder['phoneNumbers'] = array(
                        array(
                            'type'    => 'Work',
                            'number' => $work_phone
                        )
                    );
                }
            }

            if( isset( $org_data['email'] ) && $org_data['email'] ) {
                $email_address = adfoin_get_parsed_values( $org_data['email'], $posted_data );

                if( $email_address ) {
                    $org_holder['emailAddresses'] = array(
                        array(
                        'type'    => 'Work',
                        'address' => $email_address
                        )
                    );
                }
            }

            if( isset( $org_data['website'] ) 
            || isset( $org_data['twitter'] )
            || isset( $org_data['linkedin'] )
            || isset( $org_data['facebook'] )
            || isset( $org_data['youtube'] )
            || isset( $org_data['instagram'] ) ) {
                $org_holder['websites'] = array();

                if( isset( $org_data['website'] ) && $org_data['website'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'URL', 'address' => adfoin_get_parsed_values( $org_data['website'], $posted_data ) ) );
                }

                if( isset( $org_data['twitter'] ) && $org_data['twitter'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'TWITTER', 'address' => adfoin_get_parsed_values( $org_data['twitter'], $posted_data ) ) );
                }

                if( isset( $org_data['linkedin'] ) && $org_data['linkedin'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'LINKEDIN', 'address' => adfoin_get_parsed_values( $org_data['linkedin'], $posted_data ) ) );
                }

                if( isset( $org_data['facebook'] ) && $org_data['facebook'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'FACEBOOK', 'address' => adfoin_get_parsed_values( $org_data['facebook'], $posted_data ) ) );
                }

                if( isset( $org_data['youtube'] ) && $org_data['youtube'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'YOUTUBE', 'address' => adfoin_get_parsed_values( $org_data['youtube'], $posted_data ) ) );
                }

                if( isset( $org_data['instagram'] ) && $org_data['instagram'] ) {
                    array_push( $org_holder['websites'], array( 'service' => 'INSTAGRAM', 'address' => adfoin_get_parsed_values( $org_data['instagram'], $posted_data ) ) );
                }
            }

            if( isset( $org_data['address'] ) 
            || isset( $org_data['city'] )
            || isset( $org_data['state'] )
            || isset( $org_data['zip'] )
            || isset( $org_data['country'] ) ) {
                $org_holder['addresses'] = array(
                    array(
                        'type' => 'Office'
                    )
                );

                if( isset( $org_data['address'] ) && $org_data['address'] ) {
                    $org_holder['addresses'][0]['street'] = adfoin_get_parsed_values( $org_data['address'], $posted_data );
                }

                if( isset( $org_data['city'] ) && $org_data['city'] ) {
                    $org_holder['addresses'][0]['city'] = adfoin_get_parsed_values( $org_data['city'], $posted_data );
                }

                if( isset( $org_data['state'] ) && $org_data['state'] ) {
                    $org_holder['addresses'][0]['state'] = adfoin_get_parsed_values( $org_data['state'], $posted_data );
                }

                if( isset( $org_data['zip'] ) && $org_data['zip'] ) {
                    $org_holder['addresses'][0]['zip'] = adfoin_get_parsed_values( $org_data['zip'], $posted_data );
                }

                if( isset( $org_data['country'] ) && $org_data['country'] ) {
                    $org_holder['addresses'][0]['country'] = adfoin_get_parsed_values( $org_data['country'], $posted_data );
                }
            }

            $org_id = adfoin_capsulecrm_party_exists( $org_holder['name'], $cred_id );

            if( $org_id ) {
                $endpoint = "parties/{$org_id}";
                $method   = 'PUT';
            }

            $org_holder   = array_filter( $org_holder );
            $org_response = adfoin_capsulecrm_request( $endpoint, $method, array( 'party' => $org_holder ), $record, $cred_id );
            $org_body     = json_decode( wp_remote_retrieve_body( $org_response ), true );

            if( isset( $org_body['party'], $org_body['party']['id'] ) ) {
                $org_id = $org_body['party']['id'];
            }
        }

        if( isset( $person_data['firstName'] ) && $person_data['firstName'] ) {
            $endpoint           = 'parties';
            $method             = 'POST';
            $person_holder         = array();
            $person_holder['type'] = 'person';
            $person_holder['title'] = isset( $person_data['title'] ) ? adfoin_get_parsed_values( $person_data['title'], $posted_data ) : null;
            $person_holder['firstName'] = isset( $person_data['firstName'] ) ? adfoin_get_parsed_values( $person_data['firstName'], $posted_data ) : null;
            $person_holder['lastName'] = isset( $person_data['lastName'] ) ? adfoin_get_parsed_values( $person_data['lastName'], $posted_data ) : null;
            $person_holder['jobTitle'] = isset( $person_data['jobTitle'] ) ? adfoin_get_parsed_values( $person_data['jobTitle'], $posted_data ) : null;

            // Resolve email up-front so the upsert check below can search on
            // the real address. Previously the search used the undefined key
            // $person_holder['email'], which could match the first random
            // party in the account and overwrite an unrelated record.
            $email_address = '';

            if( $owner ) {
                if( substr( $owner, 0, 6 ) == 'user__' ) {
                    $user_id = substr( $owner, 6 );
                    
                    $person_holder['owner'] = array(
                        'id' => (int)$user_id
                    );
                }

                if( substr( $owner, 0, 6 ) == 'team__' ) {
                    $team_id = substr( $owner, 6 );
                    
                    $person_holder['team'] = array(
                        'id' => (int)$team_id
                    );
                }
            }

            if( isset( $person_data['workPhone'] ) || isset( $person_data['homePhone'] ) || isset( $person_data['mobilePhone'] ) ) {
                $work_phone   = isset( $person_data['workPhone'] ) ? adfoin_get_parsed_values( $person_data['workPhone'], $posted_data ) : '';
                $home_phone   = isset( $person_data['homePhone'] ) ? adfoin_get_parsed_values( $person_data['homePhone'], $posted_data ) : '';
                $mobile_phone = isset( $person_data['mobilePhone'] ) ? adfoin_get_parsed_values( $person_data['mobilePhone'], $posted_data ) : '';

                if( $work_phone || $home_phone || $mobile_phone ) {
                    $person_holder['phoneNumbers'] = array();
                }

                if( $work_phone ) {
                    array_push( $person_holder['phoneNumbers'],
                        array(
                            'type'    => 'Work',
                            'number' => $work_phone
                        )
                    );
                }

                if( $home_phone ) {
                    array_push( $person_holder['phoneNumbers'],
                        array(
                            'type'    => 'Home',
                            'number' => $home_phone
                        )
                    );
                }

                if( $mobile_phone ) {
                    array_push( $person_holder['phoneNumbers'],
                        array(
                            'type'    => 'Mobile',
                            'number' => $mobile_phone
                        )
                    );
                }
            }

            if( isset( $person_data['email'] ) && $person_data['email'] ) {
                $email_address = adfoin_get_parsed_values( $person_data['email'], $posted_data );

                if( $email_address ) {
                    $person_holder['emailAddresses'] = array(
                        array(
                        'type'    => 'Work',
                        'address' => $email_address
                        )
                    );
                }
            }

            if( $org_id ) {
                $person_holder['organisation'] = array( 'id' => $org_id );
            }

            if( isset( $person_data['website'] ) 
            || isset( $person_data['twitter'] )
            || isset( $person_data['linkedin'] )
            || isset( $person_data['facebook'] )
            || isset( $person_data['youtube'] )
            || isset( $person_data['instagram'] ) ) {
                $person_holder['websites'] = array();

                if( isset( $person_data['website'] ) && $person_data['website'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'URL', 'address' => adfoin_get_parsed_values( $person_data['website'], $posted_data ) ) );
                }

                if( isset( $person_data['twitter'] ) && $person_data['twitter'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'TWITTER', 'address' => adfoin_get_parsed_values( $person_data['twitter'], $posted_data ) ) );
                }

                if( isset( $person_data['linkedin'] ) && $person_data['linkedin'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'LINKEDIN', 'address' => adfoin_get_parsed_values( $person_data['linkedin'], $posted_data ) ) );
                }

                if( isset( $person_data['facebook'] ) && $person_data['facebook'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'FACEBOOK', 'address' => adfoin_get_parsed_values( $person_data['facebook'], $posted_data ) ) );
                }

                if( isset( $person_data['youtube'] ) && $person_data['youtube'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'YOUTUBE', 'address' => adfoin_get_parsed_values( $person_data['youtube'], $posted_data ) ) );
                }

                if( isset( $person_data['instagram'] ) && $person_data['instagram'] ) {
                    array_push( $person_holder['websites'], array( 'service' => 'INSTAGRAM', 'address' => adfoin_get_parsed_values( $person_data['instagram'], $posted_data ) ) );
                }
            }

            if( isset( $person_data['address'] ) 
            || isset( $person_data['city'] )
            || isset( $person_data['state'] )
            || isset( $person_data['zip'] )
            || isset( $person_data['country'] ) ) {
                $person_holder['addresses'] = array(
                    array(
                        'type' => ( isset( $person_data['addressType'] ) && $person_data['addressType'] ) ? $person_data['addressType'] : 'Home'
                    )
                );

                if( isset( $person_data['address'] ) && $person_data['address'] ) {
                    $person_holder['addresses'][0]['street'] = adfoin_get_parsed_values( $person_data['address'], $posted_data );
                }

                if( isset( $person_data['city'] ) && $person_data['city'] ) {
                    $person_holder['addresses'][0]['city'] = adfoin_get_parsed_values( $person_data['city'], $posted_data );
                }

                if( isset( $person_data['state'] ) && $person_data['state'] ) {
                    $person_holder['addresses'][0]['state'] = adfoin_get_parsed_values( $person_data['state'], $posted_data );
                }

                if( isset( $person_data['zip'] ) && $person_data['zip'] ) {
                    $person_holder['addresses'][0]['zip'] = adfoin_get_parsed_values( $person_data['zip'], $posted_data );
                }

                if( isset( $person_data['country'] ) && $person_data['country'] ) {
                    $person_holder['addresses'][0]['country'] = adfoin_get_parsed_values( $person_data['country'], $posted_data );
                }
            }

            $person_id = $email_address ? adfoin_capsulecrm_party_exists( $email_address, $cred_id ) : false;

            if( $person_id ) {
                $endpoint = "parties/{$person_id}";
                $method   = 'PUT';
            }

            $person_holder   = array_filter( $person_holder );
            $person_response = adfoin_capsulecrm_request( $endpoint, $method, array( 'party' => $person_holder ), $record, $cred_id );
            $person_body     = json_decode( wp_remote_retrieve_body( $person_response ), true );

            if( isset( $person_body['party'], $person_body['party']['id'] ) ) {
                $person_id = $person_body['party']['id'];
            }
        }

        if( isset( $opportunity_data['name'] ) && $opportunity_data['name'] ) {
            $endpoint                          = 'opportunities';
            $method                            = 'POST';
            $opportunity_holder                = array();
            $opportunity_holder['name']        = adfoin_get_parsed_values( $opportunity_data['name'], $posted_data );
            $opportunity_holder['description'] = isset( $opportunity_data['description'] ) ? adfoin_get_parsed_values( $opportunity_data['description'], $posted_data ) : '';

            if( isset( $opportunity_data['milestone_id'] ) && $opportunity_data['milestone_id'] ) {
                $opportunity_holder['milestone'] = array(
                    'id' => (int)$opportunity_data['milestone_id']
                );
            }

            if( $owner ) {
                if( substr( $owner, 0, 6 ) == 'user__' ) {
                    $user_id = substr( $owner, 6 );
                    
                    $opportunity_holder['owner'] = array(
                        'id' => (int)$user_id
                    );
                }

                if( substr( $owner, 0, 6 ) == 'team__' ) {
                    $team_id = substr( $owner, 6 );
                    
                    $opportunity_holder['team'] = array(
                        'id' => (int)$team_id
                    );
                }
            }

            // Opportunity links to a single party. When both an organisation and
            // a person were created/found in this submission, the person wins by
            // default; override via the filter for org-first (B2B) setups.
            $link_party_id = apply_filters( 'adfoin_capsulecrm_link_party_id', ( $person_id ? $person_id : $org_id ), $org_id, $person_id, 'opportunity' );

            if( $link_party_id ) {
                $opportunity_holder['party'] = array( 'id' => $link_party_id );
            }

            if( isset( $opportunity_data['value'] ) && $opportunity_data['value'] ) {
                $opportunity_holder['value'] = array(
                    'amount' => (float)$opportunity_data['value']
                );

                if( isset( $opportunity_data['currency'] ) && $opportunity_data['currency'] ) {
                    $opportunity_holder['value']['currency'] = $opportunity_data['currency'];
                }
            }

            if( isset( $opportunity_data['probability'] ) && $opportunity_data['probability'] ) {
                $opportunity_holder['probability'] = adfoin_get_parsed_values( $opportunity_data['probability'], $posted_data );
            }

            if( isset( $opportunity_data['expectedCloseOn'] ) && $opportunity_data['expectedCloseOn'] ) {
                $opportunity_holder['expectedCloseOn'] = adfoin_get_parsed_values( $opportunity_data['expectedCloseOn'], $posted_data );
            }

            if( isset( $opportunity_data['durationBasis'] ) && $opportunity_data['durationBasis'] ) {
                $opportunity_holder['durationBasis'] = adfoin_get_parsed_values( $opportunity_data['durationBasis'], $posted_data );
            }

            if( isset( $opportunity_data['duration'] ) && $opportunity_data['duration'] ) {
                $opportunity_holder['duration'] = adfoin_get_parsed_values( $opportunity_data['duration'], $posted_data );

                if( isset( $opportunity_holder['durationBasis'] ) && 'FIXED' == $opportunity_holder['durationBasis'] ) {
                    $opportunity_holder['duration'] = null;
                }
            }

            $opportunity_holder   = array_filter( $opportunity_holder );
            $opportunity_response = adfoin_capsulecrm_request( $endpoint, $method, array( 'opportunity' => $opportunity_holder ), $record, $cred_id );
            $opportunity_body     = json_decode( wp_remote_retrieve_body( $opportunity_response ), true );

            if( isset( $opportunity_body['opportunity'], $opportunity_body['opportunity']['id'] ) ) {
                $opportunity_id = $opportunity_body['opportunity']['id'];
            }
        }

        if( isset( $case_data['name'] ) && $case_data['name'] ) {
            $endpoint                   = 'kases';
            $method                     = 'POST';
            $case_holder                = array();
            $case_holder['name']        = adfoin_get_parsed_values( $case_data['name'], $posted_data );
            $case_holder['description'] = adfoin_get_parsed_values( $case_data['description'], $posted_data );

            if( $owner ) {
                if( substr( $owner, 0, 6 ) == 'user__' ) {
                    $user_id = substr( $owner, 6 );
                    
                    $case_holder['owner'] = array(
                        'id' => (int)$user_id
                    );
                }

                if( substr( $owner, 0, 6 ) == 'team__' ) {
                    $team_id = substr( $owner, 6 );
                    
                    $case_holder['team'] = array(
                        'id' => (int)$team_id
                    );
                }
            }

            // Case links to a single party (person-over-org by default; filterable).
            $link_party_id = apply_filters( 'adfoin_capsulecrm_link_party_id', ( $person_id ? $person_id : $org_id ), $org_id, $person_id, 'case' );

            if( $link_party_id ) {
                $case_holder['party'] = array( 'id' => $link_party_id );
            }

            if( $opportunity_id ) {
                $case_holder['opportunity'] = array( 'id' => $opportunity_id );
            }

            if( isset( $case_data['expectedCloseOn'] ) && $case_data['expectedCloseOn'] ) {
                $case_holder['expectedCloseOn'] = adfoin_get_parsed_values( $case_data['expectedCloseOn'], $posted_data );
            }

            $case_holder   = array_filter( $case_holder );
            $case_response = adfoin_capsulecrm_request( $endpoint, $method, array( 'kase' => $case_holder ), $record, $cred_id );
            $case_body     = json_decode( wp_remote_retrieve_body( $case_response ), true );

            if( isset( $case_body['kase'], $case_body['kase']['id'] ) ) {
                $case_id = $case_body['kase']['id'];
            }
        }

        if( isset( $task_data['description'] ) && $task_data['description'] ) {
            $endpoint                   = 'tasks';
            $method                     = 'POST';
            $task_holder                = array();
            $task_holder['description'] = adfoin_get_parsed_values( $task_data['description'], $posted_data );

            if( $owner ) {
                if( substr( $owner, 0, 6 ) == 'user__' ) {
                    $user_id = substr( $owner, 6 );
                    
                    $task_holder['owner'] = array(
                        'id' => (int)$user_id
                    );
                }

                if( substr( $owner, 0, 6 ) == 'team__' ) {
                    $team_id = substr( $owner, 6 );
                    
                    $task_holder['team'] = array(
                        'id' => (int)$team_id
                    );
                }
            }

            if( $org_id ) {
                $task_holder['party'] = array( 'id' => $org_id );
            }

            if( $person_id ) {
                $task_holder['party'] = array( 'id' => $person_id );
            }

            if( isset( $task_data['dueOn'] ) && $task_data['dueOn'] ) {
                $task_holder['dueOn'] = adfoin_get_parsed_values( $task_data['dueOn'], $posted_data );
            }

            if( isset( $task_data['dueTime'] ) && $task_data['dueTime'] ) {
                $task_holder['dueTime'] = adfoin_get_parsed_values( $task_data['dueTime'], $posted_data );
            }

            if( isset( $task_data['category'] ) && $task_data['category'] ) {
                $category = adfoin_get_parsed_values( $task_data['category'], $posted_data );

                if( $category ) {
                    $task_holder['category'] = array(
                        'name' => $category
                    );
                }
            }

            $task_holder   = array_filter( $task_holder );
            $task_response = adfoin_capsulecrm_request( $endpoint, $method, array( 'task' => $task_holder ), $record, $cred_id );
            $task_body     = json_decode( wp_remote_retrieve_body( $task_response ), true );

            if( isset( $task_body['task'], $task_body['task']['id'] ) ) {
                $task_id = $task_body['task']['id'];
            }
        }
    }

    return;
}
 
/*
* Checks if Party exists
* @returns: Party ID if exists
*/

function adfoin_capsulecrm_party_exists( $name, $cred_id = '' ) {

    $name = trim( (string) $name );

    if( '' === $name ) {
        return false;
    }

    $endpoint = add_query_arg( array( 'q' => $name ), 'parties/search' );
    $response = adfoin_capsulecrm_request( $endpoint, 'GET', array(), array(), $cred_id );

    if( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) ) {
        return false;
    }

    $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
    $parties       = ( isset( $response_body['parties'] ) && is_array( $response_body['parties'] ) ) ? $response_body['parties'] : array();

    if( empty( $parties ) ) {
        return false;
    }

    // Capsule's /parties/search?q= is a FUZZY match across many fields, so the
    // first result is NOT guaranteed to be the record we asked for — taking it
    // blindly could update/tag the WRONG party. Verify the match exactly:
    //   - an email value must appear (case-insensitively) in emailAddresses;
    //   - a name value must equal the organisation name or the person's full name.
    $is_email = is_email( $name );

    foreach( $parties as $party ) {
        if( $is_email ) {
            if( ! empty( $party['emailAddresses'] ) && is_array( $party['emailAddresses'] ) ) {
                foreach( $party['emailAddresses'] as $email ) {
                    if( isset( $email['address'] ) && 0 === strcasecmp( trim( $email['address'] ), $name ) ) {
                        return $party['id'];
                    }
                }
            }
            continue;
        }

        $candidates = array();
        if( isset( $party['name'] ) ) {
            $candidates[] = $party['name'];
        }
        $first = isset( $party['firstName'] ) ? $party['firstName'] : '';
        $last  = isset( $party['lastName'] ) ? $party['lastName'] : '';
        if( $first || $last ) {
            $candidates[] = trim( $first . ' ' . $last );
        }

        foreach( $candidates as $candidate ) {
            if( 0 === strcasecmp( trim( (string) $candidate ), $name ) ) {
                return $party['id'];
            }
        }
    }

    return false;
}