<?php

if( isset( $_POST['connect_getresponse'] ) && wp_verify_nonce( $_POST['getresponse_nonce'], 'wpuf_getresponse_api_key_nonce' ) ) {
    $error = '';

    if ( empty( $_POST['wpuf_getresponse_api_key'] ) ) {
        $error = __( 'Please insert your API key first','wpuf-pro' );
    }

    if ( !$error ) {
        update_option( 'wpuf_getresponse_api_key', $_POST['wpuf_getresponse_api_key'] );
        
        // Clear any previous failure cache
        delete_transient( 'wpuf_gr_api_failure' );
        delete_transient( 'wpuf_gr_last_log' );
        
        // Test API connection first
        $temp_instance = new WPUF_GetResponse();
        $api_test = $temp_instance->test_api_connection();
        
        if ( $api_test['status'] === 'success' ) {
            // API connection successful, now try to fetch lists
            $temp_instance->get_lists();
            
            $lists = get_option( 'wpuf_gr_lists' );
            if ( !empty( $lists ) ) {
                $success = __( 'Successfully connected to GetResponse and fetched your campaigns!', 'wpuf-pro' );
            } else {
                $success = __( 'API connected successfully, but no campaigns found. You may need a paid GetResponse plan to access campaigns/lists.', 'wpuf-pro' );
            }
        } else {
            if ( isset( $api_test['response']->code ) && $api_test['response']->code == '1023' ) {
                $error = __( 'GetResponse API connection failed: API access requires a paid plan. Please upgrade your GetResponse account.', 'wpuf-pro' );
            } else {
                $error = __( 'GetResponse API connection failed: ', 'wpuf-pro' ) . $api_test['message'];
            }
        }
    }

}

if( isset( $_POST['remove_api'] ) && wp_verify_nonce( $_POST['getresponse_remove_nonce'], 'wpuf_getresponse_api_key_remove_nonce' ) ) {
    delete_option( 'wpuf_getresponse_api_key' );
    delete_option( 'wpuf_gr_lists' );
    $success = __( 'Successfully removed your API key', 'wpuf-pro' );
}

if( isset( $_POST['refresh_lists'] ) && wp_verify_nonce( $_POST['getresponse_refresh_nonce'], 'wpuf_getresponse_refresh_nonce' ) ) {
    // Clear failure cache before retrying
    delete_transient( 'wpuf_gr_api_failure' );
    delete_transient( 'wpuf_gr_last_log' );
    
    $temp_instance = new WPUF_GetResponse();
    $temp_instance->get_lists();
    
    $lists = get_option( 'wpuf_gr_lists' );
    if ( !empty( $lists ) ) {
        $success = __( 'Successfully refreshed your GetResponse campaigns!', 'wpuf-pro' );
    } else {
        $error = __( 'Could not fetch campaigns. Please check your API key and account status.', 'wpuf-pro' );
    }
}

if( isset( $_POST['test_connection'] ) && wp_verify_nonce( $_POST['getresponse_test_nonce'], 'wpuf_getresponse_test_nonce' ) ) {
    $temp_instance = new WPUF_GetResponse();
    $test_result = $temp_instance->test_api_connection();
    
    if ( $test_result['status'] === 'success' ) {
        $success = __( 'API connection test successful!', 'wpuf-pro' );
    } else {
        $error = __( 'API connection failed: ', 'wpuf-pro' ) . $test_result['message'];
    }
}

?>

<?php if ( ! empty( $error ) ): ?>
    <div class="error">
        <p><?php echo $error; ?></p>
    </div>
<?php endif ?>

<?php if ( ! empty( $success ) ): ?>
    <div class="updated">
        <p><?php echo $success; ?></p>
    </div>
<?php endif ?>

<?php if ( isset( $_GET['gr_refresh'] ) ): ?>
    <?php if ( $_GET['gr_refresh'] === 'success' ): ?>
        <div class="updated">
            <p><?php _e( 'Campaigns refreshed successfully!', 'wpuf-pro' ); ?></p>
        </div>
    <?php elseif ( $_GET['gr_refresh'] === 'failed' ): ?>
        <div class="error">
            <p><?php _e( 'Failed to refresh campaigns. Please check your API key and account status.', 'wpuf-pro' ); ?></p>
        </div>
    <?php endif; ?>
<?php endif; ?>

<div class="postbox">
    <div class="inside wpuf_gr_wrapper">
        <div class="main">
        <?php if ( get_option( 'wpuf_getresponse_api_key' ) ): ?>

            <h3 id="wpuf_gr_api"><?php _e('Your GetResponse API key is :','wpuf-pro' ); ?> </h3> <?php echo get_option( 'wpuf_getresponse_api_key' ); ?>

            <div style="margin-top: 15px;">
                <form action="" method="post" id="wpuf_gr_api_remove_action" style="display: inline-block; margin-right: 10px;">
                    <?php wp_nonce_field( 'wpuf_getresponse_api_key_remove_nonce', 'getresponse_remove_nonce' ); ?>
                    <input type="submit" name="remove_api" class="button remove_api_class" value="<?php _e('Remove','wpuf-pro' ); ?>" onclick="return removeApiConfirm()">
                </form>
                
                <form action="" method="post" id="wpuf_gr_refresh_lists" style="display: inline-block; margin-right: 10px;">
                    <?php wp_nonce_field( 'wpuf_getresponse_refresh_nonce', 'getresponse_refresh_nonce' ); ?>
                    <input type="submit" name="refresh_lists" class="button button-secondary" value="<?php _e('Refresh Campaigns','wpuf-pro' ); ?>">
                </form>
                
                <a href="<?php echo add_query_arg( 'wpuf_refresh_gr_lists', '1', admin_url( 'admin.php?page=wpuf_getresponse' ) ); ?>" 
                   class="button button-secondary" style="margin-right: 10px;"><?php _e( 'Force Refresh', 'wpuf-pro' ); ?></a>
                
                <form action="" method="post" id="wpuf_gr_test_connection" style="display: inline-block;">
                    <?php wp_nonce_field( 'wpuf_getresponse_test_nonce', 'getresponse_test_nonce' ); ?>
                    <input type="submit" name="test_connection" class="button button-secondary" value="<?php _e('Test Connection','wpuf-pro' ); ?>">
                </form>
            </div>
            
            <?php 
            $lists = get_option( 'wpuf_gr_lists' );
            $api_key = get_option( 'wpuf_getresponse_api_key' );
            
            if ( !empty( $lists ) && is_array( $lists ) ) {
                echo '<p style="margin-top: 15px;"><strong>' . __( 'Available Campaigns:', 'wpuf-pro' ) . '</strong></p>';
                echo '<ul>';
                foreach( $lists as $list ) {
                    echo '<li>' . esc_html( $list['name'] ) . ' (ID: ' . esc_html( $list['id'] ) . ')</li>';
                }
                echo '</ul>';
            } else if ( $api_key ) {
                echo '<div class="notice notice-warning" style="margin-top: 15px; padding: 10px;">';
                echo '<p><strong>' . __( 'No campaigns found.', 'wpuf-pro' ) . '</strong></p>';
                echo '<p>' . __( 'This could be because:', 'wpuf-pro' ) . '</p>';
                echo '<ul>';
                echo '<li>' . __( 'Your GetResponse account is on a free plan (API access requires a paid plan)', 'wpuf-pro' ) . '</li>';
                echo '<li>' . __( 'You haven\'t created any campaigns in GetResponse yet', 'wpuf-pro' ) . '</li>';
                echo '<li>' . __( 'Your API key doesn\'t have proper permissions', 'wpuf-pro' ) . '</li>';
                echo '</ul>';
                echo '<p>' . __( 'Try using the "Test Connection" button to check your API status.', 'wpuf-pro' ) . '</p>';
                echo '</div>';
            }
            ?>

        <?php else: ?>

            <h3 style="padding:10px 5px"><?php _e( 'Please insert your GetResponse API key:','wpuf-pro' ); ?></h3>
            <form action="" method="post" style="margin-top: 20px;" id="wpuf_getresponse_api_form">
                <input type="text" style="width: 40%" name="wpuf_getresponse_api_key" value="" class="wpuf_getresponse_api">
                <?php wp_nonce_field( 'wpuf_getresponse_api_key_nonce', 'getresponse_nonce' ); ?>
                <input type="submit" class="button button-primary" name="connect_getresponse" value="<?php _e( 'Connect','wpuf-pro' ) ?>">
            </form>

        <?php endif ?>

        </div>
    </div>
</div>


<script>

    function removeApiConfirm() {
        var r = confirm("Are you sure want to delete?");
        if (r == false) {
            return false;
        }
    }
</script>