<?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'     => '',
            '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 );
        // Use the common link attributes helper
        $link_attributes = new LinkCentral_Link_Attributes();
        // Determine target: per-insertion override → per-link meta + global
        $newtab_attr = $atts['newtab'];
        if ( $newtab_attr === 'yes' || $newtab_attr === 'true' ) {
            $target = '_blank';
        } elseif ( $newtab_attr === 'no' || $newtab_attr === 'false' ) {
            $target = '';
        } else {
            $target = ( $link_attributes->get_new_tab_from_id( $link_id ) ? '_blank' : '' );
        }
        $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 . '>' . wp_kses_post( $content ) . '</a>';
    }

}
