<?php
/**
 * Adds a custom metabox with Select2 for selecting Wordpress posts.
 * 
 * @package     Dina Related Posts
 * @version     1.0.0
 * @author      Meysam Hosseinkhani
 */

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

// Register Metabox
add_action('add_meta_boxes', 'dina_register_related_posts_metabox');
function dina_register_related_posts_metabox() {
    add_meta_box(
        'dina_related_posts_box',
        __( 'Related posts (Dinakala)', 'dina-kala' ),
        'dina_related_posts_metabox_callback',
        'post',
        'normal',
        'high'
    );
}

// Render Metabox
function dina_related_posts_metabox_callback($post) {
    wp_nonce_field('dina_related_posts_nonce', 'dina_related_posts_metabox_nonce');
    $selected_posts = get_post_meta($post->ID, 'dina_related_posts', true);
    $selected_posts = is_array($selected_posts) ? $selected_posts : [];
    ?>
        <div class="inline notice woocommerce-message" style="">
            <img class="info-icon" src="<?= DI_URI . '/images/info.svg' ?>">
            <p>
                <?php _e( 'You can configure the settings for how related posts are displayed by going to "Dashboard > Appearance > Theme Settings > Post Settings > Related posts settings".', 'dina-kala' ) ?>
            </p>
        </div>
        <p>
            <label for="dina_related_posts" style="font-weight:bold;"><?= __( 'Post selection', 'dina-kala' ) ?></label><br>
            <select id="dina_related_posts" name="dina_related_posts[]" class="dina-select2-ajax" multiple="multiple" style="width:100%;" data-exclude="<?= $post->ID ?>">
                <?php
                    foreach ( $selected_posts as $post_id ) {
                        $post = get_post( (int) $post_id );
                        if ( $post && $post->post_type === 'post' ) {
                            printf(
                                '<option value="%d" selected>%s</option>',
                                esc_attr( $post_id ),
                                esc_html( get_the_title( $post ) )
                            );
                        }
                    }
                ?>
            </select>
        </p>
    <?php
}

// Save Posts
add_action('save_post', 'dina_save_related_posts_metabox');
function dina_save_related_posts_metabox($post_id) {
    if (
        !isset($_POST['dina_related_posts_metabox_nonce']) ||
        !wp_verify_nonce($_POST['dina_related_posts_metabox_nonce'], 'dina_related_posts_nonce') ||
        !current_user_can('edit_post', $post_id) ||
        (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    ) {
        return;
    }

    $posts = isset($_POST['dina_related_posts']) ? array_map('intval', $_POST['dina_related_posts']) : [];
    $posts = array_filter($posts);
    if (!empty($posts)) {
        update_post_meta($post_id, 'dina_related_posts', $posts);
    } else {
        delete_post_meta($post_id, 'dina_related_posts');
    }
}

// Enqueue scripts and styles
add_action('admin_enqueue_scripts', 'dina_enqueue_related_posts_scripts');
function dina_enqueue_related_posts_scripts($hook) {
    if (!in_array($hook, ['post.php', 'post-new.php'])) return;

    wp_enqueue_style( 'dina-select2-style' );
    wp_enqueue_script( 'dina-select2-script' );
    wp_enqueue_script( 'dina-select2-related-posts-ajax', DI_URI . '/includes/assets/js/dina-related-posts.js', ['jquery', 'select2'], DI_VER, true );

    wp_localize_script('dina-select2-related-posts-ajax', 'dina_related_posts_ajax', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('dina_search_posts'),
        'i18n'    => array(
            'inputTooShort' => esc_html__( 'Please enter at least 3 characters', 'dina-kala' ),
            'noResults'     => esc_html__( 'No results found', 'dina-kala' ),
            'searching'     => esc_html__( 'Searching...', 'dina-kala' ),
            'placeholder'   => esc_html__( 'Start typing...', 'dina-kala' ),
        )
    ]);
}

// Ajax Posts Search
add_action('wp_ajax_dina_search_posts', 'dina_search_posts_callback');
function dina_search_posts_callback() {
    if (!check_ajax_referer('dina_search_posts', '_ajax_nonce', false)) {
        wp_send_json_error(['message' => __( 'Security error', 'dina-kala' )]);
    }

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => __( 'No access', 'dina-kala' )]);
    }

    $search  = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
    $exclude = isset($_GET['exclude']) ? intval($_GET['exclude']) : '';

    $args = [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => 20,
        'post__not_in'   => array($exclude),
        's'              => $search,
    ];

    $query = new WP_Query($args);

    $results = [];
    foreach ($query->posts as $post) {
        $results[] = [
            'id'   => $post->ID,
            'text' => $post->post_title ?: sprintf( __( 'Untitled (ID: %d)', 'dina-kala' ), $post->ID ),
        ];
    }

    wp_send_json($results);
}