<?php

/**
 * Feed Service class for GsheetConnector-jetforms License operations
 * @since 1.0.0 
 */

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

/**
 * GSHFJF_JetForm_Feed_Service Class
 * @since 1.0.0
 */

class GSHFJF_JetForm_Feed_Service
{

    /**
     * Register admin and AJAX actions for saving and deleting form feed settings.
     *
     * @access public
     * @since 1.0.0
     */

    public function __construct()
    {
        // form feed settings sheet details save in table
        add_action('admin_init', array($this, 'execute_post_data'));

        // Add Feed
        add_action('wp_ajax_gshfjf_save_feed', array($this, 'gshfjf_save_feed'));

        // Delete Feed
        add_action('wp_ajax_gshfjf_delete_feed', array($this, 'gshfjf_delete_feed'));

        //Reset Feed
        add_action('wp_ajax_gshfjf_reset_feed', array($this, 'gshfjf_reset_feed'));

        // Save uninstall settings
        add_action('wp_ajax_gshfjf_save_uninstall_settings_ajax_free', array($this, 'gshfjf_save_uninstall_settings_ajax_free'));

        // Toggle Feed Status
        add_action('wp_ajax_gshfjf_toggle_feed_status', array($this, 'gshfjf_toggle_feed_status'));
    }

    /**
     * Status save.
     *
     * @access public
     * @since 1.0.0
     */

    function gshfjf_toggle_feed_status()
    {
        // 🔐 Nonce check
        if (
            !isset($_POST['security']) ||
            !wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['security'])),
                'gshfjf-ajax-nonce'
            )
        ) {

            wp_send_json_error('Invalid nonce');
        }

        $feed_id = isset($_POST['feed_id']) ? absint($_POST['feed_id']) : 0;
        $status  = isset($_POST['status']) ? absint($_POST['status']) : 0;
        if (!$feed_id) {

            wp_send_json_error('Invalid feed ID');
        }
        global $wpdb;
        $table_name = $wpdb->prefix . 'gshfjf_jetform_db_settings';
        $updated = $wpdb->update(
            $table_name,
            array('status' => $status),
            array('id' => $feed_id),
            array('%d'),
            array('%d')
        );
        if ($updated === false) {
            wp_send_json_error($wpdb->last_error);
        }

        wp_send_json_success(array(
            'feed_id' => $feed_id,
            'status'  => $status,
        ));
    }

    /**
     * Displays error message on plugin settings page if triggered by form submission.
     *
     * @access public
     * @since 1.0.0
     */

    // public function error_message($error)
    // {
    //     if (is_admin() && isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'jetform-google-sheet-config') {
    //         if (isset($_POST['gshfjf-save-btn'])) {
    //             $plugin_error = GSHFJF_JetForm_Connector_Utility::instance()->admin_notice(array(
    //                 'type' => 'error',
    //                 'message' => esc_html($error, 'gsheetconnector-for-jetform')
    //             ));
    //             echo esc_html($plugin_error, 'gsheetconnector-for-jetform');
    //         }
    //     }
    // }

    /**
     * Save feed settings in the database.
     *
     * @since 1.0.0
     */

    public function execute_post_data()
    {
        try {

            if (!isset($_POST['gshfjf-execute-edit-feed'])) {
                return;
            }

            if (
                !isset($_POST['gshfjf-ajax-nonce']) ||
                !wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['gshfjf-ajax-nonce'])),
                    'gshfjf-ajax-nonce'
                )
            ) {
                wp_die('Invalid nonce');
            }

            if (!is_user_logged_in() || !current_user_can('edit_posts')) {
                wp_die('You do not have permission to edit feeds.');
            }

            $feed_id = isset($_POST['feed_id']) ? absint($_POST['feed_id']) : 0;
            $form_id = isset($_POST['form_id']) ? absint($_POST['form_id']) : 0;
            $feed_name = isset($_POST['feed-name'])
                ? sanitize_text_field(wp_unslash($_POST['feed-name']))
                : '';

            if (!$feed_id || !$form_id || empty($feed_name)) {
                return;
            }

            $meta_value = array(
                'sheet-name'     => isset($_POST['gshf-jf']['sheet-name-custom']) ? sanitize_text_field(wp_unslash($_POST['gshf-jf']['sheet-name-custom'])) : '',
                'sheet-id'       => isset($_POST['gshf-jf']['sheet-id-custom']) ? sanitize_text_field(wp_unslash($_POST['gshf-jf']['sheet-id-custom'])) : '',
                'sheet-tab-name' => isset($_POST['gshf-jf']['sheet-tab-name-custom']) ? sanitize_text_field(wp_unslash($_POST['gshf-jf']['sheet-tab-name-custom'])) : '',
                'tab-id'         => isset($_POST['gshf-jf']['tab-id-custom']) ? sanitize_text_field(wp_unslash($_POST['gshf-jf']['tab-id-custom'])) : '',
            );

            global $wpdb;
            $table_name = $wpdb->prefix . 'gshfjf_jetform_db_settings';
            $sheet_details_serialized = maybe_serialize($meta_value);

            $existing_id = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT id FROM {$wpdb->prefix}gshfjf_jetform_db_settings WHERE id = %d AND feed_name = %s",
                    $feed_id,
                    $feed_name
                )
            );

            if ($existing_id) {

                $updated = $wpdb->update(
                    $table_name,
                    array(
                        'form_id'       => $form_id,
                        'sheet_details' => $sheet_details_serialized,
                    ),
                    array(
                        'id'        => $feed_id,
                        'feed_name' => $feed_name,
                    ),
                    array('%d', '%s'),
                    array('%d', '%s')
                );
            }
        } catch (Exception $e) {
            echo esc_html('Error saving feed: ' . $e->getMessage());
        }
    }

    /**
     * Saves a new feed for the selected jetForm if it doesn't already exist.
     *
     * @access public
     * @since 1.0.0
     */

    public function gshfjf_save_feed()
    {

        check_ajax_referer('gshfjf-ajax-nonce', 'security');
        $feed_name = isset($_POST['feed_name'])
            ? sanitize_text_field(wp_unslash($_POST['feed_name']))
            : '';

        $form_id = isset($_POST['form_id'])
            ? absint($_POST['form_id'])
            : 0;

        if (empty($feed_name) || empty($form_id)) {
            wp_send_json_error('Required data missing');
        }

        $existing_feed = get_post_meta($form_id, $feed_name, true);

        if (!empty($existing_feed)) {
            wp_send_json_error(
                'Feed name already exists in the list, please enter a unique feed name'
            );
        }

        $feed_data = get_post_meta(
            $form_id,
            'gshfjf_jetform_feeds_sheet_settings',
            true
        );

        $sheet_name = isset($feed_data['sheet-name'])
            ? sanitize_text_field($feed_data['sheet-name'])
            : '';

        $sheet_id = isset($feed_data['sheet-id'])
            ? sanitize_text_field($feed_data['sheet-id'])
            : '';

        $tab_name = isset($feed_data['sheet-tab-name'])
            ? sanitize_text_field($feed_data['sheet-tab-name'])
            : '';

        $tab_id = isset($feed_data['tab-id'])
            ? sanitize_text_field($feed_data['tab-id'])
            : '';

        $sheet_details_array = array(
            'sheet-name'     => $sheet_name,
            'sheet-tab-name' => $tab_name,
            'sheet-id'       => $sheet_id,
            'tab-id'         => $tab_id,
        );

        $sheet_details_serialized = maybe_serialize($sheet_details_array);

        update_post_meta(
            $form_id,
            $feed_name,
            'gshfjf_jetform_feeds'
        );

        global $wpdb;

        $table_name = $wpdb->prefix . 'gshfjf_jetform_db_settings';
        $inserted = $wpdb->insert(
            $table_name,
            array(
                'form_id'      => $form_id,
                'feed_name'    => $feed_name,
                'sheet_details' => $sheet_details_serialized,
                'status'       => 1,
                'created_at'   => current_time('mysql'),
            ),
            array(
                '%d',
                '%s',
                '%s',
                '%d',
                '%s'
            )
        );

        if ($inserted === false) {
            wp_send_json_error($wpdb->last_error);
        }
        wp_send_json_success('Feed has been successfully created');
    }

    /**
     * Deleting Feed.
     *
     * @since 1.0.0
     */

    function gshfjf_delete_feed()
    {
        check_ajax_referer('gshfjf-ajax-nonce', 'security');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Permission denied');
        }

        $feed_id = isset($_POST['feed_id'])
            ? absint(wp_unslash($_POST['feed_id']))
            : 0;
        if (!$feed_id) {
            wp_send_json_error('Invalid feed ID');
        }

        global $wpdb;
        $table = $wpdb->prefix . 'gshfjf_jetform_db_settings';

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, form_id, feed_name FROM {$wpdb->prefix}gshfjf_jetform_db_settings WHERE id = %d",
                $feed_id
            )
        );

        if (!$row) {
            wp_send_json_error('Feed not found');
        }

        $form_id   = (int) $row->form_id;
        $feed_name = sanitize_text_field($row->feed_name);

        $wpdb->delete(
            $table,
            array('id' => $feed_id),
            array('%d')
        );

        delete_post_meta(
            $form_id,
            $feed_name,
            'gshfjf_jetform_feeds'
        );

        delete_post_meta(
            $form_id,
            'gshfjf_jetform_feeds_sheet_settings'
        );

        wp_send_json_success('Feed deleted from table and postmeta');
    }

    /**
     * Reset Feed.
     *
     * @since 1.0.0
     */

    function gshfjf_reset_feed()
    {
        check_ajax_referer('gshfjf-ajax-nonce', 'security');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Permission denied');
        }

        $feed_id = isset($_POST['feed_id']) ? absint($_POST['feed_id']) : 0;

        if (!$feed_id) {
            wp_send_json_error('Invalid feed ID');
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'gshfjf_jetform_db_settings';

        $updated = $wpdb->update(
            $table_name,
            array('sheet_details' => ''),
            array('id' => $feed_id),
            array('%s'),
            array('%d')
        );

        if ($updated === false) {
            wp_send_json_error($wpdb->last_error);
        }

        wp_send_json_success(array(
            'updated' => $updated,
        ));
    }

    /**
     * Save Uninstall Settings.
     *
     * @since 1.0.0
     */

    function gshfjf_save_uninstall_settings_ajax_free()
    {

        check_ajax_referer('gshfjf-jetform-setting-ajax-nonce', 'security');
        $value = isset($_POST['uninstall_setting']) ? intval($_POST['uninstall_setting']) : 0;
        update_option('gshfjf_uninstall_setting', $value);
        wp_send_json_success();
    }
}
$GSHFJF_JetForm_Feed_Service = new GSHFJF_JetForm_Feed_Service();
