<?php

namespace WeDevs\Wpuf\Pro\Fields;

/**
 * Social Media Field Base Class
 *
 * @since 4.2.0
 */
abstract class Field_Social extends Pro_Field_Contract {

    protected $icon_svg;
    protected $base_url;
    protected $username_pattern;
    protected $url_pattern;
    protected $max_username_length;
    protected $example_username;

    /**
     * Render the social media field
     *
     * @param array $field_settings
     * @param int $form_id
     * @param string $type
     * @param int $post_id
     *
     * @return void
     */
    abstract public function render( $field_settings, $form_id, $type = 'post', $post_id = null );

    /**
     * Helper method to get allowed SVG attributes for wp_kses
     *
     * @since 4.1.7
     *
     * @return array
     */
    protected function get_allowed_svg_attributes() {
        return [
            'svg' => [
                'class' => [],
                'width' => [],
                'height' => [],
                'viewBox' => [],
                'viewbox' => [],
                'fill' => [],
                'xmlns' => [],
                'aria-label' => [],
                'role' => [],
                'style' => [],
            ],
            'path' => [
                'd' => [],
                'stroke' => [],
                'stroke-width' => [],
                'stroke-linecap' => [],
                'stroke-linejoin' => [],
                'fill' => [],
                'style' => [],
            ],
        ];
    }

    /**
     * Get options settings for the form builder
     *
     * @return array
     */
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings( false, array('dynamic','width') );

        // Don't include basic_settings to avoid duplicates - we'll define our own fields

        $settings = [
            [
                'name'      => 'show_icon',
                'title'     => __( 'Icon show', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'yes' => __( 'Yes', 'wpuf-pro' ),
                    'no'  => __( 'No', 'wpuf-pro' ),
                ],
                'default'   => 'yes',
                'section'   => 'basic',
                'priority'  => 15,
                'help_text' => __( 'Show the social platform icon next to the field', 'wpuf-pro' ),
            ],
            [
                'name'      => 'readonly',
                'title'     => __( 'Read Only', 'wpuf-pro' ),
                'type'      => 'checkbox',
                'is_single_opt' => true,
                'options'   => [
                    'yes' => __( 'Yes', 'wpuf-pro' ),
                ],
                'section'   => 'basic',
                'priority'  => 17,
                'help_text' => __( 'Make this field read-only', 'wpuf-pro' ),
            ],
            [
                'name'      => 'open_in_new_window',
                'title'     => __( 'Link Target', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'no'  => __( 'Same Window', 'wpuf-pro' ),
                    'yes' => __( 'New Window', 'wpuf-pro' ),
                ],
                'default'   => 'yes',
                'section'   => 'advanced',
                'priority'  => 20,
                'help_text' => __( 'Choose whether to open social media links in the same window or a new window', 'wpuf-pro' ),
            ],
            [
                'name'      => 'width',
                'title'     => __( 'Field Size', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'small'  => __( 'Small', 'wpuf-pro' ),
                    'medium' => __( 'Medium', 'wpuf-pro' ),
                    'large'  => __( 'Large', 'wpuf-pro' ),
                ],
                'section'   => 'advanced',
                'priority'  => 21,
                'default'   => 'medium',
                'inline'    => true,
                'help_text' => __( 'Select the size of the input field', 'wpuf-pro' ),
            ],
            [
                'name'      => 'nofollow',
                'title'     => __( 'SEO Follow', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'yes' => __( 'No-Follow', 'wpuf-pro' ),
                    'no'  => __( 'Follow', 'wpuf-pro' ),
                ],
                'section'   => 'advanced',
                'priority'  => 26,
                'default'   => 'yes',
                'inline'    => true,
                'help_text' => __( 'Add rel="nofollow" attribute to links (recommended for SEO)', 'wpuf-pro' ),
            ],
        ];

        return array_merge( $default_options, $settings );
    }

    /**
     * Prepare data for database storage
     *
     * @param array $field
     *
     * @return string
     */
    public function prepare_entry( $field ) {
        $value = ! empty( $_POST[ $field['name'] ] ) ? trim( $_POST[ $field['name'] ] ) : '';

        if ( ! empty( $value ) ) {
            // For Twitter fields with @ prefix display, ensure @ is not saved
            if ( isset( $field['input_type'] ) && $field['input_type'] === 'twitter_url' ) {
                // Remove any leading @ symbol to keep database clean
                $value = ltrim( $value, '@' );
            }
            // For Facebook fields, clean up any prefixes
            elseif ( isset( $field['input_type'] ) && $field['input_type'] === 'facebook_url' ) {
                // Remove any leading facebook.com/ or fb.com/ prefixes to keep database clean
                $value = preg_replace('/^(?:https?:\/\/)?(?:www\.)?(?:facebook\.com\/|fb\.com\/)/i', '', $value);
            }
            // For LinkedIn fields, clean up any prefixes
            elseif ( isset( $field['input_type'] ) && $field['input_type'] === 'linkedin_url' ) {
                // Remove any leading linkedin.com/ prefixes to keep database clean
                $value = preg_replace('/^(?:https?:\/\/)?(?:www\.)?(?:linkedin\.com\/(?:in|company)\/)*/i', '', $value);
            }
            // For Instagram fields, clean up any prefixes
            elseif ( isset( $field['input_type'] ) && $field['input_type'] === 'instagram_url' ) {
                // Remove any leading instagram.com/ or instagr.am/ prefixes to keep database clean
                $value = preg_replace('/^(?:https?:\/\/)?(?:www\.)?(?:instagram\.com\/|instagr\.am\/)/i', '', $value);
            }

            $value = $this->format_url( $value );
        }

        return strip_shortcodes( sanitize_text_field( $value ) );
    }

    /**
     * Format input to standardized URL
     *
     * @param string $input
     *
     * @return string
     */
    protected function format_url( $input ) {
        $input = trim( $input );

        // If it's already a full URL, validate and return
        if ( preg_match( $this->url_pattern, $input ) ) {
            return $input;
        }

        // If it's a username (with or without @), convert to URL
        $username = ltrim( $input, '@' );
        if ( preg_match( '/^[a-zA-Z0-9_]{1,' . $this->max_username_length . '}$/', $username ) ) {
            return $this->base_url . $username;
        }

        // Return as-is if it doesn't match any pattern
        return $input;
    }

    /**
     * Validate social media field data
     *
     * @param array $field_settings
     * @param string $value
     *
     * @return bool
     */
    protected function validate( $field_settings, $value ) {
        if ( empty( $value ) ) {
            return true; // Empty values are handled by required field validation
        }

        $formatted_url = $this->format_url( $value );

        return filter_var( $formatted_url, FILTER_VALIDATE_URL ) !== false;
    }
}
