<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
// OAuth redirect callback handler for configured connection providers.
if ( isset( $_GET['code'] ) && ! empty( $_GET['code'] ) ) {
    $oauth_code  = sanitize_text_field( wp_unslash( $_GET['code'] ) );
    $oauth_state = isset( $_GET['state'] ) ? sanitize_key( wp_unslash( $_GET['state'] ) ) : 'googlesheet';
    $configure_app = '';
    $configure_status = 'fail';

    switch ( $oauth_state ) {
        case 'salesforce':
            $configure_app = 'salesforce';
            $configure_status = SftcyWordformConnectSalesforce::wordform_connect_configure_salesforce_authentication( $oauth_code ) ? 'success' : 'fail';
            break;
        case 'zohocrm':
            $configure_app = 'zohocrm';
            $configure_status = SftcyWordformConnectZohocrm::wordform_connect_configure_zohocrm_authentication( $oauth_code ) ? 'success' : 'fail';
            break;
        case 'googlecalendar':
            $configure_app = 'googlecalendar';
            $configure_status = SftcyWordformConnectGooglecalendar::wordform_connect_configure_googlecalendar_authentication( $oauth_code ) ? 'success' : 'fail';
            break;
        case 'googlesheet':
        default:
            $configure_app = 'googlesheet';
            $configure_status = SftcyWordformConnectGooglesheet::wordform_connect_configure_google_authentication( $oauth_code ) ? 'success' : 'fail';
            break;
    }

    wp_redirect( admin_url( 'admin.php?page=wordform-connects&configure=' . $configure_app . '&status=' . $configure_status ) );
    exit();
}

// Get Google Credentials
$credentials = SftcyWordformConnectGooglesheet::get_google_credentials();
$google_client_id = array_filter( $credentials ) && isset( $credentials['clientID'] ) && ! empty( $credentials['clientID'] )? $credentials['clientID'] : '';
$google_client_secret = array_filter( $credentials ) && isset( $credentials['clientSecret'] ) && ! empty( $credentials['clientSecret'] )? $credentials['clientSecret'] : '';
// echo '<pre>';
// print_r( $credentials );
// echo '</pre>';

include_once SFTCY_WORDFORM_PLUGIN_DIR . 'admin/views/pages-header-template.php';
$wordform_upgrade_url = class_exists( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_get_upgrade_url() : 'https://softcoy.com/products/wordform-pro/checkout';

// If configured applications re-authentication requires or expires for a certain period not using the app then 'configured_status' change to 'inactive'
// to stop showing application name into select Application name dropdown menu
// Check Application Name: Google Sheet
if ( SftcyWordformConnectGooglesheet::is_google_authencation_required() ) {
    $application_slug = 'googlesheet';
    SftcyWordformBase::wordform_check_n_change_configured_status_applications( $application_slug );
}
if ( class_exists( 'SftcyWordformConnectGooglecalendar' ) && SftcyWordformConnectGooglecalendar::is_googlecalendar_authentication_required() ) {
    SftcyWordformBase::wordform_check_n_change_configured_status_applications( 'googlecalendar' );
}
if ( class_exists( 'SftcyWordformConnectSalesforce' ) && SftcyWordformConnectSalesforce::is_salesforce_authentication_required() ) {
    SftcyWordformBase::wordform_check_n_change_configured_status_applications( 'salesforce' );
}
if ( class_exists( 'SftcyWordformConnectZohocrm' ) && SftcyWordformConnectZohocrm::is_zohocrm_authentication_required() ) {
    SftcyWordformBase::wordform_check_n_change_configured_status_applications( 'zohocrm' );
}

// Get Zapier Info
$zapier_info = SftcyWordformConnectZapier::get_zapier_webhook_url();		
$zapier_webhook_url = isset( $zapier_info['webhookPostUrl'] )? $zapier_info['webhookPostUrl'] : '';	

// Get Custom Webhook Info
$custom_webhook_info = SftcyWordformConnectCustomWebhook::get_custom_webhook_url();
$custom_webhook_url = isset( $custom_webhook_info['webhookPostUrl'] ) ? $custom_webhook_info['webhookPostUrl'] : '';
$all_created_forms = SftcyWordformBase::sc_wordform_get_all_created_forms_data();
$connect_applications = SftcyWordformConnectBase::get_connects_page_applications_registry();
$all_configured_applications = SftcyWordformBase::wordform_get_all_configured_application_names();
$connection_ready_slugs = array();
if ( isset( $connect_applications ) && is_array( $connect_applications ) ) {
    foreach ( $connect_applications as $application ) {
        if ( ! empty( $application['slug'] ) && ! empty( $application['is_configured'] ) && ! empty( $application['is_active'] ) && ! empty( $application['is_available'] ) ) {
            $connection_ready_slugs[] = sanitize_key( $application['slug'] );
        }
    }
}
$connection_ready_slugs = array_values( array_unique( array_filter( $connection_ready_slugs ) ) );
$all_configured_applications = array_values(
    array_filter(
        $all_configured_applications,
        static function( $configured_application_row ) use ( $connection_ready_slugs ) {
            $application_slug = isset( $configured_application_row['application_slug'] ) ? sanitize_key( $configured_application_row['application_slug'] ) : '';
            return ! empty( $application_slug ) && in_array( $application_slug, $connection_ready_slugs, true );
        }
    )
);
$configured_application_options_by_slug = array();
if ( isset( $all_configured_applications ) && array_filter( $all_configured_applications ) ) {
    foreach ( $all_configured_applications as $configured_application_row ) {
        if ( empty( $configured_application_row['application_slug'] ) ) {
            continue;
        }

        $configured_application_options_by_slug[ sanitize_key( $configured_application_row['application_slug'] ) ] = array(
            'id'   => isset( $configured_application_row['id'] ) ? absint( $configured_application_row['id'] ) : 0,
            'name' => isset( $configured_application_row['application_name'] ) ? sanitize_text_field( $configured_application_row['application_name'] ) : '',
        );
    }
}
$connects_grid_columns = 3;
$connect_application_groups = array();
foreach ( $connect_applications as $application ) {
    $group_key = ! empty( $application['category'] ) ? sanitize_key( $application['category'] ) : 'other';
    $group_label = ! empty( $application['category_label'] ) ? sanitize_text_field( $application['category_label'] ) : __( 'Other', 'wordform-pro' );

    if ( ! isset( $connect_application_groups[ $group_key ] ) ) {
        $connect_application_groups[ $group_key ] = array(
            'label' => $group_label,
            'apps'  => array(),
        );
    }

    $connect_application_groups[ $group_key ]['apps'][] = $application;
}
$connect_application_filters = array( 'all' => __( 'All Categories', 'wordform-pro' ) );
foreach ( $connect_application_groups as $group_key => $group_data ) {
    $connect_application_filters[ $group_key ] = $group_data['label'];
}
$selected_connection_status_form_id = isset( $_GET['connection_status_form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['connection_status_form_id'] ) ) : '';
$selected_connection_status_application_slug = isset( $_GET['connection_status_application_slug'] ) ? sanitize_key( wp_unslash( $_GET['connection_status_application_slug'] ) ) : '';
$connection_status_rows = SftcyWordformConnectBase::get_connection_status_report_rows( $selected_connection_status_form_id, $selected_connection_status_application_slug );
$show_connection_status_tab = true;
$connection_status_available = class_exists( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_is_feature_available( 'connection_send_logs' ) : true;

$render_connection_status_badge = static function( $status_label = '', $status_key = '' ) {
    $status_key   = sanitize_html_class( $status_key );
    $status_label = esc_html( $status_label );

    return '<span class="wordform-connection-status-pill wordform-connection-status-pill-' . $status_key . '">' . $status_label . '</span>';
};

?>
<div class="wrap" style="margin: 1%;">
    <div id="tabs" class="sc-wordform-tabs-wrapper-div" style="display: none;">
        <ul>
            <li><a href="#scWordFormConnections" style="font-weight: bold;"><i class="fa-brands fa-connectdevelop"></i>&nbsp;<?php esc_html_e( 'Connections', 'wordform-pro' ); ?></a></li>
            <?php if ( $show_connection_status_tab ) { ?>
            <li class="<?php echo $connection_status_available ? '' : 'wordform-pro-locked-nav'; ?>">
                <a href="#scWordFormConnectionStatus" style="font-weight: bold;" class="<?php echo $connection_status_available ? '' : 'wordform-pro-locked-tab-link'; ?>" <?php if ( ! $connection_status_available ) { ?>data-upgrade-url="<?php echo esc_url( $wordform_upgrade_url ); ?>" title="<?php esc_attr_e( 'Get Pro', 'wordform' ); ?>"<?php } ?>><i class="fa-solid fa-tower-broadcast"></i>&nbsp;<?php esc_html_e( 'Connection Status', 'wordform-pro' ); ?></a>
            </li>
            <?php } ?>
        </ul>

        <div id="scWordFormConnections">
            <h2><i class="fa-brands fa-connectdevelop fa-fade fa-2xl" style="color: #74C0FC;"></i> WordForm Connects</h2>

            <!-- Start WordForm Connect Form -->
            <div class="wordform-connection-create-panel" id="WordFormConnectionCreatePanel">
                <div class="wordform-connection-create-panel-head">
                    <div>
                        <h3><?php esc_html_e( 'Create Connection', 'wordform-pro' ); ?></h3>
                        <p><?php esc_html_e( 'Choose a form and a configured application, then create the live data handoff between them.', 'wordform-pro' ); ?></p>
                    </div>
                    <span class="wordform-connection-create-panel-badge"><i class="fa-solid fa-diagram-project"></i> <?php esc_html_e( '2-Step Setup', 'wordform-pro' ); ?></span>
                </div>
                <div class="wordform-connection-create-flow">
                    <div class="wordform-connection-create-step wordform-connection-select-form-name-td">
                        <div class="wordform-connection-step-chip"><?php esc_html_e( 'Step 1', 'wordform-pro' ); ?></div>
                        <h4><?php esc_html_e( 'Select Form', 'wordform-pro' ); ?></h4>
                        <p><?php esc_html_e( 'Pick the WordForm that should send submission data to an application.', 'wordform-pro' ); ?></p>
                        <div class="wordform-connection-select-form-name-warpper-div">
                            <select id="WordFormConnectSelectForm" name="wordform-connect-selected-form">
                                <option value=""><?php esc_html_e( 'Select Form', 'wordform-pro' ); ?></option>
                                <?php
                                if ( isset( $all_created_forms ) && array_filter( $all_created_forms ) ) {
                                    foreach ( $all_created_forms as $data ) {
                                        echo '<option value="' . esc_attr( $data['form_id'] ) . '">' . esc_html( $data['form_name'] ) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="wordform-connection-create-step wordform-connection-select-connection-name-td">
                        <div class="wordform-connection-step-chip"><?php esc_html_e( 'Step 2', 'wordform-pro' ); ?></div>
                        <h4><?php esc_html_e( 'Select Application', 'wordform-pro' ); ?></h4>
                        <p><?php esc_html_e( 'Choose one configured application that is ready to receive your submission data.', 'wordform-pro' ); ?></p>
                        <select id="WordFormSelectConnectionName" name="wordform-select-connection-name">
                            <option value=""><?php esc_html_e( 'Select Application', 'wordform-pro' ); ?></option>
                            <?php
                            if ( isset( $all_configured_applications ) && array_filter( $all_configured_applications ) ) {
                                foreach ( $all_configured_applications as $data ) {
                                    echo '<option value="' . esc_attr( $data['id'] ) . '" data-application-slug = "' . $data['application_slug'] . '" >' . esc_html( $data['application_name'] ) . '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <div class="wordform-connection-create-action wordform-connection-arrow-hints-icon-wrapper-td">
                        <div class="wordform-connection-arrow-hints-icon">
                            <span class="wordform-connection-create-icon">
                                <span class="wordform-connection-create-icon-shell">
                                    <svg xmlns="http://www.w3.org/2000/svg" height="64" width="64" viewBox="0 0 512 512"><path fill="#ff5733" d="M0 256a256 256 0 1 0 512 0A256 256 0 1 0 0 256zm395.3 11.3l-112 112c-4.6 4.6-11.5 5.9-17.4 3.5s-9.9-8.3-9.9-14.8l0-64-96 0c-17.7 0-32-14.3-32-32l0-32c0-17.7 14.3-32 32-32l96 0 0-64c0-6.5 3.9-12.3 9.9-14.8s12.9-1.1 17.4 3.5l112 112c6.2 6.2 6.2 16.4 0 22.6z"/></svg>
                                </span>
                                <button class="button button-primary"><i class="fa-brands fa-connectdevelop"></i> <?php esc_html_e( 'Create Connection', 'wordform-pro' ); ?></button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- End WordForm Connect Form -->

            <!-- Horizontal Divider -->
            <div class="wordform-horizontal-divider-1"></div>

            <!-- Start Configure Third-party Applications Modal Contents-->
            <div class="wordform-connect-configure-toolbar">
                <div class="wordform-connection-application-search-wrapper" data-no-results-label="<?php esc_attr_e( 'No matching application found', 'wordform-pro' ); ?>">
                    <span class="dashicons dashicons-search" aria-hidden="true"></span>
                    <input type="search" id="WordFormConfigureApplicationSearch" name="wordform-configure-application-search" placeholder="<?php esc_attr_e( 'Search applications to configure', 'wordform-pro' ); ?>" autocomplete="off" />
                </div>
                <div class="wordform-connect-category-filter-group" aria-label="<?php esc_attr_e( 'Filter application categories', 'wordform-pro' ); ?>">
                    <?php foreach ( $connect_application_filters as $filter_key => $filter_label ) { ?>
                        <button
                            type="button"
                            class="button button-secondary wordform-connect-category-filter<?php echo 'all' === $filter_key ? ' is-active' : ''; ?>"
                            data-category-filter="<?php echo esc_attr( $filter_key ); ?>"
                        ><?php echo esc_html( $filter_label ); ?></button>
                    <?php } ?>
                </div>
                <p class="description"><?php esc_html_e( 'Search by application name to quickly find the card you want to configure.', 'wordform-pro' ); ?></p>
            </div>
            <div id="WordFormConfigureApplicationSearchEmptyState" class="wordform-configure-search-empty-state" style="display:none;">
                <p><?php esc_html_e( 'No matching application found.', 'wordform-pro' ); ?></p>
            </div>
            <div class="wordform-connect-page-configure-applications-table">
                <div class="wordform-configure-applications-th"><i class="fa-solid fa-gears"></i> Configure Applications</div>
                <?php foreach ( $connect_application_groups as $group_key => $group_data ) {
                    $group_rows = array_chunk( $group_data['apps'], $connects_grid_columns, true );
                ?>
                    <div class="wordform-connect-application-group" data-category-group="<?php echo esc_attr( $group_key ); ?>">
                        <div class="wordform-connect-application-group-head">
                            <h3><?php echo esc_html( $group_data['label'] ); ?></h3>
                            <span class="wordform-connect-application-group-count"><?php echo esc_html( count( $group_data['apps'] ) ); ?></span>
                        </div>
                        <table class="table-width-100">
                            <tbody>
                                <?php foreach ( $group_rows as $application_row ) { ?>
                                <tr class="wordform-connect-application-row">
                                    <?php foreach ( $application_row as $application ) { ?>
                                    <?php $is_available_card = array_key_exists( 'is_available', $application ) ? ! empty( $application['is_available'] ) : true; ?>
                                    <td class="wordform-connect-application-card<?php echo $is_available_card ? '' : ' wordform-pro-locked-card-surface'; ?>" data-application-name="<?php echo esc_attr( strtolower( $application['name'] ) ); ?>" data-application-slug="<?php echo esc_attr( $application['slug'] ); ?>" data-application-category="<?php echo esc_attr( $group_key ); ?>" data-feature-available="<?php echo $is_available_card ? 'yes' : 'no'; ?>">
                                        <span class="wordform-connect-application-card-badge"><?php echo esc_html( $group_data['label'] ); ?></span>
                                        <h2><?php echo esc_html( $application['name'] ); ?></h2>
                                        <div data-thirdparty-program-name="<?php echo esc_attr( $application['program_name'] ); ?>" data-upgrade-url="<?php echo esc_url( $wordform_upgrade_url ); ?>" data-feature-available="<?php echo $is_available_card ? 'yes' : 'no'; ?>" class="third-party-connect-library<?php echo $is_available_card ? '' : ' wordform-pro-locked-trigger'; ?>">
                                            <span>
                                                <span class="dashicons <?php echo $is_available_card ? 'dashicons-admin-links apps-configure-reconfigure-label' : 'dashicons-lock'; ?>" aria-hidden="true"></span>
                                                <?php echo $is_available_card ? esc_html__( 'Configure / Reconfigure', 'wordform-pro' ) : esc_html__( 'Get Pro', 'wordform' ); ?>
                                            </span>
                                            <?php echo $application['icon_html']; ?>
                                        </div>
                                        <?php
                                        $is_configured_card = ! empty( $application['is_configured'] );
                                        $is_active_card     = ! empty( $application['is_active'] );
                                        $is_connection_ready = $is_available_card && $is_active_card && isset( $configured_application_options_by_slug[ $application['slug'] ] );
                                        ?>
                                        <div class="wordform-connect-card-health-summary">
                                            <div class="wordform-connect-card-health-row">
                                                <span class="wordform-connect-card-health-label"><?php esc_html_e( 'Setup', 'wordform-pro' ); ?></span>
                                                <span class="wordform-connect-card-health-value <?php echo $is_available_card ? ( $is_configured_card ? 'is-good' : 'is-warning' ) : 'is-muted'; ?>">
                                                    <i class="fa-solid <?php echo $is_available_card ? ( $is_configured_card ? 'fa-circle-check' : 'fa-wrench' ) : 'fa-lock'; ?>"></i>
                                                    <?php echo esc_html( $is_available_card ? ( $is_configured_card ? __( 'Ready', 'wordform-pro' ) : __( 'Needs Setup', 'wordform-pro' ) ) : __( 'Pro only', 'wordform' ) ); ?>
                                                </span>
                                            </div>
                                            <div class="wordform-connect-card-health-row">
                                                <span class="wordform-connect-card-health-label"><?php esc_html_e( 'Status', 'wordform-pro' ); ?></span>
                                                <span class="wordform-connect-card-health-value <?php echo $is_available_card ? ( $is_active_card ? 'is-good' : ( $is_configured_card ? 'is-muted' : 'is-warning' ) ) : 'is-muted'; ?>">
                                                    <i class="fa-solid <?php echo $is_available_card ? ( $is_active_card ? 'fa-bolt' : ( $is_configured_card ? 'fa-pause-circle' : 'fa-circle-minus' ) ) : 'fa-lock'; ?>"></i>
                                                    <?php
                                                    echo esc_html(
                                                        $is_available_card
                                                            ? ( $is_active_card
                                                            ? __( 'Active', 'wordform-pro' )
                                                            : ( $is_configured_card ? __( 'Inactive', 'wordform-pro' ) : __( 'Not Ready', 'wordform-pro' ) ) )
                                                            : __( 'Locked', 'wordform' )
                                                    );
                                                    ?>
                                                </span>
                                            </div>
                                            <div class="wordform-connect-card-health-row">
                                                <span class="wordform-connect-card-health-label"><?php esc_html_e( 'Connection', 'wordform-pro' ); ?></span>
                                                <span class="wordform-connect-card-health-value <?php echo $is_connection_ready ? 'is-good' : 'is-muted'; ?>">
                                                    <i class="fa-solid <?php echo $is_connection_ready ? 'fa-diagram-project' : ( $is_available_card ? 'fa-arrow-right' : 'fa-arrow-up-right-from-square' ); ?>"></i>
                                                    <?php echo esc_html( $is_available_card ? ( $is_connection_ready ? __( 'Connection Ready', 'wordform-pro' ) : __( 'Configure First', 'wordform-pro' ) ) : __( 'Upgrade to unlock', 'wordform' ) ); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="wordform-connect-card-actions">
                                        <?php
                                        if ( ! $is_available_card ) {
                                            echo '<a class="button button-primary wordform-pro-locked-button" href="' . esc_url( $wordform_upgrade_url ) . '" target="_blank" rel="noopener" data-upgrade-url="' . esc_url( $wordform_upgrade_url ) . '" title="' . esc_attr__( 'Get Pro', 'wordform' ) . '">' . esc_html__( 'Get Pro', 'wordform' ) . '</a>';
                                        } elseif ( $is_configured_card ) {
                                            if ( $is_active_card ) {
                                                if ( isset( $configured_application_options_by_slug[ $application['slug'] ] ) ) {
                                                    $configured_option = $configured_application_options_by_slug[ $application['slug'] ];
                                                    echo '<button class="button button-primary wordform-use-configured-application-btn" data-application-id="' . esc_attr( $configured_option['id'] ) . '" data-application-name="' . esc_attr( $configured_option['name'] ) . '" data-application-slug="' . esc_attr( $application['slug'] ) . '"><i class="fa-solid fa-arrow-up-right-from-square"></i> ' . esc_html__( 'Use in Create Connection', 'wordform-pro' ) . '</button>';
                                                }
                                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="' . esc_attr( $application['slug'] ) . '" data-application-name="' . esc_attr( $application['name'] ) . '" data-application-status-change-to="inactive"><i class="fa-solid fa-link-slash"></i> ' . esc_html__( 'Deactivate', 'wordform-pro' ) . '</button>';
                                            } else {
                                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="' . esc_attr( $application['slug'] ) . '" data-application-name="' . esc_attr( $application['name'] ) . '" data-application-status-change-to="active"><i class="fa-solid fa-link"></i> ' . esc_html__( 'Activate', 'wordform-pro' ) . '</button>';
                                            }
                                        }
                                        ?>
                                        </div>
                                    </td>
                                    <?php } ?>
                                    <?php if ( count( $application_row ) < $connects_grid_columns ) {
                                        for ( $index = count( $application_row ); $index < $connects_grid_columns; $index++ ) {
                                            echo '<td class="wordform-connect-empty-state"></td>';
                                        }
                                    } ?>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                <?php } ?>
            </div>
            <!-- End Configure Third-party Applications Modal Contents-->
        </div>

        <?php if ( $show_connection_status_tab ) { ?>
        <div id="scWordFormConnectionStatus">
            <h3><i class="fa-solid fa-tower-broadcast"></i>&nbsp;<?php esc_html_e( 'Connection Status', 'wordform-pro' ); ?></h3>
            <p><?php esc_html_e( 'Review application configuration, per-form connection state, and the latest send result for each connected app.', 'wordform-pro' ); ?></p>
            <?php if ( ! $connection_status_available ) { ?>
                <div class="wordform-pro-locked-panel">
                    <div class="wordform-pro-locked-panel-head">
                        <div>
                            <h3><?php esc_html_e( 'Connection send logs are available in WordForm Pro', 'wordform' ); ?></h3>
                            <p><?php esc_html_e( 'Unlock form-by-form integration send history, failure drill-downs, and faster troubleshooting for live connected apps.', 'wordform' ); ?></p>
                        </div>
                        <span class="wordform-pro-preview-badge"><?php esc_html_e( 'Pro', 'wordform' ); ?></span>
                    </div>
                    <div class="wordform-pro-preview-frame">
                        <div class="wordform-pro-demo-shell">
                            <div class="wordform-connection-status-toolbar wordform-connection-status-toolbar-panel">
                                <div class="wordform-connection-status-filter-grid">
                                    <div class="wordform-connection-status-filter">
                                        <label><strong><?php esc_html_e( 'Filter by Form', 'wordform' ); ?></strong></label><br/>
                                        <div class="wordform-pro-demo-input"><?php esc_html_e( 'All Forms', 'wordform' ); ?></div>
                                    </div>

                                    <div class="wordform-connection-status-filter">
                                        <label><strong><?php esc_html_e( 'Filter by Application', 'wordform' ); ?></strong></label><br/>
                                        <div class="wordform-pro-demo-input"><?php esc_html_e( 'All Applications', 'wordform' ); ?></div>
                                    </div>

                                    <div class="wordform-connection-status-filter wordform-connection-status-filter-summary">
                                        <h4><?php esc_html_e( 'Current View', 'wordform' ); ?></h4>
                                        <p class="description"><?php esc_html_e( 'Showing all forms with all configured applications.', 'wordform' ); ?></p>
                                        <p class="description"><?php esc_html_e( 'Changing any filter keeps the Connection Status tab in view.', 'wordform' ); ?></p>
                                    </div>
                                </div>
                            </div>
                            <table class="display hover stripe wp-list-table widefat fixed striped table-view-list wordform-pro-demo-table">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e( 'Form Name', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Form ID', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Application', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Configured Status', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Connection Status', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Data Send Status', 'wordform' ); ?></th>
                                        <th><?php esc_html_e( 'Latest Submission', 'wordform' ); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><?php esc_html_e( 'Lead Capture', 'wordform' ); ?></td>
                                        <td><code>wordform-17</code></td>
                                        <td>Google Sheets</td>
                                        <td><?php esc_html_e( 'Ready', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( 'Connected', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( 'Success', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( '2026-04-08 09:48', 'wordform' ); ?></td>
                                    </tr>
                                    <tr>
                                        <td><?php esc_html_e( 'Event Booking', 'wordform' ); ?></td>
                                        <td><code>wordform-23</code></td>
                                        <td>Slack</td>
                                        <td><?php esc_html_e( 'Ready', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( 'Connected', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( 'Failed', 'wordform' ); ?></td>
                                        <td><?php esc_html_e( '2026-04-08 08:16', 'wordform' ); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <a class="wordform-pro-preview-overlay wordform-pro-locked-button" href="<?php echo esc_url( $wordform_upgrade_url ); ?>" target="_blank" rel="noopener" data-upgrade-url="<?php echo esc_url( $wordform_upgrade_url ); ?>" title="<?php esc_attr_e( 'Get Pro', 'wordform' ); ?>">
                            <span class="wordform-pro-preview-overlay-chip"><?php esc_html_e( 'Get Pro', 'wordform' ); ?></span>
                            <strong><?php esc_html_e( 'Unlock live connection status history', 'wordform' ); ?></strong>
                            <small><?php esc_html_e( 'Inspect delivery success, failures, retries, and per-app troubleshooting from the full Pro dashboard.', 'wordform' ); ?></small>
                        </a>
                    </div>
                </div>
            <?php } else { ?>
            <div class="wordform-connection-status-toolbar wordform-connection-status-toolbar-panel">
                <div class="wordform-connection-status-filter-grid">
                    <div class="wordform-connection-status-filter">
                        <label for="WordFormConnectionStatusSelectForm"><strong><?php esc_html_e( 'Filter by Form', 'wordform-pro' ); ?></strong></label><br/>
                        <select id="WordFormConnectionStatusSelectForm" name="wordform-connection-status-selected-form">
                            <option value=""><?php esc_html_e( 'All Forms', 'wordform-pro' ); ?></option>
                            <?php
                            if ( isset( $all_created_forms ) && array_filter( $all_created_forms ) ) {
                                foreach ( $all_created_forms as $data ) {
                                    echo '<option value="' . esc_attr( $data['form_id'] ) . '" ' . selected( $selected_connection_status_form_id, $data['form_id'], false ) . '>' . esc_html( $data['form_name'] ) . '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>

                    <div class="wordform-connection-status-filter">
                        <label for="WordFormConnectionStatusSelectApplication"><strong><?php esc_html_e( 'Filter by Application', 'wordform-pro' ); ?></strong></label><br/>
                        <select id="WordFormConnectionStatusSelectApplication" name="wordform-connection-status-selected-application">
                            <option value=""><?php esc_html_e( 'All Applications', 'wordform-pro' ); ?></option>
                            <?php
                            foreach ( $connect_applications as $application ) {
                                echo '<option value="' . esc_attr( $application['slug'] ) . '" ' . selected( $selected_connection_status_application_slug, $application['slug'], false ) . '>' . esc_html( $application['name'] ) . '</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <div class="wordform-connection-status-filter wordform-connection-status-filter-summary">
                        <h4><?php esc_html_e( 'Current View', 'wordform-pro' ); ?></h4>
                        <p class="description">
                            <?php
                            $selected_form_summary = __( 'All Forms', 'wordform-pro' );
                            if ( ! empty( $selected_connection_status_form_id ) && ! empty( $all_created_forms ) ) {
                                foreach ( $all_created_forms as $form_data ) {
                                    if ( isset( $form_data['form_id'] ) && $form_data['form_id'] === $selected_connection_status_form_id ) {
                                        $selected_form_summary = sprintf(
                                            '%1$s ( %2$s )',
                                            sanitize_text_field( $form_data['form_name'] ),
                                            sanitize_text_field( $form_data['form_id'] )
                                        );
                                        break;
                                    }
                                }
                            }
                            $selected_app_summary  = ! empty( $selected_connection_status_application_slug ) && isset( $connect_applications[ $selected_connection_status_application_slug ] ) ? $connect_applications[ $selected_connection_status_application_slug ]['name'] : __( 'All Applications', 'wordform-pro' );
                            echo esc_html( sprintf( __( 'Showing %1$s with %2$s.', 'wordform-pro' ), $selected_form_summary, $selected_app_summary ) );
                            ?>
                        </p>
                        <p class="description"><?php esc_html_e( 'Changing any filter refreshes this tab and keeps the Connection Status view open.', 'wordform-pro' ); ?></p>
                    </div>
                </div>
            </div>

            <?php if ( $connection_status_rows ) { ?>
            <table id="wordformConnectionStatusTable" class="display hover stripe wp-list-table widefat fixed striped table-view-list wordform-connection-status-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Form Name', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Form ID', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Application', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Configured Status', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Connection Status', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Data Send Status', 'wordform-pro' ); ?></th>
                        <th><?php esc_html_e( 'Latest Submission', 'wordform-pro' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $connection_status_rows as $status_row ) { ?>
                    <tr>
                        <td><a href="<?php echo esc_url( $status_row['formSendLogUrl'] ); ?>"><?php echo esc_html( $status_row['formName'] ); ?></a></td>
                        <td><code><?php echo esc_html( $status_row['formId'] ); ?></code></td>
                        <td><?php echo esc_html( $status_row['applicationName'] ); ?></td>
                        <td><?php echo $render_connection_status_badge( $status_row['configuredStatusLabel'], $status_row['configuredStatusKey'] ); ?></td>
                        <td><?php echo $render_connection_status_badge( $status_row['connectionStatusLabel'], $status_row['connectionStatusKey'] ); ?></td>
                        <td>
                            <?php echo $render_connection_status_badge( $status_row['dataSendStatusLabel'], $status_row['dataSendStatusKey'] ); ?>
                            <?php if ( 'fail' === $status_row['dataSendStatusKey'] && ! empty( $status_row['failureDetail'] ) ) { ?>
                                <button
                                    type="button"
                                    class="button button-link wordform-open-connection-fail-detail-modal"
                                    data-failure-detail="<?php echo esc_attr( wp_json_encode( $status_row['failureDetail'] ) ); ?>"
                                    title="<?php esc_attr_e( 'View fail details', 'wordform-pro' ); ?>"
                                ><span class="dashicons dashicons-warning" aria-hidden="true"></span></button>
                            <?php } ?>
                        </td>
                        <td>
                            <?php
                            if ( ! empty( $status_row['latestSubmissionDate'] ) ) {
                                echo esc_html( SftcyWordformConnectBase::format_connection_status_datetime( $status_row['latestSubmissionDate'] ) );
                            } else {
                                esc_html_e( 'No submission yet', 'wordform-pro' );
                            }
                            ?>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
            <?php } else { ?>
                <div class="notice notice-info">
                    <p><?php esc_html_e( 'No forms found for the current Connection Status filter.', 'wordform-pro' ); ?></p>
                </div>
            <?php } ?>
            <?php } ?>
        </div>
        <?php } ?>
    </div>

    <?php
    foreach ( $connect_applications as $application ) {
        if ( ! empty( $application['modal_view'] ) && file_exists( $application['modal_view'] ) ) {
            include $application['modal_view'];
        }
    }
    ?>

    <!-- Start WordForm & Third-party Connection Modal Wrapper Element - On click Create Connection Button -->
    <div id="WordFormConnectionModal" title="WordForm Connection" class="" style="display: none;"></div>
    <!-- Start WordForm & Third-party Connection Modal - On click Create Connection Button -->

    <!-- Start WordForm Configure Success- Fail Message Display Modal - Based on configured application show modal -->    
    <?php
        if ( isset( $_GET['configure'] ) && ! empty( $_GET['configure'] ) && isset( $_GET['status'] ) && ! empty( $_GET['status'] )  ) {
            $configure_app = $_GET['configure'];
            $configure_app_result = $_GET['status'];
            $render_connect_callback_help_link = static function( $provider_slug = '' ) {
                $help_url = SftcyWordformConnectBase::get_connect_provider_help_url( $provider_slug );
                if ( empty( $help_url ) ) {
                    return '';
                }

                $help_label = SftcyWordformConnectBase::get_connect_provider_help_label( $provider_slug );
                if ( empty( $help_label ) ) {
                    $help_label = __( 'Official setup guide', 'wordform-pro' );
                }

                return '<p><a href="' . esc_url( $help_url ) . '" target="_blank" rel="noopener">' . esc_html( $help_label ) . '</a></p>';
            };
            switch ( $configure_app ) {
                case 'googlesheet':
                    if ( $configure_app_result == 'success' ) {
                        $configure_app_result_msg = '<h4 class="text-success"><i class="fa-solid fa-circle-check"></i> Google Sheet authorized successfully.</h4>';

                    }
                    else if ( $configure_app_result == 'fail' ) {
                        $google_sheet_error_detail = get_option( 'wordform_connect_google_sheet_last_auth_error', '' );
                        $configure_app_result_msg = '<h4 class="text-error"><i class="fa-solid fa-circle-exclamation"></i> Google Sheet failed to configure.</h4>';
                        if ( ! empty( $google_sheet_error_detail ) ) {
                            $configure_app_result_msg .= '<p>' . esc_html( $google_sheet_error_detail ) . '</p>';
                        } else {
                            $configure_app_result_msg .= '<p>' . esc_html__( 'Please try again.', 'wordform-pro' ) . '</p>';
                        }
                        $configure_app_result_msg .= '<p>' . esc_html__( 'Check that the exact redirect URL from the modal is registered in Google Cloud before trying again.', 'wordform-pro' ) . '</p>';
                        $configure_app_result_msg .= $render_connect_callback_help_link( 'googlesheet' );
                    }
                    break;
                case 'googlecalendar':
                    if ( $configure_app_result == 'success' ) {
                        $configure_app_result_msg = '<h4 class="text-success"><i class="fa-solid fa-circle-check"></i> Google Calendar authorized successfully. WordForm will use the primary calendar by default when it is available.</h4>';
                    }
                    else if ( $configure_app_result == 'fail' ) {
                        $google_calendar_error_detail = get_option( 'wordform_connect_google_calendar_last_auth_error', '' );
                        $configure_app_result_msg = '<h4 class="text-error"><i class="fa-solid fa-circle-exclamation"></i> Google Calendar authorization failed.</h4>';
                        if ( ! empty( $google_calendar_error_detail ) ) {
                            $configure_app_result_msg .= '<p>' . esc_html( $google_calendar_error_detail ) . '</p>';
                        } else {
                            $configure_app_result_msg .= '<p>' . esc_html__( 'Please try again.', 'wordform-pro' ) . '</p>';
                        }
                        $configure_app_result_msg .= '<p>' . esc_html__( 'Check that the exact redirect URL from the modal is registered in Google Cloud before trying again.', 'wordform-pro' ) . '</p>';
                        $configure_app_result_msg .= $render_connect_callback_help_link( 'googlecalendar' );
                    }
                    break;
                case 'salesforce':
                    if ( $configure_app_result == 'success' ) {
                        $configure_app_result_msg = '<h4 class="text-success"><i class="fa-solid fa-circle-check"></i> Salesforce configured successfully.</h4>';
                    } else if ( $configure_app_result == 'fail' ) {
                        $salesforce_error_detail = get_option( 'wordform_connect_salesforce_last_auth_error', '' );
                        $configure_app_result_msg = '<h4 class="text-error"><i class="fa-solid fa-circle-exclamation"></i> Salesforce failed to configure.</h4>';
                        if ( ! empty( $salesforce_error_detail ) ) {
                            $configure_app_result_msg .= '<p>' . esc_html( $salesforce_error_detail ) . '</p>';
                        } else {
                            $configure_app_result_msg .= '<p>' . esc_html__( 'Please try again.', 'wordform-pro' ) . '</p>';
                        }
                        $configure_app_result_msg .= '<p>' . esc_html__( 'Check that the Connected App callback URL exactly matches the redirect URL shown in the WordForm modal.', 'wordform-pro' ) . '</p>';
                        $configure_app_result_msg .= $render_connect_callback_help_link( 'salesforce' );
                    }
                    break;
                case 'zohocrm':
                    if ( $configure_app_result == 'success' ) {
                        $configure_app_result_msg = '<h4 class="text-success"><i class="fa-solid fa-circle-check"></i> Zoho CRM configured successfully.</h4>';
                    } else if ( $configure_app_result == 'fail' ) {
                        $zohocrm_error_detail = get_option( 'wordform_connect_zohocrm_last_auth_error', '' );
                        $configure_app_result_msg = '<h4 class="text-error"><i class="fa-solid fa-circle-exclamation"></i> Zoho CRM failed to configure.</h4>';
                        if ( ! empty( $zohocrm_error_detail ) ) {
                            $configure_app_result_msg .= '<p>' . esc_html( $zohocrm_error_detail ) . '</p>';
                        } else {
                            $configure_app_result_msg .= '<p>' . esc_html__( 'Please try again.', 'wordform-pro' ) . '</p>';
                        }
                        $configure_app_result_msg .= '<p>' . esc_html__( 'Check that the client ID, client secret, accounts URL, and redirect URL exactly match your Zoho OAuth app settings.', 'wordform-pro' ) . '</p>';
                        $configure_app_result_msg .= $render_connect_callback_help_link( 'zohocrm' );
                    }
                    break;
            } // switch
            echo '<div id="WordFormConnectionConfigureModal" class="WordFormConnectionConfigureModal" title="WordForm Configure">' . $configure_app_result_msg . '</div>';
        }
    ?>                            
    <!-- Start WordForm Configure Success- Fail Message Display Modal - Based on configured application show modal -->

    <!-- Start Application Activate or Deactivate Confirm Modal window Wrapper-->
     <div id="WordFormApplicationActivateDeactivateConfirmModal" class="WordFormApplicationActivateDeactivateConfirmModal" title="Confirm"></div>
    <!-- End Application Activate or Deactivate Confirm Modal window Wrapper-->

    <!-- Start Connection Status failure details modal Wrapper -->
    <div id="WordFormConnectionStatusFailDetailModal" class="WordFormConnectionStatusFailDetailModal" title="Connection Failure Details" style="display:none;"></div>
    <!-- End Connection Status failure details modal Wrapper -->

</div><!-- /.wrap -->
