<?php

namespace EstatebudConnect\Controllers;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Core\Log;
use EstatebudConnect\Core\Strings;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Services\Estatebud;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Utilities\Helper;

class Favorites
{
    use Singleton;

    public function __construct()
    {
        add_action('wp_ajax_estatebud_add_favorites', [$this, 'handle_add_favorites']);
        add_action('wp_ajax_nopriv_estatebud_add_favorites', [$this, 'handle_add_favorites']);
        add_action('wp_ajax_estatebud_remove_favorite', [$this, 'handle_remove_favorite']);
        add_action('wp_ajax_nopriv_estatebud_remove_favorite', [$this, 'handle_remove_favorite']);
    }
    
    public function handle_add_favorites()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(['message' => 'Invalid nonce'], 400);
            return;
        }

        $listing_id = sanitize_text_field(wp_unslash($_POST['listing_id'] ?? ''));
        $listing_type = sanitize_text_field(wp_unslash($_POST['listing_type'] ?? 'property'));

        $user_session = Helper::get_user_session();

        $favorites = $user_session['favorites'] ?? [];

        $favorites_filtered = $favorites[$listing_type] ?? [];
        $favorites_filtered[] = $listing_id;

        $favorites[$listing_type] = $favorites_filtered;

        Log::event("Favorites: Adding {$listing_type} {$listing_id} to session", $favorites);

        Helper::set_user_session_data([
            'favorites' => $favorites,
        ]);

        if (in_array($listing_id, $favorites_filtered)) {
            wp_send_json_success(
                [
                    'message' => 'Favorites updated',
                    'code' => 200,
                    'favorites' => $favorites,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to update favorites',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_remove_favorite()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(['message' => 'Invalid nonce'], 400);
            return;
        }

        $listing_id = sanitize_text_field(wp_unslash($_POST['listing_id'] ?? ''));
        $listing_type = sanitize_text_field(wp_unslash($_POST['listing_type'] ?? 'property'));

        $user_session = Helper::get_user_session();

        $favorites = $user_session['favorites'] ?? [];

        $favorites_filtered = $favorites[$listing_type] ?? [];
        $favorites_filtered = array_values(array_diff($favorites_filtered, [$listing_id]));

        $favorites[$listing_type] = $favorites_filtered;

        Log::event("Favorites: Removing {$listing_type} {$listing_id} from session", $favorites);

        Helper::set_user_session_data([
            'favorites' => $favorites,
        ]);

        if (!in_array($listing_id, $favorites[$listing_type])) {
            wp_send_json_success(
                [
                    'message' => 'Favorite removed',
                    'code' => 200,
                    'favorites' => $favorites,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to remove favorite',
                    'code' => 400,
                ],
                400,
            );
        }
    }
}
