<?php

namespace auctionforge\ajax;

use stdClass;
use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\abs\ImageModel;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\Lot;
use auctionforge\inc\model\LotImage;
use WP_Post;

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

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

        $limit = 5;
        $items = Lot::getLots($limit, intval($data['count']));
        $total = Lot::countLots();

        $limitWords = apply_filters('auctionforge_lot_title_words', 8);
        if (!empty($items)) {
            $lots = array();
            /** @var WP_Post $item */
            foreach ($items as $item) {
                $lot = new stdClass();
                $lotHelper = new LotHelper($item->ID);
                $lot->post_title = $item->post_title;
                $lot->guid = get_permalink($item->ID);
                $lot->post_content = htmlspecialchars_decode(wp_trim_words($item->post_content, $limitWords, '...'));

                $lot->featureImage = $lotHelper->getFeatureImage();

                $lot->start_price = $lotHelper->getOptionValue('lot_start_price', 0);
                $lot->itemIndex = $lotHelper->getOptionValue('lot_itemIndex', 0);

                $lots[] = $lot;
            }
            $response = array(
                'lots' => $lots,
                'total' => $total
            );
            wp_send_json_success($response);
        } else {
            wp_send_json_error(array(
                'lots' => array()
            ));
        }
    }
}
$gate = new LotListAjax();
$gate->init('do_lot_list');
