<?php
/**
 * Blog Over: Author Bio Widget
 *
 * Displays an author bio card with avatar, name, designation,
 * description, website link, and social media icons.
 *
 * @package Blog_Over
 * @since 1.4.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Blog_Over_Author_Widget
 *
 * Custom widget for displaying author biographical information
 * in any widget area (sidebar, footer, etc.).
 */
class Blog_Over_Author_Widget extends WP_Widget
{

    /**
     * Supported social networks with Font Awesome icon classes.
     *
     * @var array
     */
    private $social_networks = array();

    /**
     * Constructor — register widget with WordPress.
     */
    public function __construct()
    {
        $this->social_networks = array(
            'facebook' => array(
                'label' => __('Facebook URL', 'blog-over'),
                'icon' => 'fab fa-facebook-f',
            ),
            'twitter' => array(
                'label' => __('X (Twitter) URL', 'blog-over'),
                'icon' => 'fab fa-x-twitter',
            ),
            'instagram' => array(
                'label' => __('Instagram URL', 'blog-over'),
                'icon' => 'fab fa-instagram',
            ),
            'linkedin' => array(
                'label' => __('LinkedIn URL', 'blog-over'),
                'icon' => 'fab fa-linkedin-in',
            ),
            'youtube' => array(
                'label' => __('YouTube URL', 'blog-over'),
                'icon' => 'fab fa-youtube',
            ),
        );

        parent::__construct(
            'blog_over_author_widget',
            __('Blog Over: Author Bio', 'blog-over'),
            array(
                'description' => __('Display an author bio card with avatar, social links, and more.', 'blog-over'),
                'classname' => 'widget_blog_over_author',
                'customize_selective_refresh' => true,
            )
        );
    }

    /**
     * Front-end output.
     *
     * @param array $args     Widget area arguments.
     * @param array $instance Widget settings.
     */
    public function widget($args, $instance)
    {
        $defaults = array(
            'title' => __('About Author', 'blog-over'),
            'author_name' => __('John Doe', 'blog-over'),
            'avatar_url' => 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=250&d=mm&r=g',
            'bio' => __('Hello! I am a passionate writer and editor. I love sharing my thoughts on technology, lifestyle, and global news.', 'blog-over'),
            'designation' => __('Editor in Chief', 'blog-over'),
            'website_url' => '#',
            'avatar_shape' => 'circle',
            'layout_style' => 'centered',
            'show_social' => true,
        );
        $instance = wp_parse_args((array) $instance, $defaults);

        $title = apply_filters('widget_title', $instance['title'], $instance, $this->id_base);
        $author_name = $instance['author_name'];
        $avatar_url = $instance['avatar_url'];
        $bio = $instance['bio'];
        $designation = $instance['designation'];
        $website_url = $instance['website_url'];
        $avatar_shape = $instance['avatar_shape'];
        $layout_style = $instance['layout_style'];
        $show_social = (bool) $instance['show_social'];

        // Bail if no content at all.
        if (empty($author_name) && empty($bio) && empty($avatar_url)) {
            return;
        }

        echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

        if ($title) {
            echo $args['before_title'] . esc_html($title) . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        $layout_class = 'blog-over-author-widget-layout-' . sanitize_html_class($layout_style);
        $shape_class = 'blog-over-author-widget-avatar-' . sanitize_html_class($avatar_shape);
        ?>
        <div class="blog-over-author-widget <?php echo esc_attr($layout_class . ' ' . $shape_class); ?>">

            <?php if ($avatar_url): ?>
                <div class="blog-over-author-widget-avatar">
                    <img src="<?php echo esc_url($avatar_url); ?>" alt="<?php echo esc_attr($author_name); ?>" loading="lazy" />
                </div>
            <?php endif; ?>

            <div class="blog-over-author-widget-content">
                <?php if ($author_name): ?>
                    <h3 class="blog-over-author-widget-name">
                        <?php echo esc_html($author_name); ?>
                    </h3>
                <?php endif; ?>

                <?php if ($designation): ?>
                    <span class="blog-over-author-widget-designation">
                        <?php echo esc_html($designation); ?>
                    </span>
                <?php endif; ?>

                <?php if ($bio): ?>
                    <div class="blog-over-author-widget-bio">
                        <?php echo wp_kses_post(wpautop($bio)); ?>
                    </div>
                <?php endif; ?>

                <?php if ($website_url): ?>
                    <a href="<?php echo esc_url($website_url); ?>" class="blog-over-author-widget-website" target="_blank"
                        rel="noopener noreferrer">
                        <i class="fas fa-globe" aria-hidden="true"></i>
                        <?php esc_html_e('Visit Website', 'blog-over'); ?>
                    </a>
                <?php endif; ?>

                <?php if ($show_social): ?>
                    <?php $this->render_social_links($instance); ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
        echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    /**
     * Render social media icon links.
     *
     * @param array $instance Widget settings.
     */
    private function render_social_links($instance)
    {
        $has_links = false;
        foreach ($this->social_networks as $key => $network) {
            if (!empty($instance['social_' . $key])) {
                $has_links = true;
                break;
            }
        }

        if (!$has_links) {
            return;
        }
        ?>
        <div class="blog-over-author-widget-social">
            <?php foreach ($this->social_networks as $key => $network):
                $url = !empty($instance['social_' . $key]) ? $instance['social_' . $key] : '';
                if (empty($url)) {
                    continue;
                }
                ?>
                <a href="<?php echo esc_url($url); ?>"
                    class="blog-over-author-social-link blog-over-social-<?php echo esc_attr($key); ?>" target="_blank"
                    rel="noopener noreferrer" aria-label="<?php echo esc_attr($network['label']); ?>">
                    <i class="<?php echo esc_attr($network['icon']); ?>" aria-hidden="true"></i>
                </a>
            <?php endforeach; ?>
        </div>
        <?php
    }

    /**
     * Admin form for widget settings.
     *
     * @param array $instance Current settings.
     * @return void
     */
    public function form($instance)
    {
        // Defaults.
        $defaults = array(
            'title' => __('About Author', 'blog-over'),
            'author_name' => __('John Doe', 'blog-over'),
            'avatar_url' => 'https://secure.gravatar.com/avatar/00000000000000000000000000000000?s=250&d=mm&r=g',
            'bio' => __('Hello! I am a passionate writer and editor. I love sharing my thoughts on technology, lifestyle, and global news.', 'blog-over'),
            'designation' => __('Editor in Chief', 'blog-over'),
            'website_url' => '#',
            'avatar_shape' => 'circle',
            'layout_style' => 'centered',
            'show_social' => true,
        );
        foreach ($this->social_networks as $key => $network) {
            $defaults['social_' . $key] = '';
        }

        $instance = wp_parse_args((array) $instance, $defaults);
        ?>
        <div class="blog-over-author-widget-admin">

            <!-- Title -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
                    <?php esc_html_e('Title:', 'blog-over'); ?>
                </label>
                <input type="text" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('title')); ?>"
                    value="<?php echo esc_attr($instance['title']); ?>" class="widefat" />
            </p>

            <!-- Author Name -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('author_name')); ?>">
                    <?php esc_html_e('Author Name:', 'blog-over'); ?>
                </label>
                <input type="text" id="<?php echo esc_attr($this->get_field_id('author_name')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('author_name')); ?>"
                    value="<?php echo esc_attr($instance['author_name']); ?>" class="widefat" />
            </p>

            <!-- Designation -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('designation')); ?>">
                    <?php esc_html_e('Designation / Role:', 'blog-over'); ?>
                </label>
                <input type="text" id="<?php echo esc_attr($this->get_field_id('designation')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('designation')); ?>"
                    value="<?php echo esc_attr($instance['designation']); ?>" class="widefat"
                    placeholder="<?php esc_attr_e('e.g. Travel Blogger, Web Developer', 'blog-over'); ?>" />
            </p>

            <!-- Avatar Image -->
            <p>
                <label>
                    <?php esc_html_e('Avatar Image:', 'blog-over'); ?>
                </label>
            </p>
            <div class="blog-over-avatar-upload-wrap">
                <div class="blog-over-avatar-preview" id="<?php echo esc_attr($this->get_field_id('avatar_preview')); ?>"
                    style="<?php echo empty($instance['avatar_url']) ? 'display:none;' : ''; ?>">
                    <img src="<?php echo esc_url($instance['avatar_url']); ?>"
                        alt="<?php echo esc_attr(!empty($instance['author_name']) ? $instance['author_name'] : __('Author avatar', 'blog-over')); ?>"
                        style="max-width:100%;height:auto;border-radius:8px;" />
                </div>
                <input type="hidden" id="<?php echo esc_attr($this->get_field_id('avatar_url')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('avatar_url')); ?>"
                    value="<?php echo esc_url($instance['avatar_url']); ?>" class="blog-over-avatar-url" />
                <p>
                    <button type="button" class="button blog-over-upload-avatar"
                        data-target="#<?php echo esc_attr($this->get_field_id('avatar_url')); ?>"
                        data-preview="#<?php echo esc_attr($this->get_field_id('avatar_preview')); ?>">
                        <?php esc_html_e('Upload Image', 'blog-over'); ?>
                    </button>
                    <button type="button" class="button blog-over-remove-avatar"
                        data-target="#<?php echo esc_attr($this->get_field_id('avatar_url')); ?>"
                        data-preview="#<?php echo esc_attr($this->get_field_id('avatar_preview')); ?>"
                        style="<?php echo empty($instance['avatar_url']) ? 'display:none;' : ''; ?>">
                        <?php esc_html_e('Remove', 'blog-over'); ?>
                    </button>
                </p>
            </div>

            <!-- Bio / Description -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('bio')); ?>">
                    <?php esc_html_e('Bio / Description:', 'blog-over'); ?>
                </label>
                <textarea id="<?php echo esc_attr($this->get_field_id('bio')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('bio')); ?>" class="widefat"
                    rows="4"><?php echo esc_textarea($instance['bio']); ?></textarea>
            </p>

            <!-- Website URL -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('website_url')); ?>">
                    <?php esc_html_e('Website URL:', 'blog-over'); ?>
                </label>
                <input type="url" id="<?php echo esc_attr($this->get_field_id('website_url')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('website_url')); ?>"
                    value="<?php echo esc_url($instance['website_url']); ?>" class="widefat" placeholder="https://" />
            </p>

            <hr style="margin: 15px 0; border: none; border-top: 1px solid #ddd;" />

            <!-- Layout Style -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('layout_style')); ?>">
                    <?php esc_html_e('Layout Style:', 'blog-over'); ?>
                </label>
                <select id="<?php echo esc_attr($this->get_field_id('layout_style')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('layout_style')); ?>" class="widefat">
                    <option value="centered" <?php selected($instance['layout_style'], 'centered'); ?>>
                        <?php esc_html_e('Centered', 'blog-over'); ?>
                    </option>
                    <option value="side" <?php selected($instance['layout_style'], 'side'); ?>>
                        <?php esc_html_e('Side by Side', 'blog-over'); ?>
                    </option>
                </select>
            </p>

            <!-- Avatar Shape -->
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('avatar_shape')); ?>">
                    <?php esc_html_e('Avatar Shape:', 'blog-over'); ?>
                </label>
                <select id="<?php echo esc_attr($this->get_field_id('avatar_shape')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('avatar_shape')); ?>" class="widefat">
                    <option value="circle" <?php selected($instance['avatar_shape'], 'circle'); ?>>
                        <?php esc_html_e('Circle', 'blog-over'); ?>
                    </option>
                    <option value="square" <?php selected($instance['avatar_shape'], 'square'); ?>>
                        <?php esc_html_e('Square (Rounded)', 'blog-over'); ?>
                    </option>
                </select>
            </p>

            <!-- Show Social Icons -->
            <p>
                <input type="checkbox" id="<?php echo esc_attr($this->get_field_id('show_social')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('show_social')); ?>" <?php checked($instance['show_social']); ?> />
                <label for="<?php echo esc_attr($this->get_field_id('show_social')); ?>">
                    <?php esc_html_e('Show Social Media Icons', 'blog-over'); ?>
                </label>
            </p>

            <hr style="margin: 15px 0; border: none; border-top: 1px solid #ddd;" />

            <!-- Social Links -->
            <p><strong>
                    <?php esc_html_e('Social Media Links', 'blog-over'); ?>
                </strong></p>
            <?php foreach ($this->social_networks as $key => $network): ?>
                <p>
                    <label for="<?php echo esc_attr($this->get_field_id('social_' . $key)); ?>">
                        <?php echo esc_html($network['label']); ?>
                    </label>
                    <input type="url" id="<?php echo esc_attr($this->get_field_id('social_' . $key)); ?>"
                        name="<?php echo esc_attr($this->get_field_name('social_' . $key)); ?>"
                        value="<?php echo esc_url($instance['social_' . $key]); ?>" class="widefat" placeholder="https://" />
                </p>
            <?php endforeach; ?>

        </div>
        <?php
    }

    /**
     * Sanitize and save widget settings.
     *
     * @param array $new_instance New values.
     * @param array $old_instance Previous values.
     * @return array Sanitized values.
     */
    public function update($new_instance, $old_instance)
    {
        $instance = $old_instance;

        $instance['title'] = sanitize_text_field($new_instance['title']);
        $instance['author_name'] = sanitize_text_field($new_instance['author_name']);
        $instance['avatar_url'] = esc_url_raw($new_instance['avatar_url']);
        $instance['bio'] = wp_kses_post($new_instance['bio']);
        $instance['designation'] = sanitize_text_field($new_instance['designation']);
        $instance['website_url'] = esc_url_raw($new_instance['website_url']);
        $instance['avatar_shape'] = in_array($new_instance['avatar_shape'], array('circle', 'square'), true)
            ? $new_instance['avatar_shape']
            : 'circle';
        $instance['layout_style'] = in_array($new_instance['layout_style'], array('centered', 'side'), true)
            ? $new_instance['layout_style']
            : 'centered';
        $instance['show_social'] = !empty($new_instance['show_social']);

        // Social links.
        foreach ($this->social_networks as $key => $network) {
            $instance['social_' . $key] = esc_url_raw($new_instance['social_' . $key]);
        }

        return $instance;
    }
}

/**
 * Enqueue media uploader script for the Author Bio widget admin form.
 *
 * @param string $hook_suffix Admin page hook suffix.
 */
function blog_over_author_widget_admin_scripts($hook_suffix)
{
    if ('widgets.php' !== $hook_suffix && 'customize.php' !== $hook_suffix) {
        return;
    }

    wp_enqueue_media();
    wp_enqueue_script(
        'blog-over-author-widget-admin',
        BLOG_OVER_URI . '/assets/js/author-widget-admin.js',
        array('jquery', 'media-upload', 'media-views'),
        BLOG_OVER_VERSION,
        true
    );
}
add_action('admin_enqueue_scripts', 'blog_over_author_widget_admin_scripts');
