<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Add the meta box
function reactify_add_reaction_meta_box() {
    add_meta_box(
        'reactify_reaction_meta_box',
        esc_html__( 'Post Reactions Settings', 'reactify' ),
        'reactify_render_reaction_meta_box',
        ['post', 'page'],
        'normal',
        'default'
    );
}
add_action( 'add_meta_boxes', 'reactify_add_reaction_meta_box' );

// Render the meta box
function reactify_render_reaction_meta_box( $post ) {
    // Retrieve current value
    $disable_reactions = get_post_meta( $post->ID, 'reactify_disable_reactions', true );

    // Add a nonce field for security
    wp_nonce_field( 'reactify_reaction_meta_box', 'reactify_reaction_meta_box_nonce' );

?>
    <p>
        <label>
            <input type="checkbox" id="reactify_disable_reactions" name="reactify_disable_reactions" value="1"
                <?php checked( $disable_reactions, '1' ); ?>>
            <?php esc_html_e( 'Disable Reactions for this post', 'reactify' ); ?>
        </label>
    </p>

    <div id="reactify-emojis-container">
        <?php
            $emojis = get_option( 'reactify_custom_emojis', ['like', 'love', 'happy', 'haha', 'sad', 'angry'] );

            foreach ( $emojis as $emoji ):
        ?>
            <div class="reactify-emoji-metabox">
                <img src="<?php echo esc_url( REACTIFY_BLOCK_INCLUDES_URL . '/assets/images/emoji-' . sanitize_file_name( $emoji ) . '.png' ); ?>"
                    alt="<?php echo esc_attr( $emoji ); ?>">
                <h4 class="reactify-react-title"><?php echo esc_html( ucfirst( esc_html( $emoji ) ) ); ?></h4>
            </div>
        <?php endforeach; ?>
    </div>
<?php
}

// Save the meta box data
function reactify_save_reaction_meta_box( $post_id ) {
    // Check if the user has permissions to save the post
    if ( !isset( $_POST['reactify_reaction_meta_box_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['reactify_reaction_meta_box_nonce'] ) ), 'reactify_reaction_meta_box' ) ) {
        return;
    }

    // Check autosave, user permissions, and bulk edits
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return;
    }

    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    // Sanitize and save the checkbox value
    $disable_reactions = isset( $_POST['reactify_disable_reactions'] ) ? '1' : '0';
    update_post_meta( $post_id, 'reactify_disable_reactions', $disable_reactions );
}
add_action( 'save_post', 'reactify_save_reaction_meta_box' );