<?php

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

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

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

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'admin_menu', array($this, 'add_integrations_page') );
        add_action( 'admin_post_giraforms_save_integrations', array($this, 'handle_save') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_styles') );
    }

    /**
     * Add integrations page to admin menu.
     */
    public function add_integrations_page() {
        add_submenu_page(
            'giraforms',
            __( 'Integrations', 'giraforms' ),
            __( 'Integrations', 'giraforms' ),
            'manage_options',
            'giraforms-integrations',
            array($this, 'render_integrations_page')
        );
    }

    /**
     * Handle saving integration keys.
     */
    public function handle_save() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have the necessary permissions to access this page.', 'giraforms' ) );
        }
        check_admin_referer( 'giraforms_integrations_nonce', '_giraforms_integrations_nonce' );
        $existing = get_option( $this->option_name, array() );
        // Only update keys that are present in the submitted form.
        if ( array_key_exists( 'turnstile_site_key', $_POST ) ) {
            $existing['turnstile_site_key'] = sanitize_text_field( wp_unslash( $_POST['turnstile_site_key'] ) );
        }
        if ( array_key_exists( 'turnstile_secret_key', $_POST ) ) {
            $val = sanitize_text_field( wp_unslash( $_POST['turnstile_secret_key'] ) );
            if ( '' !== $val ) {
                $existing['turnstile_secret_key'] = GiraForms_Encryption::encrypt( $val );
            }
        }
        // reCAPTCHA v2 keys.
        if ( array_key_exists( 'recaptcha_v2_site_key', $_POST ) ) {
            $existing['recaptcha_v2_site_key'] = sanitize_text_field( wp_unslash( $_POST['recaptcha_v2_site_key'] ) );
        }
        if ( array_key_exists( 'recaptcha_v2_secret_key', $_POST ) ) {
            $val = sanitize_text_field( wp_unslash( $_POST['recaptcha_v2_secret_key'] ) );
            if ( '' !== $val ) {
                $existing['recaptcha_v2_secret_key'] = GiraForms_Encryption::encrypt( $val );
            }
        }
        // reCAPTCHA v3 keys.
        if ( array_key_exists( 'recaptcha_v3_site_key', $_POST ) ) {
            $existing['recaptcha_v3_site_key'] = sanitize_text_field( wp_unslash( $_POST['recaptcha_v3_site_key'] ) );
        }
        if ( array_key_exists( 'recaptcha_v3_secret_key', $_POST ) ) {
            $val = sanitize_text_field( wp_unslash( $_POST['recaptcha_v3_secret_key'] ) );
            if ( '' !== $val ) {
                $existing['recaptcha_v3_secret_key'] = GiraForms_Encryption::encrypt( $val );
            }
        }
        // hCaptcha keys.
        if ( array_key_exists( 'hcaptcha_site_key', $_POST ) ) {
            $existing['hcaptcha_site_key'] = sanitize_text_field( wp_unslash( $_POST['hcaptcha_site_key'] ) );
        }
        if ( array_key_exists( 'hcaptcha_secret_key', $_POST ) ) {
            $val = sanitize_text_field( wp_unslash( $_POST['hcaptcha_secret_key'] ) );
            if ( '' !== $val ) {
                $existing['hcaptcha_secret_key'] = GiraForms_Encryption::encrypt( $val );
            }
        }
        update_option( $this->option_name, $existing );
        wp_safe_redirect( add_query_arg( array(
            'page'    => 'giraforms-integrations',
            'updated' => 'true',
        ), admin_url( 'admin.php' ) ), 302, 'Giraforms' );
        exit;
    }

    /**
     * Enqueue styles for integrations page.
     */
    public function enqueue_styles() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking page parameter for style enqueue.
        $page = ( isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '' );
        if ( 'giraforms-integrations' !== $page ) {
            return;
        }
        wp_add_inline_style( 'wp-admin', $this->get_inline_styles() );
        wp_enqueue_script( 'jquery' );
        wp_add_inline_script( 'jquery', "\n\t\t\tjQuery(document).ready(function(\$) {\n\t\t\t\t// Visibility toggle\n\t\t\t\t\$('.secret-key-toggle').on('click', function() {\n\t\t\t\t\tvar btn = \$(this);\n\t\t\t\t\tvar input = btn.siblings('input');\n\t\t\t\t\tvar icon = btn.find('.dashicons');\n\t\t\t\t\tif (input.attr('type') === 'password') {\n\t\t\t\t\t\tinput.attr('type', 'text');\n\t\t\t\t\t\ticon.removeClass('dashicons-visibility').addClass('dashicons-hidden');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput.attr('type', 'password');\n\t\t\t\t\t\ticon.removeClass('dashicons-hidden').addClass('dashicons-visibility');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Change / Cancel toggle for saved secret keys\n\t\t\t\t\$(document).on('click', '.secret-key-change-btn', function() {\n\t\t\t\t\tvar btn     = \$(this);\n\t\t\t\t\tvar wrapper = btn.closest('.secret-key-wrapper');\n\t\t\t\t\tvar input   = wrapper.find('input');\n\n\t\t\t\t\tif (wrapper.hasClass('is-editing')) {\n\t\t\t\t\t\t// Cancel — restore locked state\n\t\t\t\t\t\tinput\n\t\t\t\t\t\t\t.val(input.data('masked'))\n\t\t\t\t\t\t\t.removeAttr('name')\n\t\t\t\t\t\t\t.attr('readonly', true)\n\t\t\t\t\t\t\t.attr('type', 'password');\n\t\t\t\t\t\twrapper.find('.secret-key-toggle .dashicons')\n\t\t\t\t\t\t\t.removeClass('dashicons-hidden').addClass('dashicons-visibility');\n\t\t\t\t\t\twrapper.removeClass('is-editing');\n\t\t\t\t\t\tbtn.text(btn.data('label-change'));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Enter edit mode\n\t\t\t\t\t\tinput\n\t\t\t\t\t\t\t.val('')\n\t\t\t\t\t\t\t.attr('name', input.data('field-name'))\n\t\t\t\t\t\t\t.removeAttr('readonly');\n\t\t\t\t\t\twrapper.addClass('is-editing');\n\t\t\t\t\t\tbtn.text(btn.data('label-cancel'));\n\t\t\t\t\t\tinput.focus();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t" );
    }

    /**
     * Get inline styles for integrations page.
     *
     * @return string
     */
    private function get_inline_styles() {
        return '
			.giraforms-integrations-section {
				margin-top: 24px;
			}
			.giraforms-integrations-section:first-of-type {
				margin-top: 16px;
			}
			.giraforms-integrations-section-header {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-bottom: 4px;
			}
			.giraforms-integrations-section-title {
				margin: 0;
				font-size: 15px;
				font-weight: 600;
				color: #1d2327;
			}
			.giraforms-integrations-section-description {
				margin: 0 0 12px;
				color: #646970;
				font-size: 13px;
			}
			.giraforms-integrations-grid {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
				gap: 12px;
				margin-top: 0;
			}
			.giraforms-integration-card {
				background: #fff;
				border: 1px solid #dcdcde;
				border-radius: 6px;
				padding: 16px;
				position: relative;
				transition: border-color 0.2s ease, box-shadow 0.2s ease;
			}
			.giraforms-integration-card:hover {
				border-color: #c3c4c7;
				box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
			}
			.giraforms-integration-card .card-header {
				display: flex;
				align-items: center;
				gap: 10px;
				padding-bottom: 12px;
				margin-bottom: 10px;
				border-bottom: 1px solid #f0f0f1;
			}
			.giraforms-integration-card .card-icon {
				width: 36px;
				height: 36px;
				border-radius: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-shrink: 0;
				font-size: 14px;
				font-weight: 700;
				line-height: 1;
			}
			.giraforms-integration-card .card-icon.turnstile {
				background: #f28020;
				color: #fff;
			}
			.giraforms-integration-card .card-icon.webhooks {
				background: #edf2ff;
				color: #1d4ed8;
			}
			.giraforms-integration-card .card-icon.brevo {
				background: #0b996d;
				color: #fff;
			}
			.giraforms-integration-card .card-icon.recaptcha {
				background: #1538a9;
				color: #fff;
			}
			.giraforms-integration-card .card-icon.hcaptcha {
				background: #4ea5cb;
				color: #fff;
			}
			.giraforms-integration-card .card-icon.stripe {
				background: #635cff;
				color: #fff;
			}
			.giraforms-integration-card .card-icon.mailchimp {
				background: #ffe103;
				color: #000;
			}
			.giraforms-integration-card .card-header-info {
				flex: 1;
				min-width: 0;
			}
			.giraforms-integration-card .card-title {
				margin: 0;
				font-size: 14px;
				font-weight: 600;
			}
			.card-icon.turnstile ~ .card-header-info .card-title { color: #f28020; }
			.card-icon.recaptcha ~ .card-header-info .card-title { color: #1538a9; }
			.card-icon.hcaptcha   ~ .card-header-info .card-title { color: #4ea5cb; }
			.card-icon.brevo      ~ .card-header-info .card-title { color: #0b996d; }
			.card-icon.stripe     ~ .card-header-info .card-title { color: #635cff; }
			.card-icon.mailchimp  ~ .card-header-info .card-title { color: #000; }
			.giraforms-integration-card .card-title .badge-pro {
				display: inline-block;
				background: linear-gradient(135deg, #3858e9, #6366f1);
				color: #fff;
				font-size: 10px;
				font-weight: 700;
				padding: 1px 6px;
				border-radius: 8px;
				margin-left: 6px;
				vertical-align: middle;
				text-transform: uppercase;
				letter-spacing: 0.5px;
			}
			.giraforms-integration-card .card-status {
				display: inline-flex;
				align-items: center;
				gap: 4px;
				font-size: 11px;
				font-weight: 500;
				padding: 3px 8px;
				border-radius: 10px;
				flex-shrink: 0;
				white-space: nowrap;
			}
			.giraforms-integration-card .card-status.configured {
				background: rgba(0, 163, 42, 0.08);
				color: #00a32a;
			}
			.giraforms-integration-card .card-status.not-configured {
				background: rgba(0, 0, 0, 0.04);
				color: #787c82;
			}
			.giraforms-integration-card .card-status.requires-pro {
				background: #eef2ff;
				color: #3858e9;
			}
			.giraforms-integration-card .card-description {
				color: #50575e;
				margin: 0 0 10px 0;
				font-size: 13px;
				line-height: 1.5;
			}
			/* Collapsible form */
			.card-form-details {
				margin-top: 2px;
			}
			.card-form-details > summary {
				list-style: none;
				cursor: pointer;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 4px;
				background: #fff;
				border: 1px solid;
				font-weight: 500;
				color: var(--wp-admin-theme-color, #3858e9);
				user-select: none;
				transition: background 0.15s ease, border-color 0.15s ease;
				outline: none;
				min-height: 40px;
				margin: 0;
				padding: 0 16px;
			}
			.card-form-details > summary:hover {
				background: rgba(var(--wp-admin-theme-color--rgb, 56, 88, 233), .04);
				border-color: var(--wp-admin-theme-color-darker-20, #183ad6);
				color: var(--wp-admin-theme-color-darker-20, #183ad6);
			}
			.card-form-details > summary:focus-visible {
				box-shadow: 0 0 0 2px var(--wp-admin-theme-color, #3858e9);
			}
			.card-form-details > summary::-webkit-details-marker,
			.card-form-details > summary::marker {
				display: none;
				content: "";
			}
			.card-form-details > summary .summary-arrow {
				font-size: 16px;
				width: 16px;
				height: 16px;
				line-height: 1 !important;
				transition: transform 0.2s ease;
				flex-shrink: 0;
			}
			.card-form-details[open] > summary {
				background: rgba(var(--wp-admin-theme-color--rgb, 56, 88, 233), .04);
				border-color: var(--wp-admin-theme-color-darker-20, #183ad6);
				color: var(--wp-admin-theme-color-darker-20, #183ad6);
			}
			.card-form-details[open] > summary .summary-arrow {
				transform: rotate(90deg);
			}
			.card-form-details .card-fields {
				border-top: none;
				padding-top: 14px;
				margin-top: 0;
			}
			.card-form-details .card-action {
				padding-top: 12px;
				margin-top: 0;
				border-top: none;
			}
			/* Form fields */
			.giraforms-integration-card .card-fields label {
				display: block;
				font-weight: 500;
				margin-bottom: 4px;
				font-size: 12px;
				color: #1d2327;
			}
			.giraforms-integration-card .card-fields input[type="text"],
			.giraforms-integration-card .card-fields input[type="password"] {
				width: 100%;
				margin-bottom: 10px;
			}
			.giraforms-integration-card .card-fields .description {
				font-size: 12px;
				color: #757575;
				margin: -6px 0 10px 0;
			}
			.giraforms-integration-card .card-fields .card-fields-subsection {
				margin-top: 14px;
				padding-top: 12px;
				border-top: 1px dashed #e2e4e7;
			}
			.giraforms-integration-card .card-fields .card-fields-subsection:first-child {
				margin-top: 0;
				padding-top: 0;
				border-top: none;
			}
			.giraforms-integration-card .card-fields .card-fields-subsection-title {
				margin: 0 0 8px 0;
				font-size: 12px;
				font-weight: 600;
				color: #1d2327;
				text-transform: uppercase;
				letter-spacing: 0.3px;
			}
			.giraforms-integration-card .card-action {
				margin-top: 12px;
				padding-top: 12px;
				border-top: 1px solid #e2e4e7;
			}
			.giraforms-integration-card .card-fields .secret-key-wrapper {
				position: relative;
				display: flex;
				align-items: stretch;
				margin-bottom: 10px;
			}
			.giraforms-integration-card .card-fields .secret-key-wrapper input {
				margin-bottom: 0;
				border-top-right-radius: 0;
				border-bottom-right-radius: 0;
				flex: 1;
			}
			.giraforms-integration-card .card-fields .secret-key-wrapper.has-value:not(.is-editing) input {
				background: #f6f7f7;
				color: #787c82;
				cursor: default;
				font-family: monospace;
				letter-spacing: 0.05em;
			}
			.giraforms-integration-card .card-fields .secret-key-toggle {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 32px;
				border: 1px solid #8c8f94;
				border-left: none;
				border-radius: 0 4px 4px 0;
				background: #f0f0f1;
				cursor: pointer;
				color: #50575e;
				transition: color 0.15s ease;
				padding: 0;
			}
			.giraforms-integration-card .card-fields .secret-key-toggle:hover {
				color: #1d2327;
				background: #e8e8e9;
			}
			/* When a change button follows, toggle loses its right radius */
			.giraforms-integration-card .card-fields .secret-key-change-btn ~ .secret-key-toggle,
			.giraforms-integration-card .card-fields .secret-key-toggle:has(+ .secret-key-change-btn),
			.giraforms-integration-card .card-fields .secret-key-wrapper.is-editing .secret-key-toggle {
				border-top-right-radius: 0;
				border-bottom-right-radius: 0;
			}
			/* Hide toggle when locked (not editing) */
			.giraforms-integration-card .card-fields .secret-key-wrapper.has-value:not(.is-editing) .secret-key-toggle {
				display: none;
			}
			.giraforms-integration-card .card-fields .secret-key-change-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				border: 1px solid #8c8f94;
				border-left: none;
				border-radius: 0 4px 4px 0;
				background: #f0f0f1;
				cursor: pointer;
				color: #50575e;
				font-size: 12px;
				padding: 0 10px;
				white-space: nowrap;
				transition: color 0.15s ease, background 0.15s ease;
			}
			.giraforms-integration-card .card-fields .secret-key-change-btn:hover {
				color: #1d2327;
				background: #e8e8e9;
			}
			.giraforms-integration-card .card-fields .secret-key-wrapper.is-editing .secret-key-change-btn {
				color: #b32d2e;
			}
			.giraforms-integration-card .card-fields .secret-key-wrapper.is-editing .secret-key-change-btn:hover {
				background: #fcecec;
				border-color: #d63638;
			}
		';
    }

    /**
     * Mask a secret key showing only the last 4 characters.
     *
     * @param string $value Plain-text secret key.
     * @return string Masked representation.
     */
    private function mask_secret_key( $value ) {
        $len = mb_strlen( $value );
        $visible = min( 4, $len );
        $dots = min( 12, max( 0, $len - $visible ) );
        return str_repeat( "•", $dots ) . mb_substr( $value, -$visible );
    }

    /**
     * Render a secret key input field with locked/edit UX.
     *
     * When a value is saved the input is readonly with a masked value and has no
     * name attribute (so it is not submitted). A "Change" button switches it to
     * edit mode. When empty the input is directly editable.
     *
     * @param string $id          Input id attribute.
     * @param string $name        Input name attribute (used when editable).
     * @param string $value       Current plain-text value (empty string if none).
     * @param string $placeholder Optional placeholder for the empty editable state.
     */
    private function render_secret_key_field(
        $id,
        $name,
        $value,
        $placeholder = ''
    ) {
        $has_value = !empty( $value );
        $masked = ( $has_value ? $this->mask_secret_key( $value ) : '' );
        ?>
		<div class="secret-key-wrapper<?php 
        echo ( $has_value ? ' has-value' : '' );
        ?>">
			<input
				type="password"
				id="<?php 
        echo esc_attr( $id );
        ?>"
				<?php 
        if ( !$has_value ) {
            ?>name="<?php 
            echo esc_attr( $name );
            ?>"<?php 
        }
        ?>
				data-field-name="<?php 
        echo esc_attr( $name );
        ?>"
				<?php 
        if ( $has_value ) {
            ?>data-masked="<?php 
            echo esc_attr( $masked );
            ?>"<?php 
        }
        ?>
				value="<?php 
        echo ( $has_value ? esc_attr( $masked ) : '' );
        ?>"
				class="regular-text"
				<?php 
        if ( $has_value ) {
            ?>readonly<?php 
        }
        ?>
				<?php 
        if ( !$has_value && '' !== $placeholder ) {
            ?>placeholder="<?php 
            echo esc_attr( $placeholder );
            ?>"<?php 
        }
        ?>
			/>
			<button type="button" class="secret-key-toggle" aria-label="<?php 
        esc_attr_e( 'Toggle key visibility', 'giraforms' );
        ?>">
				<span class="dashicons dashicons-visibility"></span>
			</button>
			<?php 
        if ( $has_value ) {
            ?>
			<button
				type="button"
				class="secret-key-change-btn"
				data-label-change="<?php 
            esc_attr_e( 'Change', 'giraforms' );
            ?>"
				data-label-cancel="<?php 
            esc_attr_e( 'Cancel', 'giraforms' );
            ?>"
			><?php 
            esc_html_e( 'Change', 'giraforms' );
            ?></button>
			<?php 
        }
        ?>
		</div>
		<?php 
    }

    /**
     * Get letter marker for a service.
     *
     * @param string $service Service slug.
     * @return string
     */
    private function get_service_icon_letter( $service ) {
        $letters = array(
            'turnstile' => 'T',
            'recaptcha' => 're',
            'hcaptcha'  => 'h',
            'webhooks'  => 'W',
            'brevo'     => 'B',
            'mailchimp' => 'M',
            'stripe'    => 'S',
        );
        return ( isset( $letters[$service] ) ? $letters[$service] : '?' );
    }

    /**
     * Render integrations page.
     */
    public function render_integrations_page() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have the necessary permissions to access this page.', 'giraforms' ) );
        }
        $settings = get_option( $this->option_name, array() );
        foreach ( GiraForms_Encryption::ENCRYPTED_KEYS as $enc_key ) {
            if ( !empty( $settings[$enc_key] ) ) {
                $settings[$enc_key] = GiraForms_Encryption::decrypt( $settings[$enc_key] );
            }
        }
        $site_key = ( isset( $settings['turnstile_site_key'] ) ? $settings['turnstile_site_key'] : '' );
        $secret_key = ( isset( $settings['turnstile_secret_key'] ) ? $settings['turnstile_secret_key'] : '' );
        $turnstile_configured = !empty( $site_key ) && !empty( $secret_key );
        // Check if webhooks are configured
        $webhooks = get_option( 'giraforms_webhooks', array() );
        $webhooks_count = ( is_array( $webhooks ) ? count( $webhooks ) : 0 );
        ?>
		<div class="wrap">
			<h1><?php 
        esc_html_e( 'Integrations', 'giraforms' );
        ?></h1>
			<p><?php 
        esc_html_e( 'Connect Giraforms with external services to extend your forms capabilities.', 'giraforms' );
        ?></p>

			<?php 
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking 'updated' flag for success message display.
        if ( isset( $_GET['updated'] ) && 'true' === $_GET['updated'] ) {
            ?>
				<div class="notice notice-success is-dismissible">
					<p><?php 
            esc_html_e( 'Settings saved.', 'giraforms' );
            ?></p>
				</div>
			<?php 
        }
        ?>

			<div class="giraforms-integrations-section">
				<div class="giraforms-integrations-section-header">
					<span class="dashicons dashicons-shield"></span>
					<h2 class="giraforms-integrations-section-title"><?php 
        esc_html_e( 'Captcha Services', 'giraforms' );
        ?></h2>
				</div>
				<p class="giraforms-integrations-section-description"><?php 
        esc_html_e( 'Configure anti-spam providers used by your forms.', 'giraforms' );
        ?></p>

				<div class="giraforms-integrations-grid">
				<!-- Turnstile Card -->
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon turnstile"><?php 
        echo esc_html( $this->get_service_icon_letter( 'turnstile' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title"><?php 
        esc_html_e( 'Cloudflare Turnstile', 'giraforms' );
        ?></h3>
						</div>
						<?php 
        if ( $turnstile_configured ) {
            ?>
							<span class="card-status configured">● <?php 
            esc_html_e( 'Configured', 'giraforms' );
            ?></span>
						<?php 
        } else {
            ?>
							<span class="card-status not-configured">● <?php 
            esc_html_e( 'Not configured', 'giraforms' );
            ?></span>
						<?php 
        }
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Privacy-friendly CAPTCHA alternative. Verifies visitors without puzzles.', 'giraforms' );
        ?>
					</p>

					<details class="card-form-details">
						<summary>
							<span><?php 
        echo ( $turnstile_configured ? esc_html__( 'Edit configuration', 'giraforms' ) : esc_html__( 'Add API keys', 'giraforms' ) );
        ?></span>
							<span class="dashicons dashicons-arrow-right-alt2 summary-arrow"></span>
						</summary>
						<form method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>">
							<input type="hidden" name="action" value="giraforms_save_integrations" />
							<?php 
        wp_nonce_field( 'giraforms_integrations_nonce', '_giraforms_integrations_nonce' );
        ?>

							<div class="card-fields">
								<label for="turnstile_site_key"><?php 
        esc_html_e( 'Site Key', 'giraforms' );
        ?></label>
								<input
									type="text"
									id="turnstile_site_key"
									name="turnstile_site_key"
									value="<?php 
        echo esc_attr( $site_key );
        ?>"
									class="regular-text"
									placeholder="0x..."
								/>

								<label for="turnstile_secret_key"><?php 
        esc_html_e( 'Secret Key', 'giraforms' );
        ?></label>
								<?php 
        $this->render_secret_key_field( 'turnstile_secret_key', 'turnstile_secret_key', $secret_key );
        ?>

								<p class="description">
									<?php 
        echo wp_kses_post( sprintf( 
            /* translators: %s: Cloudflare dashboard URL */
            __( 'Get your keys from the <a href="%s" target="_blank">Cloudflare Turnstile Dashboard</a>.', 'giraforms' ),
            'https://dash.cloudflare.com/?to=/:account/turnstile'
         ) );
        ?>
								</p>
							</div>

							<?php 
        submit_button(
            __( 'Save Keys', 'giraforms' ),
            'primary',
            'submit',
            true
        );
        ?>
						</form>
					</details>
				</div>

				<!-- Google reCAPTCHA Card -->
				<?php 
        $recaptcha_v2_site_key = ( isset( $settings['recaptcha_v2_site_key'] ) ? $settings['recaptcha_v2_site_key'] : '' );
        $recaptcha_v2_secret_key = ( isset( $settings['recaptcha_v2_secret_key'] ) ? $settings['recaptcha_v2_secret_key'] : '' );
        $recaptcha_v3_site_key = ( isset( $settings['recaptcha_v3_site_key'] ) ? $settings['recaptcha_v3_site_key'] : '' );
        $recaptcha_v3_secret_key = ( isset( $settings['recaptcha_v3_secret_key'] ) ? $settings['recaptcha_v3_secret_key'] : '' );
        $recaptcha_configured = !empty( $recaptcha_v2_site_key ) && !empty( $recaptcha_v2_secret_key ) || !empty( $recaptcha_v3_site_key ) && !empty( $recaptcha_v3_secret_key );
        ?>
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon recaptcha"><?php 
        echo esc_html( $this->get_service_icon_letter( 'recaptcha' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title"><?php 
        esc_html_e( 'Google reCAPTCHA', 'giraforms' );
        ?></h3>
						</div>
						<?php 
        if ( $recaptcha_configured ) {
            ?>
							<span class="card-status configured">● <?php 
            esc_html_e( 'Configured', 'giraforms' );
            ?></span>
						<?php 
        } else {
            ?>
							<span class="card-status not-configured">● <?php 
            esc_html_e( 'Not configured', 'giraforms' );
            ?></span>
						<?php 
        }
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Supports v2 (checkbox) and v3 (invisible). Each version requires its own key pair.', 'giraforms' );
        ?>
					</p>

					<details class="card-form-details">
						<summary>
							<span><?php 
        echo ( $recaptcha_configured ? esc_html__( 'Edit configuration', 'giraforms' ) : esc_html__( 'Add API keys', 'giraforms' ) );
        ?></span>
							<span class="dashicons dashicons-arrow-right-alt2 summary-arrow"></span>
						</summary>
						<form method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>">
							<input type="hidden" name="action" value="giraforms_save_integrations" />
							<?php 
        wp_nonce_field( 'giraforms_integrations_nonce', '_giraforms_integrations_nonce' );
        ?>

							<div class="card-fields">
								<div class="card-fields-subsection">
									<h4 class="card-fields-subsection-title"><?php 
        esc_html_e( 'v2 — Checkbox', 'giraforms' );
        ?></h4>

									<label for="recaptcha_v2_site_key"><?php 
        esc_html_e( 'Site Key', 'giraforms' );
        ?></label>
									<input
										type="text"
										id="recaptcha_v2_site_key"
										name="recaptcha_v2_site_key"
										value="<?php 
        echo esc_attr( $recaptcha_v2_site_key );
        ?>"
										class="regular-text"
									/>

									<label for="recaptcha_v2_secret_key"><?php 
        esc_html_e( 'Secret Key', 'giraforms' );
        ?></label>
									<?php 
        $this->render_secret_key_field( 'recaptcha_v2_secret_key', 'recaptcha_v2_secret_key', $recaptcha_v2_secret_key );
        ?>
								</div>

								<div class="card-fields-subsection">
									<h4 class="card-fields-subsection-title"><?php 
        esc_html_e( 'v3 — Invisible', 'giraforms' );
        ?></h4>

									<label for="recaptcha_v3_site_key"><?php 
        esc_html_e( 'Site Key', 'giraforms' );
        ?></label>
									<input
										type="text"
										id="recaptcha_v3_site_key"
										name="recaptcha_v3_site_key"
										value="<?php 
        echo esc_attr( $recaptcha_v3_site_key );
        ?>"
										class="regular-text"
									/>

									<label for="recaptcha_v3_secret_key"><?php 
        esc_html_e( 'Secret Key', 'giraforms' );
        ?></label>
									<?php 
        $this->render_secret_key_field( 'recaptcha_v3_secret_key', 'recaptcha_v3_secret_key', $recaptcha_v3_secret_key );
        ?>
								</div>

								<p class="description">
									<?php 
        echo wp_kses_post( sprintf( 
            /* translators: %s: Google reCAPTCHA console URL */
            __( 'Get your keys from the <a href="%s" target="_blank">Google reCAPTCHA Console</a>. v2 and v3 require separate key pairs.', 'giraforms' ),
            'https://www.google.com/recaptcha/admin'
         ) );
        ?>
								</p>
							</div>

							<?php 
        submit_button(
            __( 'Save Keys', 'giraforms' ),
            'primary',
            'submit',
            true
        );
        ?>
						</form>
					</details>
				</div>

				<!-- hCaptcha Card -->
				<?php 
        $hcaptcha_site_key = ( isset( $settings['hcaptcha_site_key'] ) ? $settings['hcaptcha_site_key'] : '' );
        $hcaptcha_secret_key = ( isset( $settings['hcaptcha_secret_key'] ) ? $settings['hcaptcha_secret_key'] : '' );
        $hcaptcha_configured = !empty( $hcaptcha_site_key ) && !empty( $hcaptcha_secret_key );
        ?>
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon hcaptcha"><?php 
        echo esc_html( $this->get_service_icon_letter( 'hcaptcha' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title"><?php 
        esc_html_e( 'hCaptcha', 'giraforms' );
        ?></h3>
						</div>
						<?php 
        if ( $hcaptcha_configured ) {
            ?>
							<span class="card-status configured">● <?php 
            esc_html_e( 'Configured', 'giraforms' );
            ?></span>
						<?php 
        } else {
            ?>
							<span class="card-status not-configured">● <?php 
            esc_html_e( 'Not configured', 'giraforms' );
            ?></span>
						<?php 
        }
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Privacy-focused bot protection. Rewards website owners and respects user privacy.', 'giraforms' );
        ?>
					</p>

					<details class="card-form-details">
						<summary>
							<span><?php 
        echo ( $hcaptcha_configured ? esc_html__( 'Edit configuration', 'giraforms' ) : esc_html__( 'Add API keys', 'giraforms' ) );
        ?></span>
							<span class="dashicons dashicons-arrow-right-alt2 summary-arrow"></span>
						</summary>
						<form method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>">
							<input type="hidden" name="action" value="giraforms_save_integrations" />
							<?php 
        wp_nonce_field( 'giraforms_integrations_nonce', '_giraforms_integrations_nonce' );
        ?>

							<div class="card-fields">
								<label for="hcaptcha_site_key"><?php 
        esc_html_e( 'Site Key', 'giraforms' );
        ?></label>
								<input
									type="text"
									id="hcaptcha_site_key"
									name="hcaptcha_site_key"
									value="<?php 
        echo esc_attr( $hcaptcha_site_key );
        ?>"
									class="regular-text"
								/>

								<label for="hcaptcha_secret_key"><?php 
        esc_html_e( 'Secret Key', 'giraforms' );
        ?></label>
								<?php 
        $this->render_secret_key_field( 'hcaptcha_secret_key', 'hcaptcha_secret_key', $hcaptcha_secret_key );
        ?>

								<p class="description">
									<?php 
        echo wp_kses_post( sprintf( 
            /* translators: %s: hCaptcha dashboard URL */
            __( 'Get your keys from the <a href="%s" target="_blank">hCaptcha Dashboard</a>.', 'giraforms' ),
            'https://dashboard.hcaptcha.com/'
         ) );
        ?>
								</p>
							</div>

							<?php 
        submit_button(
            __( 'Save Keys', 'giraforms' ),
            'primary',
            'submit',
            true
        );
        ?>
						</form>
					</details>
				</div>
				</div>
			</div>

			<div class="giraforms-integrations-section">
				<div class="giraforms-integrations-section-header">
					<span class="dashicons dashicons-megaphone"></span>
					<h2 class="giraforms-integrations-section-title"><?php 
        esc_html_e( 'Marketing Services', 'giraforms' );
        ?></h2>
				</div>
				<p class="giraforms-integrations-section-description"><?php 
        esc_html_e( 'Connect your forms with email marketing platforms.', 'giraforms' );
        ?></p>

				<div class="giraforms-integrations-grid">
				<!-- Brevo Card -->
				<?php 
        $brevo_api_key = ( isset( $settings['brevo_api_key'] ) ? $settings['brevo_api_key'] : '' );
        $brevo_configured = !empty( $brevo_api_key );
        $brevo_detected_ip = get_transient( 'giraforms_brevo_detected_ip' );
        ?>
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon brevo"><?php 
        echo esc_html( $this->get_service_icon_letter( 'brevo' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title">
								<?php 
        esc_html_e( 'Brevo', 'giraforms' );
        ?>
								<?php 
        ?>
									<span class="badge-pro">Pro</span>
								<?php 
        ?>
							</h3>
						</div>
						<?php 
        ?>
							<span class="card-status requires-pro">● <?php 
        esc_html_e( 'Pro', 'giraforms' );
        ?></span>
						<?php 
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Add form submitters to a Brevo contact list. Configure per form in block settings.', 'giraforms' );
        ?>
					</p>

					<?php 
        ?>
						<div class="card-action">
							<a href="<?php 
        echo esc_url( giraforms__fs()->get_upgrade_url() );
        ?>" class="button button-primary">
								<?php 
        esc_html_e( 'Upgrade to Pro', 'giraforms' );
        ?>
							</a>
						</div>
					<?php 
        ?>
				</div>

				<!-- Mailchimp Card -->
				<?php 
        $mailchimp_api_key = ( isset( $settings['mailchimp_api_key'] ) ? $settings['mailchimp_api_key'] : '' );
        $mailchimp_configured = !empty( $mailchimp_api_key );
        ?>
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon mailchimp"><?php 
        echo esc_html( $this->get_service_icon_letter( 'mailchimp' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title">
								<?php 
        esc_html_e( 'Mailchimp', 'giraforms' );
        ?>
								<?php 
        ?>
									<span class="badge-pro">Pro</span>
								<?php 
        ?>
							</h3>
						</div>
						<?php 
        ?>
							<span class="card-status requires-pro">● <?php 
        esc_html_e( 'Pro', 'giraforms' );
        ?></span>
						<?php 
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Sync form submissions with your Mailchimp audiences. Configure per form in block settings.', 'giraforms' );
        ?>
					</p>

					<?php 
        ?>
						<div class="card-action">
							<a href="<?php 
        echo esc_url( giraforms__fs()->get_upgrade_url() );
        ?>" class="button button-primary">
								<?php 
        esc_html_e( 'Upgrade to Pro', 'giraforms' );
        ?>
							</a>
						</div>
					<?php 
        ?>
				</div>
				</div>
			</div>

			<div class="giraforms-integrations-section">
				<div class="giraforms-integrations-section-header">
					<span class="dashicons dashicons-money-alt"></span>
					<h2 class="giraforms-integrations-section-title"><?php 
        esc_html_e( 'Payment', 'giraforms' );
        ?></h2>
				</div>
				<p class="giraforms-integrations-section-description"><?php 
        esc_html_e( 'Collect payments directly through your forms.', 'giraforms' );
        ?></p>

				<div class="giraforms-integrations-grid">
				<!-- Stripe Card -->
				<?php 
        $stripe_mode = ( isset( $settings['stripe_mode'] ) ? $settings['stripe_mode'] : 'test' );
        $stripe_test_pub_key = ( isset( $settings['stripe_test_publishable_key'] ) ? $settings['stripe_test_publishable_key'] : '' );
        $stripe_test_sec_key = ( isset( $settings['stripe_test_secret_key'] ) ? $settings['stripe_test_secret_key'] : '' );
        $stripe_live_pub_key = ( isset( $settings['stripe_live_publishable_key'] ) ? $settings['stripe_live_publishable_key'] : '' );
        $stripe_live_sec_key = ( isset( $settings['stripe_live_secret_key'] ) ? $settings['stripe_live_secret_key'] : '' );
        $stripe_test_webhook_sec = ( isset( $settings['stripe_test_webhook_secret'] ) ? $settings['stripe_test_webhook_secret'] : '' );
        $stripe_live_webhook_sec = ( isset( $settings['stripe_live_webhook_secret'] ) ? $settings['stripe_live_webhook_secret'] : '' );
        $stripe_legacy_pub = ( isset( $settings['stripe_publishable_key'] ) ? $settings['stripe_publishable_key'] : '' );
        $stripe_legacy_sec = ( isset( $settings['stripe_secret_key'] ) ? $settings['stripe_secret_key'] : '' );
        $stripe_configured = !empty( $stripe_test_pub_key ) && !empty( $stripe_test_sec_key ) || !empty( $stripe_live_pub_key ) && !empty( $stripe_live_sec_key ) || !empty( $stripe_legacy_pub ) && !empty( $stripe_legacy_sec );
        $stripe_key_warnings = array();
        if ( !empty( $stripe_test_pub_key ) && strpos( $stripe_test_pub_key, 'pk_test_' ) !== 0 ) {
            $stripe_key_warnings[] = __( 'Test publishable key does not start with pk_test_', 'giraforms' );
        }
        if ( !empty( $stripe_test_sec_key ) && strpos( $stripe_test_sec_key, 'sk_test_' ) !== 0 && strpos( $stripe_test_sec_key, 'rk_test_' ) !== 0 ) {
            $stripe_key_warnings[] = __( 'Test secret key does not start with sk_test_', 'giraforms' );
        }
        if ( !empty( $stripe_live_pub_key ) && strpos( $stripe_live_pub_key, 'pk_live_' ) !== 0 ) {
            $stripe_key_warnings[] = __( 'Live publishable key does not start with pk_live_', 'giraforms' );
        }
        if ( !empty( $stripe_live_sec_key ) && strpos( $stripe_live_sec_key, 'sk_live_' ) !== 0 && strpos( $stripe_live_sec_key, 'rk_live_' ) !== 0 ) {
            $stripe_key_warnings[] = __( 'Live secret key does not start with sk_live_', 'giraforms' );
        }
        $webhook_url = rest_url( 'giraforms/v1/stripe/webhook' );
        ?>
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-icon stripe"><?php 
        echo esc_html( $this->get_service_icon_letter( 'stripe' ) );
        ?></div>
						<div class="card-header-info">
							<h3 class="card-title">
								<?php 
        esc_html_e( 'Stripe', 'giraforms' );
        ?>
								<?php 
        ?>
									<span class="badge-pro">Pro</span>
								<?php 
        ?>
							</h3>
						</div>
						<?php 
        ?>
							<span class="card-status requires-pro">● <?php 
        esc_html_e( 'Pro', 'giraforms' );
        ?></span>
						<?php 
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Accept payments in your forms. Supports fixed amounts, booking prices, and dynamic field values.', 'giraforms' );
        ?>
					</p>

					<?php 
        ?>
						<div class="card-action">
							<a href="<?php 
        echo esc_url( giraforms__fs()->get_upgrade_url() );
        ?>" class="button button-primary">
								<?php 
        esc_html_e( 'Upgrade to Pro', 'giraforms' );
        ?>
							</a>
						</div>
					<?php 
        ?>
				</div>
				</div>
			</div>

			<div class="giraforms-integrations-section">
				<div class="giraforms-integrations-section-header">
					<span class="dashicons dashicons-randomize"></span>
					<h2 class="giraforms-integrations-section-title"><?php 
        esc_html_e( 'Webhooks', 'giraforms' );
        ?></h2>
				</div>
				<p class="giraforms-integrations-section-description"><?php 
        esc_html_e( 'Send submissions to external automation tools and APIs.', 'giraforms' );
        ?></p>

				<div class="giraforms-integrations-grid">
				<!-- Webhooks Card -->
				<div class="giraforms-integration-card">
					<div class="card-header">
						<div class="card-header-info">
							<h3 class="card-title">
								<?php 
        esc_html_e( 'Webhooks', 'giraforms' );
        ?>
								<?php 
        ?>
									<span class="badge-pro">Pro</span>
								<?php 
        ?>
							</h3>
						</div>
						<?php 
        ?>
							<span class="card-status requires-pro">● <?php 
        esc_html_e( 'Pro', 'giraforms' );
        ?></span>
						<?php 
        ?>
					</div>
					<p class="card-description">
						<?php 
        esc_html_e( 'Send submissions to external services via HTTP POST. Works with Zapier, Make, n8n, or any URL.', 'giraforms' );
        ?>
					</p>

					<?php 
        ?>
						<div class="card-action" style="margin-top: 0; padding-top: 0; border-top: none;">
							<a href="<?php 
        echo esc_url( giraforms__fs()->get_upgrade_url() );
        ?>" class="button button-primary">
								<?php 
        esc_html_e( 'Upgrade to Pro', 'giraforms' );
        ?>
							</a>
						</div>
					<?php 
        ?>
				</div>
				</div>
			</div>
		</div>
		<?php 
    }

}
