<?php
/**
 * Shortcode functionality
 *
 * @package CustomCodeManager
 */

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

/**
 * SCC_Shortcode class
 */
class SCC_Shortcode {

    /**
     * Instance of this class
     *
     * @var SCC_Shortcode
     */
    private static $instance = null;

    /**
     * Get instance
     *
     * @return SCC_Shortcode
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        add_action( 'init', array( $this, 'register_shortcodes' ) );
    }

    /**
     * Register shortcodes
     */
    public function register_shortcodes() {
        add_shortcode( 'simple_custom_code', array( $this, 'custom_code_shortcode' ) );
        add_shortcode( 'scc_code', array( $this, 'custom_code_shortcode' ) ); // Alternative shortcode name
    }

    /**
     * Custom code shortcode handler
     *
     * @param array $atts Shortcode attributes.
     * @param string $content Shortcode content.
     * @return string
     */
    public function custom_code_shortcode( $atts, $content = '' ) {
        $atts = shortcode_atts( array(
            'id' => '',
            'title' => '', // Alternative way to identify code by title
        ), $atts, 'custom_code' );

        // Get post ID
        $post_id = 0;
        
        if ( ! empty( $atts['id'] ) ) {
            $post_id = (int) $atts['id'];
        } elseif ( ! empty( $atts['title'] ) ) {
            $post_id = $this->get_post_id_by_title( sanitize_text_field( $atts['title'] ) );
        }

        if ( ! $post_id ) {
            return '<!-- Simple Custom Code: Invalid code ID or title -->';
        }

        $frontend = SCC_Frontend::get_instance();
        return $frontend->get_code_for_shortcode( $post_id );
    }

    /**
     * Get post ID by title
     *
     * @param string $title Post title.
     * @return int
     */
    private function get_post_id_by_title( $title ) {
        $posts = get_posts( array(
            'post_type' => 'simple-custom-code',
            'title' => $title,
            'post_status' => 'publish',
            'numberposts' => 1,
            'fields' => 'ids'
        ) );

        return ! empty( $posts ) ? $posts[0] : 0;
    }
}