<?php

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

function reactify_reaction() {

    check_ajax_referer( 'reactify-nonce', 'security' );

    global $wpdb;

    $user_id       = get_current_user_id();
    $post_id       = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
    $emoji_type    = isset( $_POST['emoji_type'] ) ? sanitize_text_field( wp_unslash( $_POST['emoji_type'] ) ) : '';
    $reaction_time = gmdate( 'Y-m-d H:i:s' );
    $cookie_name   = 'wp_post_reaction_' . $post_id;
    $cookie_value  = isset( $_COOKIE[$cookie_name] ) ? sanitize_text_field( wp_unslash( $_COOKIE[$cookie_name] ) ) : '';

    $table_name = $wpdb->prefix . 'reactify';

    if ( $post_id ) {
        if ( $user_id ) {
            // User is logged in
            $existing_reaction = $wpdb->get_row( $wpdb->prepare(
                "SELECT * FROM $table_name WHERE post_id = %d AND user_id = %d",
                $post_id,
                $user_id
            ) );

            if ( $existing_reaction ) {
                // Update the existing reaction
                $wpdb->update(
                    $table_name,
                    array(
                        'emoji_type' => $emoji_type,
                        'reaction_time' => $reaction_time
                    ),
                    array(
                        'post_id' => $post_id,
                        'user_id' => $user_id
                    ),
                    array(
                        '%s',
                        '%s'
                    ),
                    array(
                        '%d',
                        '%d'
                    )
                );
            } else {
                // Insert a new reaction
                $wpdb->insert(
                    $table_name,
                    array(
                        'post_id' => $post_id,
                        'user_id' => $user_id,
                        'emoji_type' => $emoji_type,
                        'reaction_time' => $reaction_time
                    ),
                    array(
                        '%d',
                        '%d',
                        '%s',
                        '%s'
                    )
                );
            }
        } else {

            if ( $cookie_value ) {
                // Cookie exists, update the reaction
                $existing_reaction = $wpdb->get_row( $wpdb->prepare(
                    "SELECT * FROM $table_name WHERE post_id = %d AND cookie_value = %s",
                    $post_id,
                    $cookie_value
                ) );

                if ( $existing_reaction ) {
                    $wpdb->update(
                        $table_name,
                        array(
                            'emoji_type' => $emoji_type,
                            'reaction_time' => $reaction_time
                        ),
                        array(
                            'post_id' => $post_id,
                            'cookie_value' => $cookie_value
                        ),
                        array(
                            '%s',
                            '%s'
                        ),
                        array(
                            '%d',
                            '%s'
                        )
                    );
                }
            } else {
                // Generate a unique cookie value
                $cookie_value = wp_generate_uuid4();
                setcookie( $cookie_name, $cookie_value, time() + 5 * DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );

                // Insert a new reaction
                $wpdb->insert(
                    $table_name,
                    array(
                        'post_id' => $post_id,
                        'cookie_value' => $cookie_value,
                        'emoji_type' => $emoji_type,
                        'reaction_time' => $reaction_time
                    ),
                    array(
                        '%d',
                        '%s',
                        '%s',
                        '%s'
                    )
                );
            }
        }
    }

    wp_die();
}
add_action( 'wp_ajax_reactify_reaction', 'reactify_reaction' );
add_action( 'wp_ajax_nopriv_reactify_reaction', 'reactify_reaction' );

function reactify_save_reaction_title_callback() {

    check_ajax_referer( 'reactify-nonce', 'security' );

    if ( isset( $_POST['reaction_title'] ) ) {
        $reaction_title         = sanitize_text_field( wp_unslash( $_POST['reaction_title'] ) );
        $reaction_title_enabled = sanitize_text_field( wp_unslash( $_POST['reaction_title_enabled'] ) );
        $reaction_value         = sanitize_text_field( wp_unslash( $_POST['selected_value'] ) );
        if ( empty( $reaction_title ) ) {
            $reaction_title = 'What do you feel about this post?';
        }
        if ( get_option('reactify_reaction_title' ) !== false ) {
            update_option( 'reactify_reaction_title', $reaction_title );
        } else {
            add_option( 'reactify_reaction_title', $reaction_title );
        }
        if ( get_option( 'reactify_reaction_title_enable') !== false ) {
            update_option( 'reactify_reaction_title_enable', $reaction_title_enabled );
        } else {
            add_option( 'reactify_reaction_title_enable', $reaction_title_enabled );
        }
        if ( get_option( 'reactify_selected_reaction_type') !== false ) {
            update_option( 'reactify_selected_reaction_type', $reaction_value );
        } else {
            add_option( 'reactify_selected_reaction_type', $reaction_value );
        }
        wp_send_json_success();
    } else {
        wp_send_json_error();
    }
}
add_action( 'wp_ajax_reactify_save_reaction_title', 'reactify_save_reaction_title_callback' );
add_action( 'wp_ajax_nopriv_reactify_save_reaction_title', 'reactify_save_reaction_title_callback' );


function reactify_update_emojis_callback() {

    check_ajax_referer( 'reactify-nonce', 'security' );
    
    if ( !isset( $_POST['emojis'] ) || !is_array( $_POST['emojis'] ) ) {
        wp_send_json_error( ['message' => 'Invalid data'] );
    }

    $updated_emojis = array_map( 'sanitize_text_field', $_POST['emojis'] );

    // Save the updated emojis array (you could save this in the database)
    update_option( 'reactify_custom_emojis', $updated_emojis );

    wp_send_json_success( ['emojis' => $updated_emojis] );
}

add_action( 'wp_ajax_reactify_update_emojis', 'reactify_update_emojis_callback' );
add_action( 'wp_ajax_nopriv_reactify_update_emojis', 'reactify_update_emojis_callback' );
