<?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_get_favorites()
    {
        if (!isset($_GET['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $favorites_sharing_token = sanitize_text_field(wp_unslash($_GET['t'] ?? ''));

        if ($favorites_sharing_token) {
            $favorites = Helper::get_favorites_by_sharing_token($favorites_sharing_token);

            Log::event('Favorites: Return list of shared favorites', [$favorites_sharing_token, $favorites]);
        } else {
            $user_session = Helper::get_user_session();
            $favorites = $user_session['favorites'] ?? [];

            Log::event('Favorites: Return list of favorites', $user_session);
        }

        if (!count($favorites)) {
            wp_send_json_error(['message' => 'Favorites not found'], 404);
            return;
        }

        wp_send_json_success(
            [
                'message' => 'Fetched favorites',
                'code' => 200,
                'data' => $favorites,
            ],
            200,
        );
    }

    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,
                    'data' => true,
                ],
                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(['status' => 'removed']);
        } else {
            wp_send_json_error(['message' => 'Listing type not found in favorites'], 400);
        }
    }
}
