<?php

/**
 * LinkCentral Shortcode Class
 *
 * This class handles the functionality for the LinkCentral shortcode,
 * allowing users to easily insert LinkCentral links into their content.
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
class LinkCentral_Shortcode {
    /**
     * The URL prefix for LinkCentral links.
     */
    private $url_prefix;

    /**
     * Constructor.
     */
    public function __construct( $url_prefix ) {
        $this->url_prefix = $url_prefix;
    }

    /**
     * Initialize the shortcode.
     */
    public function init() {
        add_shortcode( 'linkcentral', array($this, 'render_shortcode') );
    }

    /**
     * Render the LinkCentral shortcode.
     *
     * @param array  $atts    Shortcode attributes.
     * @param string $content The content between the shortcode tags.
     * @return string The rendered shortcode output.
     */
    public function render_shortcode( $atts, $content = '' ) {
        $atts = shortcode_atts( array(
            'id'         => 0,
            'newtab'     => 'false',
            'parameters' => '',
        ), $atts, 'linkcentral' );
        $link_id = intval( $atts['id'] );
        if ( !$link_id ) {
            return $content;
        }
        $link = get_post( $link_id );
        if ( !$link || $link->post_type !== 'linkcentral_link' || $link->post_status !== 'publish' ) {
            return $content;
        }
        $url = linkcentral_get_link_url( $link_id, $link->post_name );
        $target = ( $atts['newtab'] === 'true' ? ' target="_blank"' : '' );
        // Use the common link attributes helper
        $link_attributes = new LinkCentral_Link_Attributes();
        $rel_attributes = $link_attributes->get_rel_attributes_from_id( $link_id );
        $css_classes = $link_attributes->get_css_classes_from_id( $link_id );
        $html_attributes = $link_attributes->build_html_attributes( $rel_attributes, $css_classes, $target );
        return '<a href="' . esc_url( $url ) . '"' . $html_attributes . '>' . $content . '</a>';
    }

}
