<?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: 13px;\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\tline-height: 1.5;\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-security-grid {\n\t\t\tdisplay: grid;\n\t\t\tgrid-template-columns: repeat(auto-fill, minmax(280px, 1fr));\n\t\t\tgap: 16px;\n\t\t\tmargin-top: 16px;\n\t\t}\n\t\t.giraforms-security-card {\n\t\t\tbackground: #fff;\n\t\t\tborder: 1px solid #e0e0e0;\n\t\t\tborder-radius: 8px;\n\t\t\tpadding: 18px 20px;\n\t\t\tdisplay: flex;\n\t\t\tgap: 14px;\n\t\t\talign-items: flex-start;\n\t\t}\n\t\t.giraforms-security-card-icon {\n\t\t\twidth: 36px;\n\t\t\theight: 36px;\n\t\t\tborder-radius: 8px;\n\t\t\tbackground: #f0fdf4;\n\t\t\tdisplay: flex;\n\t\t\talign-items: center;\n\t\t\tjustify-content: center;\n\t\t\tflex-shrink: 0;\n\t\t}\n\t\t.giraforms-security-card-icon .dashicons {\n\t\t\tcolor: #16a34a;\n\t\t\tfont-size: 18px;\n\t\t\twidth: 18px;\n\t\t\theight: 18px;\n\t\t}\n\t\t.giraforms-security-card-body h4 {\n\t\t\tmargin: 0 0 4px;\n\t\t\tfont-size: 13px;\n\t\t\tfont-weight: 600;\n\t\t}\n\t\t.giraforms-security-card-body p {\n\t\t\tmargin: 0;\n\t\t\tfont-size: 12px;\n\t\t\tcolor: #757575;\n\t\t\tline-height: 1.5;\n\t\t}\n\t\t.giraforms-security-intro {\n\t\t\tdisplay: flex;\n\t\t\talign-items: center;\n\t\t\tgap: 10px;\n\t\t\tbackground: #f0fdf4;\n\t\t\tborder: 1px solid #bbf7d0;\n\t\t\tborder-radius: 6px;\n\t\t\tpadding: 12px 16px;\n\t\t\tfont-size: 13px;\n\t\t\tcolor: #166534;\n\t\t}\n\t\t.giraforms-security-intro .dashicons {\n\t\t\tcolor: #16a34a;\n\t\t\tflex-shrink: 0;\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// Hide save button on read-only tabs\n\t\t\t\tif ( target === 'security-settings' ) {\n\t\t\t\t\t\$('.submit').hide();\n\t\t\t\t} else {\n\t\t\t\t\t\$('.submit').show();\n\t\t\t\t}\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\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'
        );
        add_settings_field(
            'show_email_attribution',
            __( '"Powered by" footer', 'giraforms' ),
            array($this, 'show_email_attribution_callback'),
            'giraforms_settings',
            'giraforms_email_section'
        );
        // Submissions section
        add_settings_section(
            'giraforms_submissions_section',
            __( 'Submissions', 'giraforms' ),
            array($this, 'submissions_section_callback'),
            'giraforms_settings'
        );
        add_settings_field(
            'submission_default_status',
            __( 'New Submission Status', 'giraforms' ),
            array($this, 'submission_default_status_callback'),
            'giraforms_settings',
            'giraforms_submissions_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>';
    }

    /**
     * Submissions section callback.
     */
    public function submissions_section_callback() {
        echo '<p>' . esc_html__( 'Configure how new form submissions are handled.', '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;">
						<?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;
    }

    /**
     * Show email attribution callback.
     */
    public function show_email_attribution_callback() {
        $settings = $this->get_settings();
        $show_attribution = ( isset( $settings['show_email_attribution'] ) ? (bool) $settings['show_email_attribution'] : false );
        ?>
		<label>
			<input
				type="checkbox"
				name="<?php 
        echo esc_attr( $this->option_name );
        ?>[show_email_attribution]"
				value="1"
				<?php 
        checked( $show_attribution, true );
        ?>
			/>
			<?php 
        esc_html_e( 'Show "Powered by giraforms" in emails', 'giraforms' );
        ?>
		</label>
		<p class="description">
			<?php 
        esc_html_e( 'Help promote the plugin ✓', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * Submission default status callback.
     */
    public function submission_default_status_callback() {
        $settings = $this->get_settings();
        $value = ( isset( $settings['submission_default_status'] ) ? $settings['submission_default_status'] : 'unread' );
        ?>
		<select name="<?php 
        echo esc_attr( $this->option_name );
        ?>[submission_default_status]">
			<option value="unread" <?php 
        selected( $value, 'unread' );
        ?>><?php 
        esc_html_e( 'Unread (default)', 'giraforms' );
        ?></option>
			<option value="read" <?php 
        selected( $value, 'read' );
        ?>><?php 
        esc_html_e( 'Read', 'giraforms' );
        ?></option>
		</select>
		<p class="description">
			<?php 
        esc_html_e( 'Status automatically assigned to new submissions.', 'giraforms' );
        ?>
		</p>
		<?php 
    }

    /**
     * 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' );
        // Email attribution (opt-in, available to all)
        $sanitized['show_email_attribution'] = ( isset( $input['show_email_attribution'] ) ? true : false );
        // Default submission status
        $allowed_statuses = array('unread', 'read');
        $status_input = ( isset( $input['submission_default_status'] ) ? $input['submission_default_status'] : 'unread' );
        $sanitized['submission_default_status'] = ( in_array( $status_input, $allowed_statuses, true ) ? $status_input : 'unread' );
        // 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'];
            }
        }
        if ( isset( $input['mailchimp_api_key'] ) ) {
            $sanitized['mailchimp_api_key'] = sanitize_text_field( $input['mailchimp_api_key'] );
        } elseif ( !isset( $sanitized['mailchimp_api_key'] ) ) {
            $existing_settings = ( isset( $existing_settings ) ? $existing_settings : get_option( $this->option_name, array() ) );
            if ( isset( $existing_settings['mailchimp_api_key'] ) ) {
                $sanitized['mailchimp_api_key'] = $existing_settings['mailchimp_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="line-height: 1; margin: 0;"></span>
					<?php 
        esc_html_e( 'Email Notifications', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="submissions-settings">
					<span class="dashicons dashicons-feedback" style="line-height: 1; margin: 0;"></span>
					<?php 
        esc_html_e( 'Submissions', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="privacy-settings">
					<span class="dashicons dashicons-shield" style="line-height: 1; margin: 0;"></span>
					<?php 
        esc_html_e( 'Privacy', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="data-settings">
					<span class="dashicons dashicons-database" style="line-height: 1; margin: 0;"></span>
					<?php 
        esc_html_e( 'Data Management', 'giraforms' );
        ?>
				</a>
				<a href="#" class="nav-tab" data-tab="security-settings">
					<span class="dashicons dashicons-lock" style="line-height: 1; margin: 0;"></span>
					<?php 
        esc_html_e( 'Security', '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: 6px;">
						<span class="dashicons dashicons-email-alt" style="line-height: 1; margin: 0;"></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>

				<!-- Submissions Settings Tab -->
				<div id="submissions-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Submissions', 'giraforms' );
        ?></h2>
					<p class="description" style="margin-bottom: 16px;">
						<?php 
        esc_html_e( 'Configure how new form submissions are handled.', 'giraforms' );
        ?>
					</p>
					<table class="form-table" role="presentation">
						<?php 
        do_settings_fields( 'giraforms_settings', 'giraforms_submissions_section' );
        ?>
					</table>
				</div>

				<!-- Security Tab -->
				<div id="security-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Security', 'giraforms' );
        ?></h2>
					<p class="description" style="margin-bottom: 16px;">
						<?php 
        esc_html_e( 'Overview of the security protections active on your forms.', 'giraforms' );
        ?>
					</p>

					<div class="giraforms-security-intro">
						<span class="dashicons dashicons-yes-alt"></span>
						<?php 
        esc_html_e( 'All protections below are active on every form on your site.', 'giraforms' );
        ?>
					</div>

					<?php 
        $settings = get_option( $this->option_name, array() );
        $has_turnstile = !empty( $settings['turnstile_site_key'] ) && !empty( $settings['turnstile_secret_key'] );
        $has_recaptcha = !empty( $settings['recaptcha_v2_site_key'] ) && !empty( $settings['recaptcha_v2_secret_key'] ) || !empty( $settings['recaptcha_v3_site_key'] ) && !empty( $settings['recaptcha_v3_secret_key'] );
        $has_hcaptcha = !empty( $settings['hcaptcha_site_key'] ) && !empty( $settings['hcaptcha_secret_key'] );
        $has_captcha = $has_turnstile || $has_recaptcha || $has_hcaptcha;
        $captcha_names = array();
        if ( $has_turnstile ) {
            $captcha_names[] = 'Cloudflare Turnstile';
        }
        if ( $has_recaptcha ) {
            $captcha_names[] = 'Google reCAPTCHA';
        }
        if ( $has_hcaptcha ) {
            $captcha_names[] = 'hCaptcha';
        }
        $disallowed_keys = trim( (string) get_option( 'disallowed_keys', '' ) );
        $has_disallowed = '' !== $disallowed_keys;
        $features = array(
            array(
                'icon'  => 'admin-network',
                'title' => __( 'WordPress Nonce', 'giraforms' ),
                'desc'  => __( 'Every submission is verified with a cryptographic token. Prevents CSRF attacks and forged requests.', 'giraforms' ),
            ),
            array(
                'icon'  => 'hidden',
                'title' => __( 'Honeypot', 'giraforms' ),
                'desc'  => __( 'A hidden field invisible to humans traps bots that fill all form fields automatically.', 'giraforms' ),
            ),
            array(
                'icon'  => 'clock',
                'title' => __( 'Timing Check', 'giraforms' ),
                'desc'  => __( 'Submissions completed in under 3 seconds are rejected — no human can read and fill a form that fast.', 'giraforms' ),
            ),
            array(
                'icon'  => 'dashboard',
                'title' => __( 'Rate Limiting', 'giraforms' ),
                'desc'  => sprintf( 
                    /* translators: %d: number of allowed submissions per hour */
                    __( 'Each IP address is limited to %d submissions per hour to prevent flooding.', 'giraforms' ),
                    apply_filters( 'giraforms_rate_limit', 5 )
                 ),
            ),
            array(
                'icon'  => 'editor-spellcheck',
                'title' => __( 'Disallowed Words', 'giraforms' ),
                'desc'  => ( $has_disallowed ? __( 'Submissions, IP addresses and user agents are checked against your WordPress disallowed words list.', 'giraforms' ) : __( 'Disallowed words list check is active. Add words or IP addresses to block matching submissions.', 'giraforms' ) ),
                'link'  => array(
                    'url'   => admin_url( 'options-discussion.php' ) . '#disallowed_keys',
                    'label' => __( 'Settings → Discussion', 'giraforms' ),
                ),
            ),
            array(
                'icon'  => 'lock',
                'title' => __( 'API Keys Encrypted', 'giraforms' ),
                'desc'  => __( 'Integration secrets (Stripe, Brevo, captcha keys) are encrypted at rest using libsodium. A database dump alone cannot expose them.', 'giraforms' ),
            )
        );
        if ( $has_captcha ) {
            $features[] = array(
                'icon'  => 'shield',
                'title' => __( 'Captcha', 'giraforms' ),
                'desc'  => sprintf( 
                    /* translators: %s: comma-separated list of configured captcha providers */
                    __( 'Configured: %s.', 'giraforms' ),
                    implode( ', ', $captcha_names )
                 ),
            );
        }
        ?>

					<div class="giraforms-security-grid">
						<?php 
        foreach ( $features as $feature ) {
            ?>
							<div class="giraforms-security-card">
								<div class="giraforms-security-card-icon">
									<span class="dashicons dashicons-<?php 
            echo esc_attr( $feature['icon'] );
            ?>"></span>
								</div>
								<div class="giraforms-security-card-body">
									<h4><?php 
            echo esc_html( $feature['title'] );
            ?></h4>
									<p>
										<?php 
            echo esc_html( $feature['desc'] );
            ?>
										<?php 
            if ( !empty( $feature['link'] ) ) {
                ?>
											<br><br><a href="<?php 
                echo esc_url( $feature['link']['url'] );
                ?>" style="white-space:nowrap;"><?php 
                echo esc_html( $feature['link']['label'] );
                ?></a>
										<?php 
            }
            ?>
									</p>
								</div>
							</div>
						<?php 
        }
        ?>
					</div>
				</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>

					<?php 
        ?>
				</div>

				<!-- Data Management Tab -->
				<div id="data-settings" class="tab-content">
					<h2><?php 
        esc_html_e( 'Data Management', 'giraforms' );
        ?></h2>

					<?php 
        // Database usage summary
        global $wpdb;
        $tables = array(
            $wpdb->prefix . 'giraforms_submissions'     => __( 'Submissions', 'giraforms' ),
            $wpdb->prefix . 'giraforms_submission_meta' => __( 'Submission data', 'giraforms' ),
        );
        // SHOW TABLE STATUS works with standard DB user rights (no information_schema needed)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $status_rows = $wpdb->get_results( $wpdb->prepare( 'SHOW TABLE STATUS LIKE %s', $wpdb->esc_like( $wpdb->prefix . 'giraforms_' ) . '%' ) );
        $total_bytes = 0;
        $by_table = array();
        foreach ( $status_rows as $row ) {
            $name = $row->Name;
            if ( isset( $tables[$name] ) ) {
                $by_table[$name] = (object) array(
                    'table_rows' => (int) $row->Rows,
                    'size_bytes' => (int) $row->Data_length + (int) $row->Index_length,
                );
                $total_bytes += $by_table[$name]->size_bytes;
            }
        }
        $format_size = function ( $bytes ) {
            if ( $bytes >= 1048576 ) {
                return round( $bytes / 1048576, 1 ) . ' MB';
            }
            if ( $bytes >= 1024 ) {
                return round( $bytes / 1024, 1 ) . ' KB';
            }
            return $bytes . ' B';
        };
        ?>
					<div style="background:#f9f9f9;border:1px solid #e0e0e0;border-radius:6px;padding:16px 20px;margin-bottom:20px;">
						<p style="margin:0 0 10px;font-weight:600;font-size:13px;">
							<?php 
        esc_html_e( 'Database usage', 'giraforms' );
        ?>
							<span style="font-weight:400;color:#777;margin-left:8px;"><?php 
        echo esc_html( $format_size( $total_bytes ) );
        ?> <?php 
        esc_html_e( 'total', 'giraforms' );
        ?></span>
						</p>
						<table style="width:100%;border-collapse:collapse;font-size:13px;">
							<?php 
        foreach ( $tables as $table_name => $label ) {
            $info = ( isset( $by_table[$table_name] ) ? $by_table[$table_name] : null );
            $size = ( $info ? $format_size( (int) $info->size_bytes ) : '—' );
            $count = ( $info ? number_format_i18n( (int) $info->table_rows ) : '—' );
            $exists = $info !== null;
            ?>
							<tr style="border-top:1px solid #e8e8e8;">
								<td style="padding:6px 0;color:<?php 
            echo ( $exists ? '#333' : '#aaa' );
            ?>;"><?php 
            echo esc_html( $label );
            ?></td>
								<td style="padding:6px 0;color:#777;text-align:right;"><?php 
            echo ( $exists ? esc_html( $count ) . ' ' . esc_html__( 'rows', 'giraforms' ) : esc_html__( 'Not created', 'giraforms' ) );
            ?></td>
								<td style="padding:6px 0;font-weight:600;text-align:right;width:80px;color:<?php 
            echo ( $exists ? '#333' : '#aaa' );
            ?>;"><?php 
            echo esc_html( $size );
            ?></td>
							</tr>
							<?php 
        }
        ?>
						</table>
					</div>

					<table class="form-table" role="presentation">
						<?php 
        do_settings_fields( 'giraforms_settings', 'giraforms_data_section' );
        ?>
					</table>

					<?php 
        ?>

				</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-alt',
                    'title'       => __( 'Email Marketing', 'giraforms' ),
                    'description' => __( 'Brevo & Mailchimp 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',
            'disable_analytics'             => '0',
            'analytics_retention_days'      => 90,
            '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 );
    }

}
