<?php

/**
 * LinkCentral Post Type Class
 *
 * This class handles the registration and management of the custom post type for LinkCentral links.
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
// Include the countries file
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/countries.php';
// Include the Link Manager
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/link-manager.php';
class LinkCentral_Post_Type {
    /**
     * Nonce action for form submission
     * @var string
     */
    private $nonce_action = 'linkcentral_save_link_data';

    /**
     * Nonce name for form submission
     * @var string
     */
    private $nonce_name = 'linkcentral_link_nonce';

    /**
     * Link Manager instance
     * @var LinkCentral_Link_Manager
     */
    private $link_manager;

    /**
     * Initialize the class by hooking methods to WordPress actions
     */
    public function init() {
        $this->link_manager = new LinkCentral_Link_Manager();
        add_action( 'init', array($this, 'register_post_type') );
        add_action( 'init', array($this, 'register_taxonomy') );
        add_filter( 'manage_edit-linkcentral_category_columns', array($this, 'filter_linkcentral_category_columns') );
        add_action( 'add_meta_boxes', array($this, 'add_meta_boxes') );
        add_action( 'add_meta_boxes', array($this, 'add_how_to_use_meta_box') );
        add_action( 'add_meta_boxes', array($this, 'remove_slug_meta_box'), 11 );
        add_filter(
            'wp_insert_post_data',
            array($this, 'validate_post_data'),
            10,
            2
        );
        add_action(
            'save_post',
            array($this, 'save_meta_boxes'),
            10,
            2
        );
        add_action( 'before_delete_post', array($this->link_manager, 'cleanup_link_on_delete') );
        add_action( 'wp_trash_post', array($this->link_manager, 'cleanup_link_on_trash') );
        add_action( 'post_updated_messages', array($this, 'custom_post_updated_messages') );
        add_action( 'in_admin_header', array($this, 'add_admin_header') );
        add_filter(
            'redirect_post_location',
            array($this, 'redirect_after_trash'),
            10,
            2
        );
        add_action( 'wp_ajax_linkcentral_check_slug', array($this, 'ajax_check_slug') );
        add_filter(
            'wp_statuses_list',
            array($this, 'remove_post_statuses'),
            10,
            2
        );
        add_filter(
            'wp_insert_post_data',
            array($this, 'filter_post_data'),
            10,
            3
        );
        // Add the enqueue action
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_scripts') );
    }

    /**
     * Register the custom post type for LinkCentral links
     */
    public function register_post_type() {
        $labels = array(
            'name'               => _x( 'LinkCentral Links', 'post type general name', 'linkcentral' ),
            'singular_name'      => _x( 'LinkCentral Link', 'post type singular name', 'linkcentral' ),
            'menu_name'          => _x( 'LinkCentral Links', 'admin menu', 'linkcentral' ),
            'name_admin_bar'     => _x( 'LinkCentral Link', 'add new on admin bar', 'linkcentral' ),
            'add_new'            => _x( 'Add New', 'link', 'linkcentral' ),
            'add_new_item'       => __( 'Add a New Link', 'linkcentral' ),
            'new_item'           => __( 'New Link', 'linkcentral' ),
            'edit_item'          => __( 'Edit Link', 'linkcentral' ),
            'view_item'          => __( 'View Link', 'linkcentral' ),
            'all_items'          => __( 'All Links', 'linkcentral' ),
            'search_items'       => __( 'Search Links', 'linkcentral' ),
            'parent_item_colon'  => __( 'Parent Links:', 'linkcentral' ),
            'not_found'          => __( 'No links found.', 'linkcentral' ),
            'not_found_in_trash' => __( 'No links found in Trash.', 'linkcentral' ),
        );
        $args = array(
            'labels'                => $labels,
            'public'                => false,
            'publicly_queryable'    => false,
            'show_ui'               => true,
            'show_in_menu'          => false,
            'query_var'             => true,
            'rewrite'               => false,
            'capability_type'       => 'post',
            'map_meta_cap'          => false,
            'capabilities'          => array(
                'read_post'              => 'linkcentral_view_links',
                'read_private_posts'     => 'linkcentral_view_links',
                'edit_post'              => 'linkcentral_create_edit_links',
                'edit_posts'             => 'linkcentral_create_edit_links',
                'edit_others_posts'      => 'linkcentral_create_edit_links',
                'edit_private_posts'     => 'linkcentral_create_edit_links',
                'edit_published_posts'   => 'linkcentral_create_edit_links',
                'delete_post'            => 'linkcentral_create_edit_links',
                'delete_posts'           => 'linkcentral_create_edit_links',
                'delete_others_posts'    => 'linkcentral_create_edit_links',
                'delete_private_posts'   => 'linkcentral_create_edit_links',
                'delete_published_posts' => 'linkcentral_create_edit_links',
                'publish_posts'          => 'linkcentral_create_edit_links',
                'create_posts'           => 'linkcentral_create_edit_links',
            ),
            'has_archive'           => false,
            'hierarchical'          => false,
            'menu_position'         => null,
            'supports'              => array('title', 'slug'),
            'show_in_rest'          => true,
            'exclude_from_search'   => true,
            'rest_base'             => 'linkcentral_link',
            'rest_controller_class' => 'WP_REST_Posts_Controller',
        );
        register_post_type( 'linkcentral_link', $args );
    }

    /**
     * Register custom taxonomy for link categories
     */
    public function register_taxonomy() {
        $labels = array(
            'name'              => _x( 'Link Categories', 'taxonomy general name', 'linkcentral' ),
            'singular_name'     => _x( 'Link Category', 'taxonomy singular name', 'linkcentral' ),
            'search_items'      => __( 'Search Link Categories', 'linkcentral' ),
            'all_items'         => __( 'All Link Categories', 'linkcentral' ),
            'parent_item'       => __( 'Parent Link Category', 'linkcentral' ),
            'parent_item_colon' => __( 'Parent Link Category:', 'linkcentral' ),
            'edit_item'         => __( 'Edit Link Category', 'linkcentral' ),
            'update_item'       => __( 'Update Link Category', 'linkcentral' ),
            'add_new_item'      => __( 'Add New Link Category', 'linkcentral' ),
            'new_item_name'     => __( 'New Link Category Name', 'linkcentral' ),
            'menu_name'         => __( 'Link Categories', 'linkcentral' ),
        );
        $args = array(
            'hierarchical'       => true,
            'labels'             => $labels,
            'show_ui'            => true,
            'show_admin_column'  => true,
            'query_var'          => false,
            'rewrite'            => false,
            'public'             => false,
            'publicly_queryable' => false,
            'show_in_rest'       => true,
        );
        register_taxonomy( 'linkcentral_category', array('linkcentral_link'), $args );
    }

    /**
     * Remove the default count column from the Link Categories admin list table.
     *
     * @param array $columns Existing columns.
     * @return array Modified columns.
     */
    public function filter_linkcentral_category_columns( $columns ) {
        if ( isset( $columns['posts'] ) ) {
            unset($columns['posts']);
        }
        return $columns;
    }

    /**
     * Add custom meta boxes for the link post type
     */
    public function add_meta_boxes() {
        global $post;
        $title = __( 'Link Details', 'linkcentral' );
        // Only add ID if this is an existing post
        if ( $post && $post->ID ) {
            $title = sprintf( '%s <span id="linkcentral-id-badge">ID: %d</span>', $title, $post->ID );
        }
        add_meta_box(
            'linkcentral_link_details',
            $title,
            array($this, 'render_meta_box'),
            'linkcentral_link',
            'normal',
            'high'
        );
        add_meta_box(
            'linkcentral_link_tools',
            __( 'Tools', 'linkcentral' ),
            array($this, 'render_tools_meta_box'),
            'linkcentral_link',
            'normal',
            'default'
        );
        // Add auto-keyword linking meta box for premium users and when feature is enabled
        if ( linkcentral_fs()->can_use_premium_code__premium_only() && get_option( 'linkcentral_enable_auto_keyword_linking', false ) ) {
            add_meta_box(
                'linkcentral_keywords',
                __( 'Auto-Keyword Linking', 'linkcentral' ),
                array($this, 'render_keywords_meta_box'),
                'linkcentral_link',
                'normal',
                'default'
            );
        }
    }

    /**
     * Remove the default slug meta box
     */
    public function remove_slug_meta_box() {
        remove_meta_box( 'slugdiv', 'linkcentral_link', 'normal' );
    }

    /**
     * Render the custom meta box for link details
     *
     * @param WP_Post $post The current post object
     */
    public function render_meta_box( $post ) {
        wp_nonce_field( $this->nonce_action, $this->nonce_name );
        $destination_url = get_post_meta( $post->ID, '_linkcentral_destination_url', true );
        $nofollow = get_post_meta( $post->ID, '_linkcentral_nofollow', true );
        $new_tab = get_post_meta( $post->ID, '_linkcentral_new_tab', true );
        $sponsored = get_post_meta( $post->ID, '_linkcentral_sponsored', true );
        $redirection_type = get_post_meta( $post->ID, '_linkcentral_redirection_type', true );
        $parameter_forwarding = get_post_meta( $post->ID, '_linkcentral_parameter_forwarding', true );
        $css_classes_option = get_post_meta( $post->ID, '_linkcentral_css_classes_option', true );
        $custom_css_classes = get_post_meta( $post->ID, '_linkcentral_custom_css_classes', true );
        $other_attributes_option = get_post_meta( $post->ID, '_linkcentral_other_attributes_option', true );
        $custom_other_attributes = get_post_meta( $post->ID, '_linkcentral_custom_other_attributes', true );
        $disable_slug_prefix = get_post_meta( $post->ID, '_linkcentral_disable_slug_prefix', true );
        $url_prefix = get_option( 'linkcentral_url_prefix', 'go' );
        // For new posts, use the default setting
        if ( empty( $post->ID ) || $post->post_status === 'auto-draft' ) {
            $default_disable_prefix = get_option( 'linkcentral_default_disable_prefix', false );
            $disable_slug_prefix = $default_disable_prefix;
        }
        // Set default value for destination URL if it's empty
        $destination_url = ( $destination_url ?: 'https://' );
        // Get existing rules and set button class only for premium users
        $existing_rules = [];
        $rules_set_class = '';
        $existing_rules_json = ( !empty( $existing_rules ) ? wp_json_encode( $existing_rules ) : '[]' );
        ?>
        <table class="linkcentral-form-table linkcentral-form-table-condensed form-table">
            <tr>
                <th scope="row"><label for="post_name"><?php 
        esc_html_e( 'Slug:', 'linkcentral' );
        ?></label></th>
                <td>
                    <div id="linkcentral-url-prefix" data-home-url="<?php 
        echo esc_url( home_url( '/' ) );
        ?>">
                        <?php 
        echo esc_html( home_url( '/' ) );
        ?><span class="linkcentral-slug-toggle <?php 
        echo esc_attr( ( $disable_slug_prefix ? 'linkcentral-slug-disabled' : '' ) );
        ?>"
                             data-slug="<?php 
        echo esc_attr( $url_prefix . '/' );
        ?>"
                             title="<?php 
        esc_attr_e( 'Click to toggle URL prefix', 'linkcentral' );
        ?>"><?php 
        echo esc_html( $url_prefix . '/' );
        ?></span>
                    </div>
                    <input type="hidden" id="linkcentral_disable_slug_prefix" name="linkcentral_disable_slug_prefix" value="<?php 
        echo esc_attr( ( $disable_slug_prefix ? '1' : '0' ) );
        ?>">
                    <div class="linkcentral-slug-container">
                        <div class="linkcentral-slug-input-wrapper">
                            <input type="text" id="post_name" name="post_name" value="<?php 
        echo esc_attr( $post->post_name );
        ?>" required>
                            <button type="button" id="linkcentral-generate-slug" class="linkcentral-generate-slug-button" title="<?php 
        esc_attr_e( 'Generate a random slug', 'linkcentral' );
        ?>">
                                <span class="dashicons dashicons-update"></span>
                            </button>
                        </div>
                        <button type="button" id="linkcentral-copy-url" class="button button-secondary"><?php 
        esc_html_e( 'Copy URL', 'linkcentral' );
        ?></button>
                    </div>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="linkcentral_destination_url"><?php 
        esc_html_e( 'Destination URL:', 'linkcentral' );
        ?></label></th>
                <td>
                    <div class="linkcentral-destination-container">
                        <div class="linkcentral-destination-input-wrapper">
                            <input type="url" id="linkcentral_destination_url" name="linkcentral_destination_url" value="<?php 
        echo esc_url( $destination_url );
        ?>" size="50" required<?php 
        echo ( linkcentral_fs()->can_use_premium_code__premium_only() && get_option( 'linkcentral_enable_utm_templates' ) ? ' style="padding-right: 35px;"' : '' );
        ?>>
                            <?php 
        ?>
                        </div>
                        <button type="button" id="linkcentral-dynamic-redirect" class="button button-secondary <?php 
        echo esc_attr( $rules_set_class );
        ?>">
                            <span class="dashicons dashicons-randomize"></span>
                            <?php 
        esc_html_e( 'Dynamic', 'linkcentral' );
        ?>
                            <?php 
        ?>
                                <span class="dashicons dashicons-lock linkcentral-dashicons-premium"></span>
                            <?php 
        ?>
                        </button>
                    </div>
                </td>
            </tr>
        </table>

        <h4><?php 
        esc_html_e( 'Link Attributes', 'linkcentral' );
        ?>:</h4>
        <table class="linkcentral-form-table linkcentral-form-table-condensed form-table" id="linkcentral-link-attributes">
            <tr>
                <th scope="row"><label for="linkcentral_new_tab"><?php 
        esc_html_e( 'Open in New Tab:', 'linkcentral' );
        ?></label></th>
                <td>
                    <select name="linkcentral_new_tab" id="linkcentral_new_tab">
                        <option value="default" <?php 
        selected( $new_tab, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="yes" <?php 
        selected( $new_tab, 'yes' );
        ?>><?php 
        esc_html_e( 'Yes', 'linkcentral' );
        ?></option>
                        <option value="no" <?php 
        selected( $new_tab, 'no' );
        ?>><?php 
        esc_html_e( 'No', 'linkcentral' );
        ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="linkcentral_nofollow"><?php 
        esc_html_e( 'Nofollow Attribute:', 'linkcentral' );
        ?></label></th>
                <td>
                    <select name="linkcentral_nofollow" id="linkcentral_nofollow">
                        <option value="default" <?php 
        selected( $nofollow, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="yes" <?php 
        selected( $nofollow, 'yes' );
        ?>><?php 
        esc_html_e( 'Yes', 'linkcentral' );
        ?></option>
                        <option value="no" <?php 
        selected( $nofollow, 'no' );
        ?>><?php 
        esc_html_e( 'No', 'linkcentral' );
        ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="linkcentral_sponsored"><?php 
        esc_html_e( 'Sponsored Attribute:', 'linkcentral' );
        ?></label></th>
                <td>
                    <select name="linkcentral_sponsored" id="linkcentral_sponsored">
                        <option value="default" <?php 
        selected( $sponsored, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="yes" <?php 
        selected( $sponsored, 'yes' );
        ?>><?php 
        esc_html_e( 'Yes', 'linkcentral' );
        ?></option>
                        <option value="no" <?php 
        selected( $sponsored, 'no' );
        ?>><?php 
        esc_html_e( 'No', 'linkcentral' );
        ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="linkcentral_other_attributes_option"><?php 
        esc_html_e( 'Other Attributes:', 'linkcentral' );
        ?></label></th>
                <td class="linkcentral-attribute-input-row">
                    <select name="linkcentral_other_attributes_option" id="linkcentral_other_attributes_option">
                        <option value="default" <?php 
        selected( $other_attributes_option, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="replace" <?php 
        selected( $other_attributes_option, 'replace' );
        ?>><?php 
        esc_html_e( 'Replace with:', 'linkcentral' );
        ?></option>
                        <option value="append" <?php 
        selected( $other_attributes_option, 'append' );
        ?>><?php 
        esc_html_e( 'Append with:', 'linkcentral' );
        ?></option>
                    </select>
                    <input type="text" id="linkcentral_custom_other_attributes" name="linkcentral_custom_other_attributes" value="<?php 
        echo esc_attr( $custom_other_attributes );
        ?>" placeholder="<?php 
        esc_attr_e( 'e.g., noreferrer', 'linkcentral' );
        ?>" style="display: <?php 
        echo ( $other_attributes_option === '' || $other_attributes_option === 'default' ? 'none' : 'inline-block' );
        ?>;">
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="linkcentral_redirection_type"><?php 
        esc_html_e( 'Redirection Type:', 'linkcentral' );
        ?></label></th>
                <td>
                    <select name="linkcentral_redirection_type" id="linkcentral_redirection_type">
                        <option value="default" <?php 
        selected( $redirection_type, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="307" <?php 
        selected( $redirection_type, '307' );
        ?>><?php 
        esc_html_e( '307 (Temporary)', 'linkcentral' );
        ?></option>
                        <option value="302" <?php 
        selected( $redirection_type, '302' );
        ?>><?php 
        esc_html_e( '302 (Temporary)', 'linkcentral' );
        ?></option>
                        <option value="301" <?php 
        selected( $redirection_type, '301' );
        ?>><?php 
        esc_html_e( '301 (Permanent)', 'linkcentral' );
        ?></option>
                    </select>
                </td>
            </tr>
            <tr class="linkcentral-premium-feature <?php 
        echo ( linkcentral_fs()->can_use_premium_code__premium_only() ? 'linkcentral-premium-active' : '' );
        ?>">
                <th scope="row"><label for="linkcentral_parameter_forwarding"><?php 
        esc_html_e( 'Parameter Forwarding:', 'linkcentral' );
        ?></label></th>
                <td>
                    <select name="linkcentral_parameter_forwarding" id="linkcentral_parameter_forwarding" <?php 
        echo ( !linkcentral_fs()->can_use_premium_code__premium_only() ? 'disabled' : '' );
        ?>>
                        <option value="default" <?php 
        selected( $parameter_forwarding, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="yes" <?php 
        selected( $parameter_forwarding, 'yes' );
        ?>><?php 
        esc_html_e( 'Yes', 'linkcentral' );
        ?></option>
                        <option value="no" <?php 
        selected( $parameter_forwarding, 'no' );
        ?>><?php 
        esc_html_e( 'No', 'linkcentral' );
        ?></option>
                    </select>
                    <?php 
        ?>
                        <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=linkcentral-settings#linkcentral-premium' ) );
        ?>" class="linkcentral-premium-tag"><?php 
        esc_html_e( 'Premium', 'linkcentral' );
        ?></a>
                    <?php 
        ?>
                </td>
            </tr>
            <tr class="linkcentral-premium-feature <?php 
        echo ( linkcentral_fs()->can_use_premium_code__premium_only() ? 'linkcentral-premium-active' : '' );
        ?>">
                <th scope="row"><label for="linkcentral_css_classes_option"><?php 
        esc_html_e( 'CSS Classes:', 'linkcentral' );
        ?></label></th>
                <td class="linkcentral-attribute-input-row">
                    <select name="linkcentral_css_classes_option" id="linkcentral_css_classes_option" <?php 
        echo ( !linkcentral_fs()->can_use_premium_code__premium_only() ? 'disabled' : '' );
        ?>>
                        <option value="default" <?php 
        selected( $css_classes_option, 'default' );
        ?>><?php 
        esc_html_e( 'Default (Global Settings)', 'linkcentral' );
        ?></option>
                        <option value="replace" <?php 
        selected( $css_classes_option, 'replace' );
        ?>><?php 
        esc_html_e( 'Replace with:', 'linkcentral' );
        ?></option>
                        <option value="append" <?php 
        selected( $css_classes_option, 'append' );
        ?>><?php 
        esc_html_e( 'Append with:', 'linkcentral' );
        ?></option>
                    </select>
                    <input type="text" id="linkcentral_custom_css_classes" name="linkcentral_custom_css_classes" value="<?php 
        echo esc_attr( $custom_css_classes );
        ?>" placeholder="<?php 
        esc_attr_e( 'Custom CSS Classes', 'linkcentral' );
        ?>" style="display: <?php 
        echo ( $css_classes_option === '' || $css_classes_option === 'default' || !linkcentral_fs()->can_use_premium_code__premium_only() ? 'none' : 'inline-block' );
        ?>;" <?php 
        echo ( !linkcentral_fs()->can_use_premium_code__premium_only() ? 'disabled' : '' );
        ?>>
                    <?php 
        ?>
                        <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=linkcentral-settings#linkcentral-premium' ) );
        ?>" class="linkcentral-premium-tag"><?php 
        esc_html_e( 'Premium', 'linkcentral' );
        ?></a>
                    <?php 
        ?>
                </td>
            </tr>
        </table>
        <?php 
        ?>
            <!-- Dynamic Redirect Modal (Free Version) -->
            <div id="linkcentral-dynamic-redirect-modal" class="linkcentral-modal">
                <div class="linkcentral-dynamic-redirect-modal-content">
                    <div class="linkcentral-dynamic-redirect-modal-inner">
                        <span class="linkcentral-dynamic-redirect-modal-close">&times;</span>
                        <h3>
                        <?php 
        esc_html_e( 'Dynamic Redirect Rules', 'linkcentral' );
        ?>
                            <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=linkcentral-settings#linkcentral-premium' ) );
        ?>" class="linkcentral-premium-tag"><?php 
        esc_html_e( 'Premium', 'linkcentral' );
        ?></a>
                        </h3>
                        <p><?php 
        esc_html_e( 'Upgrade to LinkCentral Premium to unlock advanced Dynamic Redirects, including redirects by device, country, date, time, number of clicks, and other powerful features!', 'linkcentral' );
        ?></p>
                        <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=linkcentral-settings#linkcentral-premium' ) );
        ?>" class="button button-primary"><?php 
        esc_html_e( 'Upgrade Now', 'linkcentral' );
        ?></a>
                        <a href="<?php 
        echo esc_url( 'https://designforwp.com/docs/linkcentral/creating-and-using-links/dynamic-redirects/' );
        ?>" target="_blank" class="button button-secondary"><?php 
        esc_html_e( 'Learn More About Dynamic Redirects', 'linkcentral' );
        ?></a>
                        <img src="<?php 
        echo esc_url( LINKCENTRAL_PLUGIN_URL . 'assets/images/linkcentral-dynamic-redirects-premium-banner.png' );
        ?>" alt="Advanced Dynamic Redirects with LinkCentral Premium" class="linkcentral-dynamic-redirects-premium-banner">

                    </div>
                </div>
            </div>
        <?php 
        ?>
        
        <?php 
    }

    /**
     * Render the meta box for tools
     *
     * @param WP_Post $post The current post object
     */
    public function render_tools_meta_box( $post ) {
        $note = get_post_meta( $post->ID, '_linkcentral_note', true );
        $qr_codes_enabled = get_option( 'linkcentral_enable_qr_codes', false );
        ?>
        <table class="linkcentral-form-table linkcentral-form-table-condensed form-table">
            <?php 
        if ( $qr_codes_enabled && $post->ID ) {
            ?>
            <tr>
                <th scope="row"><label><?php 
            esc_html_e( 'QR Code:', 'linkcentral' );
            ?></label></th>
                <td>
                    <button type="button" id="linkcentral-generate-qr" class="button button-secondary">
                        <?php 
            esc_html_e( 'Generate QR Code', 'linkcentral' );
            ?>
                    </button>
                </td>
            </tr>
            <?php 
        }
        ?>
            <tr>
                <th scope="row"><label for="linkcentral_note"><?php 
        esc_html_e( 'Administrative Note:', 'linkcentral' );
        ?></label></th>
                <td>
                    <div class="linkcentral-note-display">
                        <span class="linkcentral-note-text"><?php 
        echo esc_html( $note );
        ?></span>
                        <a href="#" class="linkcentral-edit-note">
                            <span class="dashicons dashicons-edit"></span>
                            <?php 
        esc_html_e( 'Edit', 'linkcentral' );
        ?>
                        </a>
                    </div>
                    <div class="linkcentral-note-edit" style="display: none;">
                        <textarea name="linkcentral_note" id="linkcentral_note" rows="4" style="width: 100%;"><?php 
        echo esc_textarea( $note );
        ?></textarea>
                        <p class="description"><?php 
        esc_html_e( 'This note is for your administrative purposes only and will not be displayed publicly.', 'linkcentral' );
        ?></p>
                        <button type="button" class="linkcentral-save-note button button-primary"><?php 
        esc_html_e( 'Update', 'linkcentral' );
        ?></button>
                        <button type="button" class="linkcentral-cancel-edit button button-secondary"><?php 
        esc_html_e( 'Cancel', 'linkcentral' );
        ?></button>
                    </div>
                </td>
            </tr>
        </table>

        <?php 
        if ( $qr_codes_enabled && $post->ID ) {
            ?>
            <!-- QR Code Modal -->
            <div id="linkcentral-qr-modal" class="linkcentral-modal">
                <div class="linkcentral-qr-modal-content">
                    <div class="linkcentral-qr-modal-inner">
                        <span class="linkcentral-qr-modal-close">&times;</span>
                        <h3><?php 
            esc_html_e( 'QR Code', 'linkcentral' );
            ?></h3>
                        
                        <div class="linkcentral-qr-content">
                            <div class="linkcentral-qr-canvas-container">
                                <canvas id="linkcentral-qr-canvas"></canvas>
                            </div>
                            <div class="linkcentral-qr-info">
                                <p><strong><?php 
            esc_html_e( 'Short URL to:', 'linkcentral' );
            ?></strong></p>
                                <p class="linkcentral-qr-url" id="linkcentral-qr-url"></p>
                            </div>
                        </div>
                        
                        <div class="linkcentral-qr-actions">
                            <button type="button" id="linkcentral-qr-download-png" class="button button-primary">
                                <span class="dashicons dashicons-download"></span>
                                <?php 
            esc_html_e( 'Download PNG', 'linkcentral' );
            ?>
                            </button>
                            <button type="button" id="linkcentral-qr-download-svg" class="button">
                                <span class="dashicons dashicons-download"></span>
                                <?php 
            esc_html_e( 'Download SVG', 'linkcentral' );
            ?>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        <?php 
        }
        ?>
        <?php 
    }

    /**
     * Render the keywords meta box for auto-keyword linking
     *
     * @param WP_Post $post The current post object
     */
    public function render_keywords_meta_box( $post ) {
        // Check if auto-keyword linking is enabled
        $auto_keyword_linking_enabled = get_option( 'linkcentral_enable_auto_keyword_linking', false );
        if ( !$auto_keyword_linking_enabled ) {
            echo '<p>' . esc_html__( 'Auto-keyword linking is not enabled. Enable it in the LinkCentral settings to use this feature.', 'linkcentral' ) . '</p>';
            return;
        }
        // Get existing keywords for this link
        global $wpdb;
        $keywords = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}linkcentral_keywords` WHERE link_id = %d ORDER BY id ASC", $post->ID ) );
        ?>
        <div class="linkcentral-keywords">
            <p class="description"><?php 
        esc_html_e( 'Define keywords that will be automatically replaced with this link across your website, along with their density.', 'linkcentral' );
        ?></p>
            
            <div id="linkcentral-keywords-container">
                <?php 
        if ( !empty( $keywords ) ) {
            ?>
                    <?php 
            foreach ( $keywords as $keyword ) {
                ?>
                        <div class="linkcentral-keyword-row">
                            <input type="text" name="linkcentral_keywords[]" value="<?php 
                echo esc_attr( $keyword->keyword );
                ?>" placeholder="<?php 
                esc_attr_e( 'Enter keyword or phrase', 'linkcentral' );
                ?>" class="regular-text">
                            <select name="linkcentral_keyword_densities[]">
                                <option value="low" <?php 
                selected( $keyword->density, 'low' );
                ?>><?php 
                esc_html_e( 'Low', 'linkcentral' );
                ?></option>
                                <option value="medium" <?php 
                selected( $keyword->density, 'medium' );
                ?>><?php 
                esc_html_e( 'Medium', 'linkcentral' );
                ?></option>
                                <option value="high" <?php 
                selected( $keyword->density, 'high' );
                ?>><?php 
                esc_html_e( 'High', 'linkcentral' );
                ?></option>
                            </select>
                            <button type="button" class="button button-secondary linkcentral-remove-keyword"><?php 
                esc_html_e( 'Remove', 'linkcentral' );
                ?></button>
                        </div>
                    <?php 
            }
            ?>
                <?php 
        }
        ?>
            </div>
            
            <button type="button" class="button button-secondary" id="linkcentral-add-keyword"><?php 
        esc_html_e( 'Add Keyword', 'linkcentral' );
        ?></button>
        </div>

        <script type="text/template" id="linkcentral-keyword-template">
            <div class="linkcentral-keyword-row">
                <input type="text" name="linkcentral_keywords[]" placeholder="<?php 
        esc_attr_e( 'Enter keyword or phrase', 'linkcentral' );
        ?>" class="regular-text">
                <select name="linkcentral_keyword_densities[]">
                    <option value="low"><?php 
        esc_html_e( 'Low', 'linkcentral' );
        ?></option>
                    <option value="medium" selected><?php 
        esc_html_e( 'Medium', 'linkcentral' );
        ?></option>
                    <option value="high"><?php 
        esc_html_e( 'High', 'linkcentral' );
        ?></option>
                </select>
                <button type="button" class="button button-secondary linkcentral-remove-keyword"><?php 
        esc_html_e( 'Remove', 'linkcentral' );
        ?></button>
            </div>
        </script>
        <?php 
    }

    /**
     * Validate post data before saving to prevent invalid posts
     *
     * @param array $data An array of slashed, sanitized, and processed post data.
     * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
     * @return array Modified post data.
     */
    public function validate_post_data( $data, $postarr ) {
        // Only validate LinkCentral links
        if ( $data['post_type'] !== 'linkcentral_link' ) {
            return $data;
        }
        // Skip validation during autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return $data;
        }
        // Skip validation if this is not a POST request or no POST data
        if ( empty( $_POST ) ) {
            return $data;
        }
        // Check nonce
        if ( !isset( $_POST[$this->nonce_name] ) || !wp_verify_nonce( sanitize_key( $_POST[$this->nonce_name] ), $this->nonce_action ) ) {
            return $data;
        }
        // Prepare data for validation
        $link_data = [
            'title'           => ( isset( $_POST['post_title'] ) ? sanitize_text_field( wp_unslash( $_POST['post_title'] ) ) : '' ),
            'slug'            => ( isset( $_POST['post_name'] ) ? linkcentral_sanitize_input_slug( sanitize_text_field( wp_unslash( $_POST['post_name'] ) ) ) : '' ),
            'destination_url' => ( isset( $_POST['linkcentral_destination_url'] ) ? esc_url_raw( wp_unslash( $_POST['linkcentral_destination_url'] ) ) : '' ),
        ];
        // Use Link Manager for validation
        $post_id = ( isset( $postarr['ID'] ) ? intval( $postarr['ID'] ) : 0 );
        $validation_result = $this->link_manager->validate_link_data( $link_data, 'admin', $post_id );
        if ( is_wp_error( $validation_result ) ) {
            $error_message = $validation_result->get_error_message();
            wp_die( esc_html( $error_message ), esc_html__( 'Validation Error', 'linkcentral' ), array(
                'back_link' => true,
            ) );
        }
        return $data;
    }

    /**
     * Save the custom meta box data
     *
     * @param int $post_id The ID of the post being saved
     * @param WP_Post $post The post object
     */
    public function save_meta_boxes( $post_id, $post ) {
        // Single nonce check
        if ( !isset( $_POST[$this->nonce_name] ) || !wp_verify_nonce( sanitize_key( $_POST[$this->nonce_name] ), $this->nonce_action ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        if ( $post->post_type !== 'linkcentral_link' ) {
            return;
        }
        // Check for appropriate capabilities
        if ( !current_user_can( 'linkcentral_create_edit_links' ) ) {
            wp_die( esc_html__( 'You do not have permission to create or edit links.', 'linkcentral' ) );
        }
        // Prepare data from POST for Link Manager
        $link_data = [
            'title' => $post->post_title,
            'slug'  => $post->post_name,
        ];
        // Add basic fields
        $basic_fields = [
            'linkcentral_destination_url'         => 'destination_url',
            'linkcentral_new_tab'                 => 'new_tab',
            'linkcentral_nofollow'                => 'nofollow',
            'linkcentral_sponsored'               => 'sponsored',
            'linkcentral_redirection_type'        => 'redirection_type',
            'linkcentral_note'                    => 'note',
            'linkcentral_other_attributes_option' => 'other_attributes_option',
            'linkcentral_custom_other_attributes' => 'custom_other_attributes',
        ];
        foreach ( $basic_fields as $post_field => $data_field ) {
            if ( isset( $_POST[$post_field] ) ) {
                // Sanitize based on field type
                switch ( $data_field ) {
                    case 'destination_url':
                        $link_data[$data_field] = esc_url_raw( wp_unslash( $_POST[$post_field] ) );
                        break;
                    case 'note':
                        $link_data[$data_field] = sanitize_textarea_field( wp_unslash( $_POST[$post_field] ) );
                        break;
                    default:
                        $link_data[$data_field] = sanitize_text_field( wp_unslash( $_POST[$post_field] ) );
                        break;
                }
            }
        }
        // Add boolean fields
        $link_data['disable_slug_prefix'] = isset( $_POST['linkcentral_disable_slug_prefix'] ) && $_POST['linkcentral_disable_slug_prefix'] === '1';
        // Use Link Manager to update the link
        $result = $this->link_manager->update_link( $post_id, $link_data );
        if ( is_wp_error( $result ) ) {
            wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Save Error', 'linkcentral' ), array(
                'back_link' => true,
            ) );
        }
    }

    /**
     * Add a meta box to display the How to Use for the link
     */
    public function add_how_to_use_meta_box() {
        add_meta_box(
            'linkcentral_how_to_use',
            __( 'How to Use This Link', 'linkcentral' ),
            array($this, 'render_how_to_use_meta_box'),
            'linkcentral_link',
            'side',
            'low'
        );
    }

    /**
     * Render the How to Use meta box
     *
     * @param WP_Post $post The current post object
     */
    public function render_how_to_use_meta_box( $post ) {
        /* 
         $shortcode = sprintf('[linkcentral id="%d"]Your text[/linkcentral]', $post->ID);
         <a href="#" class="linkcentral-copy-shortcode" data-shortcode="<?php echo esc_attr($shortcode); ?>"><?php esc_html_e('Copy', 'linkcentral'); ?></a> 
        */
        ?>
        <div class="linkcentral-how-to-use">
            <p class="description">
                <?php 
        printf( 
            // translators: %s is the URL to the usage settings page
            esc_html__( 'Please see the %s for instructions on how to insert a link into your content.', 'linkcentral' ),
            '<a href="' . esc_url( 'https://designforwp.com/docs/linkcentral/creating-and-using-links/inserting-links-into-your-content/' ) . '" target="_blank">' . esc_html__( 'overview', 'linkcentral' ) . '</a>'
         );
        ?>
            </p>
        </div>
        <?php 
    }

    /**
     * Customize the post updated messages for the link post type
     *
     * @param array $messages The existing post update messages
     * @return array The modified post update messages
     */
    public function custom_post_updated_messages( $messages ) {
        global $post, $post_ID;
        $messages['linkcentral_link'] = array(
            0  => '',
            1  => __( 'Link updated.', 'linkcentral' ),
            2  => __( 'Custom field updated.', 'linkcentral' ),
            3  => __( 'Custom field deleted.', 'linkcentral' ),
            4  => __( 'Link updated.', 'linkcentral' ),
            5  => ( isset( $_GET['revision'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'view-post-revision_' . $post_ID ) ? sprintf( 
                // Translators: %s is the revision date
                __( 'Link restored to revision from %s', 'linkcentral' ),
                wp_post_revision_title( (int) sanitize_text_field( wp_unslash( $_GET['revision'] ) ), false )
             ) : false ),
            6  => __( 'Link published.', 'linkcentral' ),
            7  => __( 'Link saved.', 'linkcentral' ),
            8  => __( 'Link submitted.', 'linkcentral' ),
            9  => sprintf( __( 'Link scheduled for: %1$s.', 'linkcentral' ), '<strong>' . date_i18n( 'M j, Y \\@ G:i', strtotime( $post->post_date ) ) . '</strong>' ),
            10 => __( 'Link draft updated (link is inactive).', 'linkcentral' ),
        );
        return $messages;
    }

    /**
     * Add custom admin header for LinkCentral pages
     */
    public function add_admin_header() {
        $screen = get_current_screen();
        if ( $screen->post_type === 'linkcentral_link' || $screen->id === 'edit-linkcentral_category' ) {
            do_action( 'linkcentral_admin_header' );
        }
    }

    /**
     * Redirect to LinkCentral admin page after trashing/untrashing a link
     *
     * @param string $location The redirect location
     * @param int $post_id The post ID
     * @return string Modified redirect location
     */
    public function redirect_after_trash( $location, $post_id ) {
        // Only modify redirect for LinkCentral links
        if ( get_post_type( $post_id ) !== 'linkcentral_link' ) {
            return $location;
        }
        // Check if this is a trash or untrash action by examining the current URL
        $get_action = ( isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '' );
        if ( $get_action && isset( $_GET['_wpnonce'] ) && in_array( $get_action, array('trash', 'untrash'), true ) && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'trash-post_' . $post_id ) ) {
            // Redirect to the LinkCentral overview page instead of the default edit page
            return admin_url( 'admin.php?page=linkcentral' );
        }
        return $location;
    }

    /**
     * Handle AJAX request to check and generate a unique slug
     */
    public function ajax_check_slug() {
        check_ajax_referer( 'linkcentral_admin_nonce', 'nonce' );
        $slug = ( isset( $_POST['slug'] ) ? linkcentral_sanitize_input_slug( sanitize_text_field( wp_unslash( $_POST['slug'] ) ) ) : '' );
        $post_id = ( isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0 );
        if ( empty( $slug ) ) {
            wp_send_json_error( array(
                'message' => __( 'Invalid slug.', 'linkcentral' ),
            ) );
        }
        $unique_slug = $this->link_manager->get_unique_slug( $slug, $post_id );
        wp_send_json_success( array(
            'unique_slug' => $unique_slug,
        ) );
    }

    /**
     * Remove 'pending' status for our custom post type.
     *
     * @param array   $statuses List of post statuses.
     * @param WP_Post $post     The post object.
     * @return array Modified list of post statuses.
     */
    public function remove_post_statuses( $statuses, $post ) {
        if ( $post && $post->post_type === 'linkcentral_link' ) {
            unset($statuses['pending']);
        }
        return $statuses;
    }

    /**
     * Filter the post data for LinkCentral links to preserve forward slashes and prevent pending status
     *
     * @param array $data    An array of slashed, sanitized, and processed post data.
     * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
     * @param array $unsanitized_postarr An array of slashed yet unsanitized and unprocessed post data.
     * @return array Modified post data.
     */
    public function filter_post_data( $data, $postarr, $unsanitized_postarr ) {
        if ( $data['post_type'] === 'linkcentral_link' ) {
            // Preserve forward slashes in slug
            if ( isset( $unsanitized_postarr['post_name'] ) ) {
                $slug = linkcentral_sanitize_input_slug( $unsanitized_postarr['post_name'] );
                // Use Link Manager for slug uniqueness checking
                $post_id = ( isset( $postarr['ID'] ) ? intval( $postarr['ID'] ) : 0 );
                // Create temporary Link Manager instance if not available
                if ( !$this->link_manager ) {
                    $this->link_manager = new LinkCentral_Link_Manager();
                }
                $data['post_name'] = $this->link_manager->get_unique_slug( $slug, $post_id );
            }
            // Prevent pending status
            if ( in_array( $data['post_status'], ['pending'] ) ) {
                $data['post_status'] = 'draft';
            }
        }
        return $data;
    }

    /**
     * Enqueue admin scripts
     *
     * @param string $hook The current admin page hook
     */
    public function enqueue_admin_scripts( $hook ) {
        if ( 'post.php' != $hook && 'post-new.php' != $hook ) {
            return;
        }
        global $post;
        if ( 'linkcentral_link' !== $post->post_type ) {
            return;
        }
        wp_enqueue_script(
            'linkcentral-dynamic-redirect-modal',
            LINKCENTRAL_PLUGIN_URL . 'assets/js/modals/dynamic-redirect.js',
            array('jquery'),
            LINKCENTRAL_VERSION,
            true
        );
        // Register script translations for dynamic redirect modal
        wp_set_script_translations( 'linkcentral-dynamic-redirect-modal', 'linkcentral' );
        // Enqueue QR code modal script if QR codes are enabled
        if ( get_option( 'linkcentral_enable_qr_codes', false ) ) {
            // Enqueue vendor chunks (same approach as insights page)
            $vendor_chunks = glob( LINKCENTRAL_PLUGIN_DIR . 'assets/js/vendor.*.js' );
            $vendor_dependencies = array();
            foreach ( $vendor_chunks as $chunk ) {
                $chunk_name = basename( $chunk, '.js' );
                $handle = "linkcentral-{$chunk_name}";
                wp_enqueue_script(
                    $handle,
                    LINKCENTRAL_PLUGIN_URL . "assets/js/{$chunk_name}.js",
                    array(),
                    LINKCENTRAL_VERSION,
                    true
                );
                $vendor_dependencies[] = $handle;
            }
            // Make QR code modal depend on vendor chunks and jQuery
            $dependencies = array_merge( array('jquery'), $vendor_dependencies );
            wp_enqueue_script(
                'linkcentral-qr-code-modal',
                LINKCENTRAL_PLUGIN_URL . 'assets/js/modals/qr-code.js',
                $dependencies,
                LINKCENTRAL_VERSION,
                true
            );
            // Register script translations for QR code modal
            wp_set_script_translations( 'linkcentral-qr-code-modal', 'linkcentral' );
            // Localize QR code settings
            wp_localize_script( 'linkcentral-qr-code-modal', 'linkcentral_qr_settings', array(
                'linkcentral_qr_background_color'       => get_option( 'linkcentral_qr_background_color', '#FFFFFF' ),
                'linkcentral_qr_background_transparent' => get_option( 'linkcentral_qr_background_transparent', false ),
                'linkcentral_qr_front_color'            => get_option( 'linkcentral_qr_front_color', '#000000' ),
            ) );
        }
        // Get the countries data
        $countries = linkcentral_get_countries();
        // Get the current geolocation service
        $geolocation_service = get_option( 'linkcentral_geolocation_service', 'none' );
        // Get translated user role names
        $user_roles = array();
        foreach ( wp_roles()->get_names() as $role_slug => $role_name ) {
            $user_roles[$role_slug] = translate_user_role( $role_name );
        }
        wp_localize_script( 'linkcentral-dynamic-redirect-modal', 'linkcentral_data', array(
            'countries'                          => $countries,
            'can_use_premium_code__premium_only' => linkcentral_fs()->can_use_premium_code__premium_only(),
            'geolocation_service'                => $geolocation_service,
            'user_roles'                         => $user_roles,
            'utm_templates_enabled'              => get_option( 'linkcentral_enable_utm_templates', false ),
        ) );
    }

}
