<?php
/*
 * Google Sheet configuration and settings page
 * @since 1.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit();
}

global $wpdb;

// Fetch Formidable Forms from the frm_forms table
$formidable_forms = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}frm_forms", OBJECT);

$feed_table = esc_sql($wpdb->prefix . 'postmeta');

$query = $wpdb->prepare(
    "SELECT * FROM `{$feed_table}` WHERE `meta_value` = %s",
    'gscfrm_form_feeds'
);

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$feedList = $wpdb->get_results($query);




// Check if the user is authenticated
$authenticated = get_option('frmgsc_gs_token');
$formidable_per = get_option('gscfrmdform_verify');
$show_setting = 0;
$selected_method = '';
$selected_method = __('Use Existing Client/Secret Key (Auto Google API Configuration)', 'gsheetconnector-formidable-forms');



// Check if the user is authenticated when saving existing API method
if (!empty($authenticated) && $formidable_per == 'valid') {
    $show_setting = 1;
}
else {
    ?>

    <p class='formidable-gs-display-note'>
        <?php
        echo esc_html__('Make Sure, your selected Method is:', 'gsheetconnector-formidable-forms') . ' ';
        echo esc_html($selected_method);
        echo '<br><br><strong>' . esc_html__('Authentication Required:', 'gsheetconnector-formidable-forms') . '</strong> ';
        echo wp_kses_post(__('You must have to <a href="admin.php?page=formidable-form-google-sheet-config&tab=integration" target="_blank">Authenticate using your Google Account</a> along with Google Drive and Google Sheets Permissions in order to enable the settings for configuration.', 'gsheetconnector-formidable-forms'));
        ?>
    </p>


    <?php
}

if ($show_setting == 1) {
    ?>

    <!-- Feed message display block -->
    <div class="feed-error-message" style="display:none;"></div>
    <div class="feed-success-message" style="display:none;"></div>

    <div class="elementor-main">
        <div class="elementor-row">
            <div>
                <button class="elementor-btn" id="add-new-feed">
                    <?php echo esc_html('Add Feeds', 'gsheetconnector-formidable-forms'); ?>
                </button>
                <button class="elementor-close-btn" id="close-feed" style="display:none">
                    <?php echo esc_html('Close Feeds', 'gsheetconnector-formidable-forms'); ?>
                </button>
            </div>

            <div class="add-feed-form">
                <form method="post">
                    <label for="feed_name"><?php echo esc_html('Feed Name', 'gsheetconnector-formidable-forms'); ?></label>
                    <input type="text" id="feed_name" class="feedName" name="feed_name" />

                    <label
                        for="formidable_form_select"><?php echo esc_html('Select Form', 'gsheetconnector-formidable-forms'); ?></label>
                    <select id="formidable_form_select" name="formidableforms" class="formidableForms">
                        <option value=""><?php echo esc_html('Select Form', 'gsheetconnector-formidable-forms'); ?></option>

                        <?php
                        // Display fetched Formidable Forms
                        if (!empty($formidable_forms)) {
                            foreach ($formidable_forms as $formidable_form) { ?>
                                <option value="<?php echo esc_attr($formidable_form->id); ?>">
                                    <?php echo esc_html($formidable_form->name); ?>
                                </option>
                            <?php }
                        }
                        ?>
                    </select>

                    <input type="hidden" name="gs-ajax-nonce" id="gs-ajax-nonce"
                        value="<?php echo esc_attr(wp_create_nonce('gs-ajax-nonce')); ?>" />
                    <input type="button" name="execute-submit-feed-formidable" class="formidable-gs-sub-btn"
                        value="<?php echo esc_html('Submit', 'gsheetconnector-formidable-forms'); ?>">
                    <span class="fld-fetch-load">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                </form>
            </div>
        </div>

        <div class="elementor-feeds-list">
            <table border="0" id="formidableformtable">
                <?php
                if (!empty($feedList)) {
                    ?>
                    <tr>
                        <th><?php echo esc_html('Sr No', 'gsheetconnector-formidable-forms'); ?></th>
                        <th><?php echo esc_html('Feed Name', 'gsheetconnector-formidable-forms'); ?></th>
                        <th><?php echo esc_html('Form Name', 'gsheetconnector-formidable-forms'); ?></th> <!-- New Column -->
                        <th><?php echo esc_html('Form ID', 'gsheetconnector-formidable-forms'); ?></th>
                        <th><?php echo esc_html('Page Name', 'gsheetconnector-formidable-forms'); ?></th>
                    </tr>

                    <?php
                    foreach ($feedList as $key => $value) {
                        // Fetch the post title (page name)
                        $post_title = get_the_title($value->post_id);

                        // Fetch the form name from the frm_forms table
                        $form_name = $wpdb->get_var($wpdb->prepare(
                            "SELECT name FROM {$wpdb->prefix}frm_forms WHERE id = %d",
                            $value->post_id
                        ));

                        // Find which pages/posts are using this form ID in their content
                        $pages_using_form = $wpdb->get_results(
                            $wpdb->prepare(
                                "SELECT ID, post_title FROM {$wpdb->posts}
             WHERE post_type IN ('page', 'post')
             AND post_status = 'publish'
             AND post_content LIKE %s",
                                '%' . $wpdb->esc_like($value->post_id) . '%'
                            )
                        );
                        $form_key = $wpdb->get_var($wpdb->prepare(
                            "SELECT form_key FROM {$wpdb->prefix}frm_forms WHERE id = %d",
                            $value->post_id
                        ));

                        $preview_url = admin_url('admin-ajax.php?action=frm_forms_preview&form=' . $form_key);
                        ?>
                        <tr id="feed-<?php echo esc_attr($value->meta_id); ?>">
                            <td><?php echo esc_html($key + 1); ?></td>
                            <td>
                                <div class="feed-info">
                                    <div class="feed-title"><?php echo esc_html($value->meta_key); ?></div>
                                    <div class="feed-edit-option">
                                        <a
                                            href="?page=formidable-form-google-sheet-config&tab=form_feed_settings&form_id=<?php echo esc_attr($value->post_id); ?>&feed_id=<?php echo esc_attr($value->meta_id); ?>">
                                            <?php echo esc_html__('Edit', 'gsheetconnector-formidable-forms'); ?>
                                        </a>
                                        <a href="#" data-feed-id="<?php echo esc_attr($value->meta_id); ?>"
                                            class="delete elementor-gs-btn delete-feed">
                                            <?php echo esc_html__('Delete', 'gsheetconnector-formidable-forms'); ?>
                                        </a>
                                        <a href="<?php echo esc_url($preview_url); ?>" target="_blank">
                                            <?php echo esc_html__('View', 'gsheetconnector-formidable-forms'); ?>
                                        </a>


                                    </div>
                                    <span
                                        class="loading-sign-delete-feed-elegs<?php echo esc_attr($value->meta_id); ?>">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                </div>
                            </td>
                            <td><?php echo esc_html($form_name); ?></td>
                            <td><?php echo esc_html($value->post_id); ?></td>
                            <td>
                                <?php
                                if (!empty($pages_using_form)) {
                                    foreach ($pages_using_form as $page) {
                                        echo esc_html($page->post_title) . '<br>';
                                    }
                                } else {
                                    echo esc_html__('No Page Add', 'gsheetconnector-formidable-forms');
                                }
                                ?>
                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    ?>
                    <tr>
                        <td colspan="4">
                            <h3><?php echo esc_html('No feeds found', 'gsheetconnector-formidable-forms'); ?></h3>
                        </td>
                    </tr>
                    <?php
                }
                ?>
            </table>
        </div>
    </div>
    <?php
}

?>

<script type="text/javascript">
    jQuery(document).ready(function ($) {
        // Ensure $ alias is used within this function scope

        // Hide the close-feed button initially
        $("#close-feed").hide();

        // Show the add-feed form and toggle buttons
        $(document).on('click', '#add-new-feed', function () {
            $(".add-feed-form").show();
            $("#add-new-feed").hide();
            $("#close-feed").show();
        });

        // Hide the add-feed form and toggle buttons
        $(document).on('click', '#close-feed', function (event) {
            event.preventDefault(); // Prevent default link behavior
            $("#add-new-feed").show();
            $("#close-feed").hide();
            $(".add-feed-form").hide();
        });
    });
</script>
