<?php

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

function adfoin_agilecrm_actions( $actions ) {

    $actions['agilecrm'] = array(
        'title' => __( 'Agile CRM', 'advanced-form-integration' ),
        'tasks' => array(
            'add_contact' => __( 'Create New Contact/Deal/Note', 'advanced-form-integration' )
        )
    );

    return $actions;
}

/**
 * Get Agile CRM credentials by ID
 * 
 * @param string $cred_id Credential ID (optional, can be from $_POST)
 * @return array Array with 'api_key', 'email', 'subdomain' keys, or empty strings if not found
 */
function adfoin_agilecrm_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 = '';
    $user_email = '';
    $subdomain = '';

    if ( $cred_id ) {
        $credentials = adfoin_read_credentials( 'agilecrm' );
        foreach( $credentials as $single ) {
            if( $single['id'] == $cred_id ) {
                $api_key = $single['api_key'];
                $user_email = $single['email'];
                $subdomain = $single['subdomain'];
                break;
            }
        }
    } else {
        // Fallback to old options if no cred_id provided
        $api_key    = get_option( 'adfoin_agilecrm_api_key' ) ? get_option( 'adfoin_agilecrm_api_key' ) : '';
        $user_email = get_option( 'adfoin_agilecrm_email' ) ? get_option( 'adfoin_agilecrm_email' ) : '';
        $subdomain  = get_option( 'adfoin_agilecrm_subdomain' ) ? get_option( 'adfoin_agilecrm_subdomain' ) : '';
    }

    return array(
        'api_key'    => $api_key,
        'email'      => $user_email,
        'subdomain'  => $subdomain
    );
}

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

function adfoin_agilecrm_settings_tab( $providers ) {
    $providers['agilecrm'] = __( 'Agile CRM', 'advanced-form-integration' );

    return $providers;
}

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

function adfoin_agilecrm_settings_view( $current_tab ) {
    if( $current_tab != 'agilecrm' ) {
        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_agilecrm_api_key' );
    $old_email = get_option( 'adfoin_agilecrm_email' );
    $old_subdomain = get_option( 'adfoin_agilecrm_subdomain' );
    
    $existing_creds = adfoin_read_credentials( 'agilecrm' );

    if ( $old_api_key && $old_email && $old_subdomain && empty( $existing_creds ) ) {
        $new_cred = array(
            'id' => wp_generate_uuid4(),
            'title' => 'Default Account',
            'api_key' => $old_api_key,
            'email' => $old_email,
            'subdomain' => $old_subdomain
        );
        adfoin_save_credentials( 'agilecrm', array( $new_cred ) );
    }

    $fields = array(
        array(
            'name'          => 'subdomain',
            'label'         => __( 'Subdomain', 'advanced-form-integration' ),
            'type'          => 'text',
            'required'      => true,
            'placeholder'   => __( 'e.g., mycompany', 'advanced-form-integration' ),
            'description'   => __( 'If your URL is https://mycompany.agilecrm.com, enter "mycompany"', 'advanced-form-integration' ),
            'show_in_table' => true,
        ),
        array(
            'name'          => 'email',
            'label'         => __( 'User Email', 'advanced-form-integration' ),
            'type'          => 'text',
            'required'      => true,
            'placeholder'   => __( 'Your login email', 'advanced-form-integration' ),
            'show_in_table' => true,
        ),
        array(
            'name'          => 'api_key',
            'label'         => __( 'REST API Key', 'advanced-form-integration' ),
            'type'          => 'text',
            'required'      => true,
            'placeholder'   => __( 'Enter your REST API Key', 'advanced-form-integration' ),
            'mask'          => true,  // Mask API key in table
            'show_in_table' => true,
        ),
    );

    $instructions = '<ol class="afi-instructions-list">
            <li>' . __( 'Enter the Subdomain part of your Agile CRM URL (e.g., if URL is https://mycompany.agilecrm.com, enter "mycompany").', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Go to Admin Settings > Developers & API > copy REST API Key.', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Enter your User Email (login email).', 'advanced-form-integration' ) . '</li>
            <li>' . __( 'Click "Add Account" and save your credentials.', 'advanced-form-integration' ) . '</li>
        </ol>';

    ADFOIN_Account_Manager::render_settings_view( 'agilecrm', 'Agile CRM', $fields, $instructions );
}

// AJAX Hooks for Account Manager
add_action( 'wp_ajax_adfoin_get_agilecrm_credentials', 'adfoin_get_agilecrm_credentials' );
function adfoin_get_agilecrm_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( 'agilecrm' );
}

add_action( 'wp_ajax_adfoin_save_agilecrm_credentials', 'adfoin_save_agilecrm_credentials' );
function adfoin_save_agilecrm_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( 'agilecrm', array( 'subdomain', 'email', 'api_key' ) );
}

add_action( 'wp_ajax_adfoin_get_agilecrm_credentials_list', 'adfoin_agilecrm_get_credentials_list_ajax' );
function adfoin_agilecrm_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' => 'subdomain', 'mask' => false ),
        array( 'name' => 'email', 'mask' => false ),
        array( 'name' => 'api_key', 'mask' => true ),
    );

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


add_action( 'adfoin_action_fields', 'adfoin_agilecrm_action_fields' );

function adfoin_agilecrm_action_fields() {
    ?>
    <script type="text/template" id="agilecrm-action-template">
        <div>
            <table class="form-table">
                <tr valign="top" v-if="action.task == 'add_contact'">
                    <th scope="row"><?php esc_html_e( 'Agile CRM Account', 'advanced-form-integration' ); ?></th>
                    <td>
                        <select name="fieldData[credId]" v-model="fielddata.credId" @change="fetchPipelines">
                            <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=agilecrm' ); ?>" 
                           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>
                    </td>
                </tr>

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

                    </td>
                </tr>

                <tr class="alternate" v-if="action.task == 'add_contact'">
                    <td>
                        <label for="tablecell">
                            <?php esc_attr_e( 'Instructions', 'advanced-form-integration' ); ?>
                        </label>
                    </td>

                    <td>
                        <p><?php _e('This task will create Contact, Deal & Note. Leave blank Deal & Note fields if not needed', 'advanced-form-integration' );?></p>
                    </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_contact', 'Agile CRM [PRO]', 'tags & custom fields' ); ?>
            </table>
        </div>
    </script>

    <?php
}

add_action( 'wp_ajax_adfoin_get_agilecrm_pipelines', 'adfoin_get_agilecrm_pipelines', 10, 0 );

function adfoin_get_agilecrm_pipelines() {
    // Security Check
    adfoin_verify_nonce();

    $credentials = adfoin_agilecrm_get_credentials();
    $api_key     = $credentials['api_key'];
    $user_email  = $credentials['email'];
    $subdomain   = $credentials['subdomain'];

    if( !$api_key || !$subdomain || !$user_email ) {
        return;
    }

    $users     = "";
    $pipelines = "";
    $sources   = "";

    $args = array(
        "timeout" => 30,
        "headers" => array(
            'Content-Type'  => 'application/json',
            'Accept'        => 'application/json',
            'Authorization' => 'Basic ' . base64_encode( $user_email . ':' . $api_key )
        )
    );

    $user_url = "https://{$subdomain}.agilecrm.com/dev/api/users";

    $user_response = wp_remote_get( $user_url, $args );

    if( !is_wp_error( $user_response ) ) {
        $user_body = json_decode( wp_remote_retrieve_body( $user_response ) );

        foreach( $user_body as $single ) {
            $users .= $single->name . ': ' . $single->id . ' ';
        }
    }

    $url = "https://{$subdomain}.agilecrm.com/dev/api/milestone/pipelines";

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

    if( !is_wp_error( $response ) ) {
        $body = json_decode( wp_remote_retrieve_body( $response ) );

        if ( is_array( $body ) ) {
            foreach( $body as $single ) {
                $pipelines .= $single->name . ': ' . $single->id . ' ';
            }
        }

        $deal_fields = array(
            array( 'key' => 'dealName', 'value' => 'Name [Deal]', 'description' => 'Required for Deal creation' ),
            array( 'key' => 'dealValue', 'value' => 'Value [Deal]', 'description' => 'Required for Deal creation' ),
            array( 'key' => 'dealProbability', 'value' => 'Probability [Deal]', 'description' => 'Integer value' ),
            array( 'key' => 'dealCloseDate', 'value' => 'Close Date [Deal]', 'description' => 'Use YYYY-MM-DD format' ),
            array( 'key' => 'dealSource', 'value' => 'Source ID [Deal]', 'description' => '' ),
            array( 'key' => 'dealDescription', 'value' => 'Description [Deal]', 'description' => '' ),
            array( 'key' => 'dealTrack', 'value' => 'Track/Pipeline ID [Deal]', 'description' => $pipelines ),
            array( 'key' => 'dealMilestone', 'value' => 'Milestone [Deal]', 'description' => 'Example: New, Prospect, Proposal, Won, Lost' ),
            array( 'key' => 'dealOwner', 'value' => 'Owner ID [Deal]', 'description' => $users ),
            array( 'key' => 'noteSubject', 'value' => 'Subject [Note]', 'description' => '' ),
            array( 'key' => 'noteDescription', 'value' => 'Description [Note]', 'description' => '' ),

        );

        wp_send_json_success( $deal_fields );
    }

    wp_send_json_error( __( 'Could not fetch Agile CRM pipelines.', 'advanced-form-integration' ) );
}

/**
 * Canonical Agile CRM request helper. Defined here (free) so it is always
 * available; the Pro add-on reuses it. Resolves credentials from the record's
 * credId (falling back to legacy options), is method-aware, retries on HTTP 429
 * honouring Retry-After, and logs when a record is supplied.
 */
if ( ! function_exists( 'adfoin_agilecrm_request' ) ) {
    function adfoin_agilecrm_request( $endpoint, $method = 'GET', $data = array(), $record = array(), $retry_count = 0 ) {
        $cred_id = '';

        if ( is_array( $record ) && isset( $record['data'] ) ) {
            $record_data = json_decode( $record['data'], true );
            if ( is_array( $record_data ) && isset( $record_data['field_data']['credId'] ) ) {
                $cred_id = $record_data['field_data']['credId'];
            }
        }

        $credentials = adfoin_agilecrm_get_credentials( $cred_id );
        $api_key     = isset( $credentials['api_key'] ) ? $credentials['api_key'] : '';
        $user_email  = isset( $credentials['email'] ) ? $credentials['email'] : '';
        $subdomain   = isset( $credentials['subdomain'] ) ? $credentials['subdomain'] : '';

        if ( ! $api_key || ! $user_email || ! $subdomain ) {
            return new WP_Error( 'adfoin_agilecrm_missing_credentials', __( 'Agile CRM credentials not found.', 'advanced-form-integration' ) );
        }

        $endpoint = ltrim( $endpoint, '/' );
        $url      = "https://{$subdomain}.agilecrm.com/dev/api/{$endpoint}";

        $args = array(
            'timeout' => 30,
            'method'  => $method,
            'headers' => array(
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
                'Authorization' => 'Basic ' . base64_encode( $user_email . ':' . $api_key ),
            ),
        );

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

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

        // Retry on rate limiting (HTTP 429), honouring Retry-After.
        if ( ! is_wp_error( $response ) && 429 == wp_remote_retrieve_response_code( $response ) && $retry_count < 2 ) {
            $retry_after = (int) wp_remote_retrieve_header( $response, 'retry-after' );
            $retry_after = ( $retry_after > 0 && $retry_after <= 10 ) ? $retry_after : 3;
            sleep( $retry_after );

            return adfoin_agilecrm_request( $endpoint, $method, $data, $record, $retry_count + 1 );
        }

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

        return $response;
    }
}

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

function adfoin_agilecrm_job_queue( $data ) {
    adfoin_agilecrm_send_data( $data['record'], $data['posted_data'] );
}

/*
 * Handles sending data to Agile CRM API
 */
function adfoin_agilecrm_send_data( $record, $posted_data ) {

    $record_data = json_decode( $record['data'], true );
    $field_data = isset( $record_data['field_data'] ) ? $record_data['field_data'] : array();
    
    $cred_id = isset( $field_data['credId'] ) ? $field_data['credId'] : '';
    
    $credentials = adfoin_agilecrm_get_credentials( $cred_id );
    $api_key     = $credentials['api_key'];
    $user_email  = $credentials['email'];
    $subdomain   = $credentials['subdomain'];

    if( !$api_key || !$subdomain || !$user_email ) {
        return;
    }

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

    $data       = $record_data['field_data'];
    $task       = $record['task'];
    $email      = empty( $data['email'] ) ? '' : adfoin_get_parsed_values( $data['email'], $posted_data );
    $first_name = empty( $data['firstName'] ) ? '' : adfoin_get_parsed_values( $data['firstName'], $posted_data );
    $last_name  = empty( $data['lastName'] ) ? '' : adfoin_get_parsed_values( $data['lastName'], $posted_data );
    $title      = empty( $data['title'] ) ? '' : adfoin_get_parsed_values( $data['title'], $posted_data );
    $company    = empty( $data['company'] ) ? '' : adfoin_get_parsed_values( $data['company'], $posted_data );
    $phone      = empty( $data['phone'] ) ? '' : adfoin_get_parsed_values( $data['phone'], $posted_data );
    $address    = empty( $data['address'] ) ? '' : adfoin_get_parsed_values( $data['address'], $posted_data );
    $city       = empty( $data['city'] ) ? '' : adfoin_get_parsed_values( $data['city'], $posted_data );
    $state      = empty( $data['state'] ) ? '' : adfoin_get_parsed_values( $data['state'], $posted_data );
    $zip        = empty( $data['zip'] ) ? '' : adfoin_get_parsed_values( $data['zip'], $posted_data );
    $country    = empty( $data['country'] ) ? '' : adfoin_get_parsed_values( $data['country'], $posted_data );
    $deal_name  = empty( $data['dealName'] ) ? '' : adfoin_get_parsed_values( $data['dealName'], $posted_data );
    $note_sub   = empty( $data['noteSubject'] ) ? '' : adfoin_get_parsed_values( $data['noteSubject'], $posted_data );
    $note_desc  = empty( $data['noteDescription'] ) ? '' : adfoin_get_parsed_values( $data['noteDescription'], $posted_data );

    if( $task == 'add_contact' ) {

        $body = array( 'properties' => array() );

        if ( $first_name ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'first_name', 'value' => $first_name );
        }

        if ( $last_name ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'last_name', 'value' => $last_name );
        }

        if ( $email ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'email', 'value' => $email );
        }

        if ( $title ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'title', 'value' => $title );
        }

        if ( $company ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'company', 'value' => $company );
        }

        if ( $phone ) {
            $body['properties'][] = array( 'type' => 'SYSTEM', 'name' => 'phone', 'value' => $phone );
        }

        if ( $address || $city || $state || $zip || $country ) {
            $body['properties'][] = array(
                'name'  => 'address',
                'value' => wp_json_encode( array_filter( array(
                    'address'     => $address,
                    'city'        => $city,
                    'state'       => $state,
                    'zip'         => $zip,
                    'countryname' => $country,
                ) ) ),
            );
        }

        // Find an existing contact by email (update) or create a new one.
        $contact_id = '';

        if ( $email ) {
            $search = adfoin_agilecrm_request( 'contacts/search/email/' . urlencode( $email ), 'GET', array(), $record );

            if ( ! is_wp_error( $search ) && 200 === wp_remote_retrieve_response_code( $search ) ) {
                $search_body = json_decode( wp_remote_retrieve_body( $search ) );
                if ( isset( $search_body->id ) ) {
                    $contact_id = $search_body->id;
                }
            }
        }

        if ( $contact_id ) {
            adfoin_agilecrm_request( 'contacts/edit-properties', 'PUT', array_merge( $body, array( 'id' => $contact_id ) ), $record );
        } else {
            $response = adfoin_agilecrm_request( 'contacts', 'POST', $body, $record );

            if ( ! is_wp_error( $response ) ) {
                $response_body = json_decode( wp_remote_retrieve_body( $response ) );
                if ( isset( $response_body->id ) ) {
                    $contact_id = $response_body->id;
                }
            }
        }

        if ( ! $contact_id ) {
            return;
        }

        if( $deal_name ) {
            $deal_value       = empty( $data['dealValue'] ) ? '' : adfoin_get_parsed_values( $data['dealValue'], $posted_data );
            $deal_probability = empty( $data['dealProbability'] ) ? '' : adfoin_get_parsed_values( $data['dealProbability'], $posted_data );
            $deal_close_date  = empty( $data['dealCloseDate'] ) ? '' : strtotime( adfoin_get_parsed_values( $data['dealCloseDate'], $posted_data ) );
            $deal_source      = empty( $data['dealSource'] ) ? '' : adfoin_get_parsed_values( $data['dealSource'], $posted_data );
            $deal_description = empty( $data['dealDescription'] ) ? '' : adfoin_get_parsed_values( $data['dealDescription'], $posted_data );
            $deal_track       = empty( $data['dealTrack'] ) ? '' : adfoin_get_parsed_values( $data['dealTrack'], $posted_data );
            $deal_milestone   = empty( $data['dealMilestone'] ) ? '' : adfoin_get_parsed_values( $data['dealMilestone'], $posted_data );
            $deal_owner       = empty( $data['dealOwner'] ) ? '' : adfoin_get_parsed_values( $data['dealOwner'], $posted_data );

            $deal_body = array_filter( array(
                'name'           => $deal_name,
                'contact_ids'    => array( $contact_id ),
                'expected_value' => $deal_value,
                'owner_id'       => $deal_owner,
                'pipeline_id'    => $deal_track,
                'milestone'      => $deal_milestone,
                'description'    => $deal_description,
                'probability'    => intval( $deal_probability ),
                'close_date'     => $deal_close_date,
                'deal_source_id' => $deal_source,
            ) );

            adfoin_agilecrm_request( 'opportunity', 'POST', $deal_body, $record );
        }

        if( $note_sub ) {
            $note_body = array(
                'subject'     => $note_sub,
                'description' => $note_desc,
                'contact_ids' => array( $contact_id ),
            );

            adfoin_agilecrm_request( 'notes', 'POST', $note_body, $record );
        }

    }

    return;
}