<?php

namespace auctionforge\ajax;

use Exception;
use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\BidSpiritRequest;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\LotMetaData;
use WP_Post;

class ProfileLink extends AJAXHandler
{
    function callback ()
    {
        check_ajax_referer( 'bp-ajax-string', 'security' );

        $this->setAction("account/getFavorites");
        $data = $_POST;

        $this->setAction($data["action"]);
        unset($data["action"]);

        // Validate that the required bidSpirit data exists
        if (empty($data['bidSpirit']['lot_id'])) {
            wp_send_json_error(array(
                'lot' => 'not found',
                'message' => 'Missing lot identifier'
            ));
            return;
        }

        $lotId = sanitize_text_field($data['bidSpirit']['lot_id']);

        $args = array(
            'numberposts' => 1,
            'post_type' => BidspiritLots::POST_TYPE,
            'hide_empty' => 0,
            'taxonomy' => BidspiritLots::TAX_AUCTION_TYPE,
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $currentLang = pll_current_language();
            $args = array_merge($args, array(
                'lang' => $currentLang
            ));
        }

        $args = array_merge($args, array(
            LotMetaData::BP_QUERY => array(
                "bp_id" => [
                    "value" => $lotId,
                    "compare" => "="
                ],
            ),
            "suppress_filters" => false
        ));

        /** @var WP_Post $lot */
        $lot = get_posts($args);

        if (!empty($lot) && isset($lot[0])) {
            $response = array(
                'lot' => $lot[0],
                'link' => get_permalink($lot[0]->ID)
            );
            wp_send_json_success($response);
        } else {
            wp_send_json_error(array(
                'lot' => 'not found'
            ));
        }
    }
}
$gate = new ProfileLink();
$gate->init('do_link');