<?php

/**
 * Settings Page
 *
 * @package Giraforms
 */
// Exit if accessed directly.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Class GiraForms_Settings
 */
class GiraForms_Settings {
    /**
     * Instance of this class.
     *
     * @var GiraForms_Settings
     */
    private static $instance = null;

    /**
     * Settings option name.
     *
     * @var string
     */
    private $option_name = 'giraforms_settings';

    /**
     * Get instance.
     *
     * @return GiraForms_Settings
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'admin_init', array($this, 'register_settings') );
        add_action( 'admin_menu', array($this, 'add_settings_page') );
        add_action( 'admin_post_giraforms_delete_submissions', array($this, 'handle_delete_submissions') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_scripts') );
    }

    /**
     * Enqueue scripts for settings page.
     */
    public function enqueue_scripts() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking page parameter for script enqueue.
        $page = ( isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '' );
        // Only load on settings page.
        if ( 'giraforms-settings' !== $page ) {
            return;
        }
        // Enqueue jQuery (already included in WordPress).
        wp_enqueue_script( 'jquery' );
        // Add inline styles
        $inline_style = "\n\t\t.giraforms-settings-page .nav-tab-wrapper {\n\t\t\tmargin: 20px 0;\n\t\t\tborder-bottom: 1px solid #ccc;\n\t\t}\n\t\t.giraforms-settings-page .nav-tab {\n\t\t\tposition: relative;\n\t\t\tpadding: 8px 15px;\n\t\t\tfont-size: 15px;\n\t\t\tdisplay: flex;\n\t\t\tgap: 8px;\n\t\t\tborder-top-left-radius: 6px;\n\t\t\tborder-top-right-radius: 6px;\n\t\t}\n\t\t.giraforms-settings-page .tab-content {\n\t\t\tdisplay: none;\n\t\t\tpadding: 20px 0;\n\t\t}\n\t\t.giraforms-settings-page .tab-content.active {\n\t\t\tdisplay: block;\n\t\t}\n\t\t.giraforms-email-tags {\n\t\t\tdisplay: flex;\n\t\t\tflex-wrap: wrap;\n\t\t\tgap: 8px;\n\t\t\tmargin-bottom: 10px;\n\t\t\tmin-height: 40px;\n\t\t\tpadding: 8px;\n\t\t\tborder: 1px solid #8c8f94;\n\t\t\tborder-radius: 4px;\n\t\t\tbackground: #fff;\n\t\t}\n\t\t.giraforms-email-tag {\n\t\t\tdisplay: inline-flex;\n\t\t\talign-items: center;\n\t\t\tgap: 6px;\n\t\t\tpadding: 4px 10px;\n\t\t\tbackground: #3858e9;\n\t\t\tcolor: #fff;\n\t\t\tborder-radius: 4px;\n\t\t\tfont-size: 13px;\n\t\t}\n\t\t.giraforms-email-tag .remove {\n\t\t\tcursor: pointer;\n\t\t\tfont-weight: bold;\n\t\t\topacity: 0.8;\n\t\t}\n\t\t.giraforms-email-tag .remove:hover {\n\t\t\topacity: 1;\n\t\t}\n\t\t.giraforms-email-input-wrapper {\n\t\t\tdisplay: flex;\n\t\t\tgap: 10px;\n\t\t\talign-items: flex-start;\n\t\t}\n\t\t.giraforms-email-input-wrapper input[type='email'] {\n\t\t\tflex: 1;\n\t\t}\n\t\t.giraforms-email-input-wrapper .validation-message {\n\t\t\tcolor: #d63638;\n\t\t\tfont-size: 12px;\n\t\t\tmargin-top: 5px;\n\t\t}\n\t\t";
        wp_add_inline_style( 'wp-admin', $inline_style );
        // Add inline script
        $inline_script = "\n\t\tjQuery(document).ready(function(\$) {\n\t\t\t// Tabs functionality\n\t\t\t\$('.nav-tab').on('click', function(e) {\n\t\t\t\te.preventDefault();\n\t\t\t\tvar target = \$(this).data('tab');\n\n\t\t\t\t\$('.nav-tab').removeClass('nav-tab-active');\n\t\t\t\t\$(this).addClass('nav-tab-active');\n\n\t\t\t\t\$('.tab-content').removeClass('active');\n\t\t\t\t\$('#' + target).addClass('active');\n\n\t\t\t\t// Update URL hash\n\t\t\t\twindow.location.hash = target;\n\t\t\t});\n\n\t\t\t// Activate tab from URL hash on load\n\t\t\tif (window.location.hash) {\n\t\t\t\tvar hash = window.location.hash.substring(1);\n\t\t\t\t\$('.nav-tab[data-tab=\"' + hash + '\"]').click();\n\t\t\t} else {\n\t\t\t\t\$('.nav-tab').first().click();\n\t\t\t}\n\n\t\t\t// Email tags management\n\t\t\tvar emails = [];\n\n\t\t\t// Parse existing emails from hidden input\n\t\t\tvar existingEmails = \$('#giraforms_notification_emails_hidden').val();\n\t\t\tif (existingEmails) {\n\t\t\t\temails = existingEmails.split('\\n').filter(function(email) {\n\t\t\t\t\treturn email.trim() !== '';\n\t\t\t\t});\n\t\t\t\trenderEmailTags();\n\t\t\t}\n\n\t\t\tfunction renderEmailTags() {\n\t\t\t\tvar tagsHtml = '';\n\t\t\t\temails.forEach(function(email, index) {\n\t\t\t\t\ttagsHtml += '<div class=\"giraforms-email-tag\">' +\n\t\t\t\t\t\t'<span>' + email + '</span>' +\n\t\t\t\t\t\t'<span class=\"remove\" data-index=\"' + index + '\">&times;</span>' +\n\t\t\t\t\t\t'</div>';\n\t\t\t\t});\n\t\t\t\t\$('.giraforms-email-tags').html(tagsHtml || '<span style=\"color: #666;\">No email addresses added yet</span>');\n\t\t\t\t\$('#giraforms_notification_emails_hidden').val(emails.join('\\n'));\n\t\t\t}\n\n\t\t\tfunction isValidEmail(email) {\n\t\t\t\tvar re = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+\$/;\n\t\t\t\treturn re.test(email);\n\t\t\t}\n\n\t\t\t\$('#giraforms_add_email_btn').on('click', function() {\n\t\t\t\tvar email = \$('#giraforms_new_email').val().trim();\n\t\t\t\tvar errorMsg = \$('.validation-message');\n\n\t\t\t\tif (!email) {\n\t\t\t\t\terrorMsg.text('" . esc_js( __( 'Please enter an email address', 'giraforms' ) ) . "').show();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!isValidEmail(email)) {\n\t\t\t\t\terrorMsg.text('" . esc_js( __( 'Please enter a valid email address', 'giraforms' ) ) . "').show();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (emails.indexOf(email) !== -1) {\n\t\t\t\t\terrorMsg.text('" . esc_js( __( 'This email is already added', 'giraforms' ) ) . "').show();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\temails.push(email);\n\t\t\t\trenderEmailTags();\n\t\t\t\t\$('#giraforms_new_email').val('');\n\t\t\t\terrorMsg.hide();\n\t\t\t});\n\n\t\t\t// Allow Enter key to add email\n\t\t\t\$('#giraforms_new_email').on('keypress', function(e) {\n\t\t\t\tif (e.which === 13) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\$('#giraforms_add_email_btn').click();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Remove email tag\n\t\t\t\$(document).on('click', '.giraforms-email-tag .remove', function() {\n\t\t\t\tvar index = \$(this).data('index');\n\t\t\t\temails.splice(index, 1);\n\t\t\t\trenderEmailTags();\n\t\t\t});\n\n\t\t\t// Track unsaved changes\n\t\t\tvar giraformsFormDirty = false;\n\t\t\t\$('form[action=\"options.php\"] :input').on('change input', function() {\n\t\t\t\tgiraformsFormDirty = true;\n\t\t\t});\n\n\t\t\t// Initialize color pickers with change tracking\n\t\t\tif (\$.fn.wpColorPicker) {\n\t\t\t\t\$('.giraforms-color-picker').wpColorPicker({\n\t\t\t\t\tchange: function() { giraformsFormDirty = true; },\n\t\t\t\t\tclear: function() { giraformsFormDirty = true; }\n\t\t\t\t});\n\t\t\t}\n\t\t\t\$('form[action=\"options.php\"]').on('submit', function() {\n\t\t\t\tgiraformsFormDirty = false;\n\t\t\t});\n\n\t\t\t// Send test email\n\t\t\t\$('#giraforms-send-test-email').on('click', function() {\n\t\t\t\tif (giraformsFormDirty) {\n\t\t\t\t\tif (!confirm('" . esc_js( __( 'You have unsaved changes. The test email will use the last saved settings. Continue anyway?', 'giraforms' ) ) . "')) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar btn = \$(this);\n\t\t\t\tvar result = \$('#giraforms-test-email-result');\n\t\t\t\tbtn.prop('disabled', true).text('" . esc_js( __( 'Sending...', 'giraforms' ) ) . "');\n\t\t\t\tresult.text('').css('color', '');\n\t\t\t\t\$.post(ajaxurl, {\n\t\t\t\t\taction: 'giraforms_send_test_email',\n\t\t\t\t\tnonce: \$('#giraforms_test_email_nonce').val()\n\t\t\t\t}, function(response) {\n\t\t\t\t\tif (response.success) {\n\t\t\t\t\t\tresult.text(response.data).css('color', '#00a32a');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult.text(response.data).css('color', '#d63638');\n\t\t\t\t\t}\n\t\t\t\t\tbtn.prop('disabled', false).html('<span class=\"dashicons dashicons-email-alt\" style=\"margin-top:3px;\"></span> " . esc_js( __( 'Send Test Email', 'giraforms' ) ) . "');\n\t\t\t\t}).fail(function() {\n\t\t\t\t\tresult.text('" . esc_js( __( 'Request failed.', 'giraforms' ) ) . "').css('color', '#d63638');\n\t\t\t\t\tbtn.prop('disabled', false).html('<span class=\"dashicons dashicons-email-alt\" style=\"margin-top:3px;\"></span> " . esc_js( __( 'Send Test Email', 'giraforms' ) ) . "');\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t// Delete submissions confirmation\n\t\t\t\$('.giraforms-delete-submissions-btn').on('click', function(e) {\n\t\t\t\te.preventDefault();\n\t\t\t\tif (confirm('" . esc_js( __( 'Are you absolutely sure you want to delete ALL submissions? This action cannot be undone!', 'giraforms' ) ) . "')) {\n\t\t\t\t\t\$('#giraforms-delete-submissions-form').submit();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\t";
        wp_add_inline_script( 'jquery', $inline_script );
    }

    /**
     * Add settings page to admin menu.
     */
    public function add_settings_page() {
        add_submenu_page(
            'giraforms',
            __( 'Settings', 'giraforms' ),
            __( 'Settings', 'giraforms' ),
            'manage_options',
            'giraforms-settings',
            array($this, 'render_settings_page')
        );
    }

    /**
     * Register settings.
     */
    public function register_settings() {
        register_setting( 'giraforms_settings_group', $this->option_name, array($this, 'sanitize_settings') );
        // Email notifications section
        add_settings_section(
            'giraforms_email_section',
            __( 'Notifications Email', 'giraforms' ),
            array($this, 'email_section_callback'),
            'giraforms_settings'
        );
        add_settings_field(
            'notification_emails',
            __( 'Notification Email Addresses', 'giraforms' ),
            array($this, 'notification_emails_callback'),
            'giraforms_settings',
            'giraforms_email_section'
        );
        add_settings_field(
            'email_from_name',
            __( 'Sender Name', 'giraforms' ),
            array($this, 'email_from_name_callback'),
            'giraforms_settings',
            'giraforms_email_section'
        );
        add_settings_field(
            'email_from_address',
            __( 'Sender Email', 'giraforms' ),
            array($this, 'email_from_address_callback'),
            'giraforms_settings',
            'giraforms_email_section'
        );
        add_settings_field(
            'email_subject',
            __( 'Default Subject', 'giraforms' ),
            array($this, 'email_subject_callback'),
            'giraforms_settings',
            'giraforms_email_section'
        );
        // Privacy section
        add_settings_section(
            'giraforms_privacy_section',
            __( 'Privacy', 'giraforms' ),
            array($this, 'privacy_section_callback'),
            'giraforms_settings'
        );
        add_settings_field(
            'disable_ip_collection',
            __( 'IP Address Collection', 'giraforms' ),
            array($this, 'disable_ip_collection_callback'),
            'giraforms_settings',
            'giraforms_privacy_section'
        );
        add_settings_field(
            'disable_user_agent_collection',
            __( 'User Agent Collection', 'giraforms' ),
            array($this, 'disable_user_agent_collection_callback'),
            'giraforms_settings',
            'giraforms_privacy_section'
        );
        // Data management section
        add_settings_section(
            'giraforms_data_section',
            __( 'Data Management', 'giraforms' ),
            array($this, 'data_section_callback'),
            'giraforms_settings'
        );
        add_settings_field(
            'delete_data_on_uninstall',
            __( 'Delete data on uninstall', 'giraforms' ),
            array($this, 'delete_data_callback'),
            'giraforms_settings',
            'giraforms_data_section'
        );
        add_settings_field(
            'delete_all_submissions',
            __( 'Delete All Submissions', 'giraforms' ),
            array($this, 'delete_all_submissions_callback'),
            'giraforms_settings',
            'giraforms_data_section'
        );
    }

    /**
     * Email section callback.
     */
    public function email_section_callback() {
        echo '<p>' . esc_html__( 'Configure email notification settings for your forms.', 'giraforms' ) . '</p>';
    }

    /**
     * Privacy section callback.
     */
    public function privacy_section_callback() {
        echo '<p>' . esc_html__( 'Configure privacy-related settings for GDPR/RGPD compliance.', 'giraforms' ) . '</p>';
    }

    /**
     * Disable IP collection callback.
     */
    public function disable_ip_collection_callback() {
        $settings = $this->get_settings();
        $disable_ip = ( isset( $settings['disable_ip_collection'] ) ? $settings['disable_ip_collection'] : '0' );
        ?>
		<label>
			<input
				type="checkbox"
				name="<?php 
        echo esc_attr( $this->option_name );
        ?>[disable_ip_collection]"
				value="1"
				<?php 
        checked( $disable_ip, '1' );
        ?>
			/>
			<?php 
        esc_html_e( 'Do not collect visitor IP addresses', 'giraforms' );
        ?>
		</label>
		<p class="description">
			<?php 
        esc_html_e( 'When enabled, IP addresses will not be stored with form submissions. Note: IP-based rate limiting will be disabled when this option is active.', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Disable User Agent collection callback.
     */
    public function disable_user_agent_collection_callback() {
        $settings = $this->get_settings();
        $disable_user_agent = ( isset( $settings['disable_user_agent_collection'] ) ? $settings['disable_user_agent_collection'] : '0' );
        ?>
		<label>
			<input
				type="checkbox"
				name="<?php 
        echo esc_attr( $this->option_name );
        ?>[disable_user_agent_collection]"
				value="1"
				<?php 
        checked( $disable_user_agent, '1' );
        ?>
			/>
			<?php 
        esc_html_e( 'Do not collect visitor user agents', 'giraforms' );
        ?>
		</label>
		<p class="description">
			<?php 
        esc_html_e( 'When enabled, user agent strings (browser and device information) will not be stored with form submissions.', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Data management section callback.
     */
    public function data_section_callback() {
        echo '<p>' . esc_html__( 'Manage your form submissions data.', 'giraforms' ) . '</p>';
    }

    /**
     * Notification emails callback.
     */
    public function notification_emails_callback() {
        $settings = $this->get_settings();
        $emails = ( isset( $settings['notification_emails'] ) ? $settings['notification_emails'] : get_option( 'admin_email' ) );
        ?>
		<div class="giraforms-email-manager">
			<div class="giraforms-email-tags"></div>

			<div class="giraforms-email-input-wrapper">
				<input
					type="email"
					id="giraforms_new_email"
					placeholder="<?php 
        esc_attr_e( 'Enter email address...', 'giraforms' );
        ?>"
					class="regular-text"
				/>
				<button type="button" id="giraforms_add_email_btn" class="button button-secondary">
					<?php 
        esc_html_e( 'Add Email', 'giraforms' );
        ?>
				</button>
			</div>
			<div class="validation-message" style="display: none;"></div>

			<input
				type="hidden"
				name="<?php 
        echo esc_attr( $this->option_name );
        ?>[notification_emails]"
				id="giraforms_notification_emails_hidden"
				value="<?php 
        echo esc_attr( $emails );
        ?>"
			/>

			<p class="description" style="margin-top: 10px;">
				<?php 
        esc_html_e( 'Add email addresses to receive form notifications. If empty, notifications will be sent to the site administrator.', 'giraforms' );
        ?>
			</p>
		</div>
		<?php 
    }

    /**
     * Email from name callback.
     */
    public function email_from_name_callback() {
        $settings = $this->get_settings();
        $from_name = ( isset( $settings['email_from_name'] ) ? $settings['email_from_name'] : get_bloginfo( 'name' ) );
        ?>
		<input
			type="text"
			name="<?php 
        echo esc_attr( $this->option_name );
        ?>[email_from_name]"
			value="<?php 
        echo esc_attr( $from_name );
        ?>"
			class="regular-text"
		/>
		<p class="description">
			<?php 
        esc_html_e( 'The name that will appear as the email sender.', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Email from address callback.
     */
    public function email_from_address_callback() {
        $settings = $this->get_settings();
        $from_address = ( isset( $settings['email_from_address'] ) ? $settings['email_from_address'] : get_option( 'admin_email' ) );
        ?>
		<input
			type="email"
			name="<?php 
        echo esc_attr( $this->option_name );
        ?>[email_from_address]"
			value="<?php 
        echo esc_attr( $from_address );
        ?>"
			class="regular-text"
		/>
		<p class="description">
			<?php 
        esc_html_e( 'The email address that will appear as the sender.', 'giraforms' );
        ?>
			<br>
			<strong><?php 
        esc_html_e( 'Important:', 'giraforms' );
        ?></strong>
			<?php 
        esc_html_e( 'For better email deliverability, use an email address linked to your domain (e.g., contact@yourdomain.com) rather than a generic address (e.g., yoursite@gmail.com).', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Email subject callback.
     */
    public function email_subject_callback() {
        $settings = $this->get_settings();
        $subject = ( isset( $settings['email_subject'] ) ? $settings['email_subject'] : __( 'New form submission', 'giraforms' ) );
        ?>
		<input
			type="text"
			name="<?php 
        echo esc_attr( $this->option_name );
        ?>[email_subject]"
			value="<?php 
        echo esc_attr( $subject );
        ?>"
			class="regular-text"
		/>
		<p class="description">
			<?php 
        echo wp_kses_post( sprintf( 
            /* translators: %s: available tags */
            __( 'Default email subject. Available variables: %s', 'giraforms' ),
            '<code>{form_name}</code>, <code>{site_name}</code>, <code>{submission_id}</code>'
         ) );
        ?>
		</p>
		<?php 
    }

    /**
     * Delete data callback.
     */
    public function delete_data_callback() {
        $settings = $this->get_settings();
        $delete_data = ( isset( $settings['delete_data_on_uninstall'] ) ? $settings['delete_data_on_uninstall'] : '0' );
        ?>
		<label>
			<input
				type="checkbox"
				name="<?php 
        echo esc_attr( $this->option_name );
        ?>[delete_data_on_uninstall]"
				value="1"
				<?php 
        checked( $delete_data, '1' );
        ?>
			/>
			<?php 
        esc_html_e( 'Delete all data (submissions, settings) when uninstalling the plugin', 'giraforms' );
        ?>
		</label>
		<p class="description">
			<?php 
        esc_html_e( '⚠️ Warning: This action is irreversible!', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Delete all submissions callback.
     */
    public function delete_all_submissions_callback() {
        global $wpdb;
        // Count total submissions
        $submissions_table = $wpdb->prefix . 'giraforms_submissions';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $submissions_table ) );
        $count = ( $count ? intval( $count ) : 0 );
        ?>
		<div class="giraforms-delete-submissions-section">
			<p class="description" style="margin-bottom: 15px;">
				<?php 
        echo esc_html( sprintf( 
            /* translators: %d: number of submissions */
            _n(
                'You currently have %d submission in the database.',
                'You currently have %d submissions in the database.',
                $count,
                'giraforms'
            ),
            $count
         ) );
        ?>
			</p>

			<?php 
        if ( $count > 0 ) {
            ?>
				<p class="description" style="margin-bottom: 15px; color: #d63638;">
					<strong><?php 
            esc_html_e( '⚠️ Warning: This will permanently delete ALL form submissions. This action cannot be undone!', 'giraforms' );
            ?></strong>
				</p>

				<p>
					<button type="button" class="button button-secondary giraforms-delete-submissions-btn" style="background: #d63638; border-color: #d63638; color: #fff;">
						<span class="dashicons dashicons-trash" style="margin-top: 3px;"></span>
						<?php 
            esc_html_e( 'Delete All Submissions', 'giraforms' );
            ?>
					</button>
				</p>
			<?php 
        } else {
            ?>
				<p class="description">
					<?php 
            esc_html_e( 'No submissions to delete.', 'giraforms' );
            ?>
				</p>
			<?php 
        }
        ?>
		</div>
		<?php 
    }

    /**
     * Handle delete all submissions request.
     */
    public function handle_delete_submissions() {
        // Check user capabilities
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'giraforms' ) );
        }
        // Verify nonce
        if ( !isset( $_POST['giraforms_delete_submissions_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['giraforms_delete_submissions_nonce'] ) ), 'giraforms_delete_submissions' ) ) {
            wp_die( esc_html__( 'Security check failed.', 'giraforms' ) );
        }
        global $wpdb;
        // Delete from submission meta table first (foreign key constraint)
        $submission_meta_table = $wpdb->prefix . 'giraforms_submission_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', $submission_meta_table ) );
        // Delete from submissions table
        $submissions_table = $wpdb->prefix . 'giraforms_submissions';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $deleted = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', $submissions_table ) );
        // Clear any cached data
        wp_cache_flush();
        // Redirect back with success message
        $redirect_url = add_query_arg( array(
            'page'                => 'giraforms-settings',
            'submissions_deleted' => ( $deleted !== false ? 'success' : 'error' ),
        ), admin_url( 'admin.php' ) );
        wp_safe_redirect( $redirect_url );
        exit;
    }

    /**
     * Sanitize settings.
     *
     * @param array $input Input settings.
     * @return array
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();
        // Notification emails
        if ( isset( $input['notification_emails'] ) ) {
            $emails = array_map( 'trim', explode( "\n", $input['notification_emails'] ) );
            $emails = array_filter( $emails, 'is_email' );
            $sanitized['notification_emails'] = implode( "\n", $emails );
        }
        // From name
        if ( isset( $input['email_from_name'] ) ) {
            $sanitized['email_from_name'] = sanitize_text_field( $input['email_from_name'] );
        }
        // From address
        if ( isset( $input['email_from_address'] ) ) {
            $sanitized['email_from_address'] = sanitize_email( $input['email_from_address'] );
        }
        // Subject
        if ( isset( $input['email_subject'] ) ) {
            $sanitized['email_subject'] = sanitize_text_field( $input['email_subject'] );
        }
        // Delete data
        $sanitized['delete_data_on_uninstall'] = ( isset( $input['delete_data_on_uninstall'] ) ? '1' : '0' );
        // Privacy
        $sanitized['disable_ip_collection'] = ( isset( $input['disable_ip_collection'] ) ? '1' : '0' );
        $sanitized['disable_user_agent_collection'] = ( isset( $input['disable_user_agent_collection'] ) ? '1' : '0' );
        // Preserve integration keys (managed in Integrations page).
        // Keys may come from $input (when Integrations calls update_option) or from existing DB value.
        if ( isset( $input['turnstile_site_key'] ) ) {
            $sanitized['turnstile_site_key'] = sanitize_text_field( $input['turnstile_site_key'] );
        } elseif ( !isset( $sanitized['turnstile_site_key'] ) ) {
            $existing_settings = get_option( $this->option_name, array() );
            if ( isset( $existing_settings['turnstile_site_key'] ) ) {
                $sanitized['turnstile_site_key'] = $existing_settings['turnstile_site_key'];
            }
        }
        if ( isset( $input['turnstile_secret_key'] ) ) {
            $sanitized['turnstile_secret_key'] = sanitize_text_field( $input['turnstile_secret_key'] );
        } elseif ( !isset( $sanitized['turnstile_secret_key'] ) ) {
            $existing_settings = get_option( $this->option_name, array() );
            if ( isset( $existing_settings['turnstile_secret_key'] ) ) {
                $sanitized['turnstile_secret_key'] = $existing_settings['turnstile_secret_key'];
            }
        }
        if ( isset( $input['brevo_api_key'] ) ) {
            $sanitized['brevo_api_key'] = sanitize_text_field( $input['brevo_api_key'] );
        } elseif ( !isset( $sanitized['brevo_api_key'] ) ) {
            $existing_settings = get_option( $this->option_name, array() );
            if ( isset( $existing_settings['brevo_api_key'] ) ) {
                $sanitized['brevo_api_key'] = $existing_settings['brevo_api_key'];
            }
        }
        // Preserve Stripe keys.
        $stripe_keys = array(
            'stripe_publishable_key',
            'stripe_secret_key',
            'stripe_mode',
            'stripe_test_publishable_key',
            'stripe_test_secret_key',
            'stripe_live_publishable_key',
            'stripe_live_secret_key',
            'stripe_test_webhook_secret',
            'stripe_live_webhook_secret'
        );
        foreach ( $stripe_keys as $key ) {
            if ( isset( $input[$key] ) ) {
                if ( 'stripe_mode' === $key ) {
                    $sanitized[$key] = ( in_array( $input[$key], array('test', 'live'), true ) ? $input[$key] : 'test' );
                } else {
                    $sanitized[$key] = sanitize_text_field( $input[$key] );
                }
            } elseif ( !isset( $sanitized[$key] ) ) {
                $existing_settings = ( isset( $existing_settings ) ? $existing_settings : get_option( $this->option_name, array() ) );
                if ( isset( $existing_settings[$key] ) ) {
                    $sanitized[$key] = $existing_settings[$key];
                }
            }
        }
        // Preserve captcha integration keys (reCAPTCHA v2, v3, hCaptcha).
        $captcha_keys = array(
            'recaptcha_v2_site_key',
            'recaptcha_v2_secret_key',
            'recaptcha_v3_site_key',
            'recaptcha_v3_secret_key',
            'hcaptcha_site_key',
            'hcaptcha_secret_key'
        );
        foreach ( $captcha_keys as $key ) {
            if ( isset( $input[$key] ) ) {
                $sanitized[$key] = sanitize_text_field( $input[$key] );
            } elseif ( !isset( $sanitized[$key] ) ) {
                $existing_settings = ( isset( $existing_settings ) ? $existing_settings : get_option( $this->option_name, array() ) );
                if ( isset( $existing_settings[$key] ) ) {
                    $sanitized[$key] = $existing_settings[$key];
                }
            }
        }
        return $sanitized;
    }

    /**
     * Render settings page.
     */
    public function render_settings_page() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have the necessary permissions to access this page.', 'giraforms' ) );
        }
        // Check for submissions deletion message
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a URL feedback parameter for displaying notices only.
        if ( isset( $_GET['submissions_deleted'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a URL feedback parameter for displaying notices only.
            $message_type = sanitize_text_field( wp_unslash( $_GET['submissions_deleted'] ) );
            if ( 'success' === $message_type ) {
                echo '<div class="notice notice-success is-dismissible"><p>';
                esc_html_e( 'All submissions have been successfully deleted.', 'giraforms' );
                echo '</p></div>';
            } elseif ( 'error' === $message_type ) {
                echo '<div class="notice notice-error is-dismissible"><p>';
                esc_html_e( 'An error occurred while deleting submissions.', 'giraforms' );
                echo '</p></div>';
            }
        }
        ?>
		<div class="wrap giraforms-settings-page">
			<h1><?php 
        echo esc_html( get_admin_page_title() );
        ?></h1>

			<div class="giraforms-settings-header">
				<p><?php 
        esc_html_e( 'Configure global Giraforms settings for all your forms.', 'giraforms' );
        ?></p>
			</div>

			<?php 
        settings_errors();
        ?>

			<!-- Tabs Navigation -->
			<h2 class="nav-tab-wrapper">
				<a href="#" class="nav-tab" data-tab="email-settings">
					<span class="dashicons dashicons-email" style="margin-top: 3px;"></span>
					<?php 
        esc_html_e( 'Email Notifications', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="privacy-settings">
					<span class="dashicons dashicons-shield" style="margin-top: 3px;"></span>
					<?php 
        esc_html_e( 'Privacy', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="data-settings">
					<span class="dashicons dashicons-database" style="margin-top: 3px;"></span>
					<?php 
        esc_html_e( 'Data Management', 'giraforms' );
        ?>
				</a>
			</h2>

			<form method="post" action="options.php">
				<?php 
        settings_fields( 'giraforms_settings_group' );
        ?>

				<!-- Email Settings Tab -->
				<div id="email-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Email Notifications', 'giraforms' );
        ?></h2>
					<table class="form-table" role="presentation">
						<?php 
        do_settings_fields( 'giraforms_settings', 'giraforms_email_section' );
        ?>
					</table>
					<hr>
					<h3><?php 
        esc_html_e( 'Test Email', 'giraforms' );
        ?></h3>
					<p class="description" style="margin-bottom: 12px;">
						<?php 
        esc_html_e( 'Send a test email to your configured notification recipients to preview how notifications look with your current settings.', 'giraforms' );
        ?>
					</p>
					<button type="button" id="giraforms-send-test-email" class="button button-secondary" style="display: inline-flex; align-items: center; gap: 4px;">
						<span class="dashicons dashicons-email-alt"></span>
						<?php 
        esc_html_e( 'Send Test Email', 'giraforms' );
        ?>
					</button>
					<span id="giraforms-test-email-result" style="margin-left: 10px;"></span>
					<?php 
        wp_nonce_field( 'giraforms_test_email', 'giraforms_test_email_nonce', false );
        ?>
				</div>

				<!-- Privacy Settings Tab -->
				<div id="privacy-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Privacy', 'giraforms' );
        ?></h2>
					<table class="form-table" role="presentation">
						<?php 
        do_settings_fields( 'giraforms_settings', 'giraforms_privacy_section' );
        ?>
					</table>
				</div>

				<!-- Data Management Tab -->
				<div id="data-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Data Management', 'giraforms' );
        ?></h2>
					<table class="form-table" role="presentation">
						<?php 
        do_settings_fields( 'giraforms_settings', 'giraforms_data_section' );
        ?>
					</table>
				</div>

				<?php 
        submit_button( __( 'Save Changes', 'giraforms' ), 'primary large' );
        ?>
			</form>

			<!-- Hidden form for delete submissions (outside main settings form) -->
			<form id="giraforms-delete-submissions-form" method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>" style="display: none;">
				<input type="hidden" name="action" value="giraforms_delete_submissions" />
				<?php 
        wp_nonce_field( 'giraforms_delete_submissions', 'giraforms_delete_submissions_nonce' );
        ?>
			</form>

			<?php 
        if ( giraforms__fs()->is_not_paying() ) {
            ?>
					<?php 
            $premium_features = array(
                array(
                    'icon'        => 'money-alt',
                    'title'       => __( 'Stripe Payments', 'giraforms' ),
                    'description' => __( 'Accept online payments', 'giraforms' ),
                    'featured'    => true,
                ),
                array(
                    'icon'        => 'calendar-alt',
                    'title'       => __( 'Booking System', 'giraforms' ),
                    'description' => __( 'Time slots & capacity', 'giraforms' ),
                    'featured'    => true,
                ),
                array(
                    'icon'        => 'randomize',
                    'title'       => __( 'Conditional Logic', 'giraforms' ),
                    'description' => __( 'Dynamic forms', 'giraforms' ),
                    'featured'    => true,
                ),
                array(
                    'icon'        => 'upload',
                    'title'       => __( 'File Upload', 'giraforms' ),
                    'description' => __( 'Accept attachments', 'giraforms' ),
                ),
                array(
                    'icon'        => 'welcome-widgets-menus',
                    'title'       => __( 'Multi-step Forms', 'giraforms' ),
                    'description' => __( 'Progress bars', 'giraforms' ),
                ),
                array(
                    'icon'        => 'admin-links',
                    'title'       => __( 'Webhooks', 'giraforms' ),
                    'description' => __( 'Zapier & Make', 'giraforms' ),
                ),
                array(
                    'icon'        => 'email',
                    'title'       => __( 'Brevo Integration', 'giraforms' ),
                    'description' => __( 'Email marketing sync', 'giraforms' ),
                ),
                array(
                    'icon'        => 'star-filled',
                    'title'       => __( 'Rating Field', 'giraforms' ),
                    'description' => __( 'Collect feedback', 'giraforms' ),
                )
            );
            ?>
						<div class="giraforms-premium-notice">
							<div class="giraforms-premium-notice__header">
							<h3 class="giraforms-premium-notice__title">
								<span class="giraforms-premium-notice__logo" aria-hidden="true">
									<svg height="40" viewBox="0 0 440 440" width="40" xmlns="http://www.w3.org/2000/svg">
										<path d="m80 0h280c44.2 0 80 35.8 80 80v280c0 44.2-35.8 80-80 80h-280c-44.2 0-80-35.8-80-80v-280c0-44.2 35.8-80 80-80z" fill="#3858e9" fill-rule="evenodd"></path>
										<path d="m179 74 2.7-.5 3.2-.1 3.1.1 3 .5 4.1 2.7 2.9 3.3 2 5 .2 3.7v4.2 4.6l-.1 4.8v4.9 4.5l-.1 7.3h17l-.2-7.6-.1-4.8-.1-5.1-.2-5-.1-4.8.1-4.7.6-4 1.5-2.9 1.9-2.2 3.6-2.9 2-1 5.2-.4h3l2.8.4 4.1 2.7 2.9 3.3 2 5 .2 5.1v3.1 3.2 3.4 3.4 3.6 3.6 3.6l-.1 3.5v3.5l.1 3.3-.1 3.3v3l.9 5.4 1.6 2.3 2 1.9 3.4 2.8 1.2-2.1 1.7-2.8 2-3.1 2.1-3 2.2-2.6 2.2-2.3 2.3-2.2 2.3-1.9 4.2-2.5 3.8-1.5 2.9-.6 3.1-.4 2.9-.1h2.9c6.2 0 12.7.1 18.2.1.3 3.9.3 7 .3 10.9l-.3 4.1-1 3.5-1.3 3.1-1.4 2.9-1.3 2.5-1.8 3.2-2.2 2.8-3.6 4.1-2 2-2.4 1.9-2.9 1.6-2.9 1.3-2.8 1.1-2.4 1-3 2 2 1.8 2.9 2.6 3.2 2.9 3.5 3.2 3.6 3.3 3.6 3.5 3.8 3.6 3.9 3.6 3.9 3.4 3.8 3.4 3.6 3.5 3.6 3.5 3.5 3.5 3.1 3.6 2.8 3.7 2.2 3.9 1.2 4.4.5 4.5.2 4.4-.2 4.4-.3 4.3c-.8 8.1-2.5 11.1-8.3 11.6l-3.8.2c-2.6.1-5.1.3-7.7.6l-3.8.1c-10.5-.6-15.8-9.5-22.8-16.5l-65-1v131h-104c14.6-65.5 29.9-130.6 44-189 1.3-4.7 2.5-8.4 4-13l-5 .1h-3.1l-3.4.1-3.3.1h-3.2l-3.1-.1-2.9-.2-4.5-1.3-3.5-1.7-4.6-2.8-2.2-1.6-2.2-1.6-3.7-3.1-3.3-3.9-1.7-3-1.7-3.2-1.4-3-1.2-2.8-1-4-.1-3.7c0-3.8.1-7.9.1-11.3 9.4.1 16.7-.6 25 0l5.1 1.3 3.9 1.7 4.1 2.7 3.9 3.3 3.7 3.4 3.3 3.6 2.1 3.6 1.9 4.4 1 4.7.7 4.8.8 4.8.5 3.7.8-4.1 1.1-5.3 1.1-5.2 1-4.4 1-2 .2-5.3v-3.3-3.7l.1-3.7v-3.8-4l.1-4v-4-4l.1-3.8v-3.7-3.6l.1-3.4v-3l.4-2.7 1.4-2.7 1.6-2.3 1.9-2.3z" fill="#fff"></path>
										<path d="m230.2 191.7c-7.8 0-14-6.2-14-14 0-7.7 6.2-13.9 14-13.9 7.7 0 14 6.2 14 13.9 0 7.8-6.3 14-14 14z" fill="#3858e9" fill-rule="evenodd"></path>
									</svg>
									</span>
									<span><?php 
            esc_html_e( 'Grow conversions with', 'giraforms' );
            ?></span>
									<span class="giraforms-premium-notice__brand">
										<span class="giraforms-premium-notice__brand-text"><?php 
            esc_html_e( 'giraforms', 'giraforms' );
            ?></span>
										<span class="giraforms-premium-notice__pro-badge"><?php 
            esc_html_e( 'PRO', 'giraforms' );
            ?></span>
									</span>
								</h3>
								<p class="giraforms-premium-notice__subtitle">
									<?php 
            esc_html_e( 'Accept payments, automate workflows, and launch high-converting forms in minutes.', 'giraforms' );
            ?>
								</p>
							</div>

							<div class="giraforms-premium-notice__content">
								<input type="checkbox" id="giraforms-premium-features-toggle" class="giraforms-premium-notice__mobile-toggle-input" />
								<ul class="giraforms-premium-notice__features">
									<?php 
            foreach ( $premium_features as $index => $feature ) {
                ?>
										<?php 
                $feature_classes = array('giraforms-premium-notice__feature');
                if ( !empty( $feature['featured'] ) ) {
                    $feature_classes[] = 'is-featured';
                }
                if ( $index >= 4 ) {
                    $feature_classes[] = 'is-mobile-optional';
                }
                ?>
										<li class="<?php 
                echo esc_attr( implode( ' ', $feature_classes ) );
                ?>">
											<span class="dashicons dashicons-<?php 
                echo esc_attr( $feature['icon'] );
                ?>" aria-hidden="true"></span>
											<div>
												<strong class="giraforms-premium-notice__feature-title"><?php 
                echo esc_html( $feature['title'] );
                ?></strong>
												<span class="giraforms-premium-notice__feature-description"><?php 
                echo esc_html( $feature['description'] );
                ?></span>
										</div>
									</li>
									<?php 
            }
            ?>
								</ul>
								<label for="giraforms-premium-features-toggle" class="giraforms-premium-notice__mobile-toggle-label">
									<?php 
            esc_html_e( 'Show or hide features', 'giraforms' );
            ?>
								</label>

								<div class="giraforms-premium-notice__actions">
									<a href="<?php 
            echo esc_url( giraforms__fs()->get_upgrade_url() );
            ?>" class="button button-primary giraforms-premium-notice__button-primary" aria-describedby="giraforms-premium-cta-note">
										<?php 
            esc_html_e( 'View Pricing', 'giraforms' );
            ?>
									</a>
									<a href="https://giraforms.com/#features" target="_blank" class="button giraforms-premium-notice__button-secondary" rel="noopener noreferrer">
										<?php 
            esc_html_e( 'See All Features', 'giraforms' );
            ?>
									</a>
									<span class="giraforms-premium-notice__guarantee">
										<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
										<?php 
            esc_html_e( 'Satisfaction guarantee', 'giraforms' );
            ?>
									</span>
									<span id="giraforms-premium-cta-note" class="giraforms-premium-notice__cta-note">
										<?php 
            esc_html_e( 'Quick setup, no migration required.', 'giraforms' );
            ?>
									</span>
								</div>
							</div>
						</div>
				<?php 
        }
        ?>
		</div>
		<?php 
    }

    /**
     * Get settings.
     *
     * @return array
     */
    public function get_settings() {
        $defaults = array(
            'notification_emails'           => get_option( 'admin_email' ),
            'email_from_name'               => get_bloginfo( 'name' ),
            'email_from_address'            => get_option( 'admin_email' ),
            'email_subject'                 => __( 'New form submission', 'giraforms' ),
            'delete_data_on_uninstall'      => '0',
            'disable_ip_collection'         => '0',
            'disable_user_agent_collection' => '0',
            'turnstile_site_key'            => '',
            'turnstile_secret_key'          => '',
            'recaptcha_v2_site_key'         => '',
            'recaptcha_v2_secret_key'       => '',
            'recaptcha_v3_site_key'         => '',
            'recaptcha_v3_secret_key'       => '',
            'hcaptcha_site_key'             => '',
            'hcaptcha_secret_key'           => '',
            'brevo_api_key'                 => '',
            'stripe_publishable_key'        => '',
            'stripe_secret_key'             => '',
            'stripe_mode'                   => 'test',
            'stripe_test_publishable_key'   => '',
            'stripe_test_secret_key'        => '',
            'stripe_live_publishable_key'   => '',
            'stripe_live_secret_key'        => '',
            'stripe_test_webhook_secret'    => '',
            'stripe_live_webhook_secret'    => '',
        );
        $settings = get_option( $this->option_name, array() );
        return wp_parse_args( $settings, $defaults );
    }

    /**
     * Get a specific setting.
     *
     * @param string $key     Setting key.
     * @param mixed  $default Default value.
     * @return mixed
     */
    public function get_setting( $key, $default = null ) {
        $settings = $this->get_settings();
        return ( isset( $settings[$key] ) ? $settings[$key] : $default );
    }

}
