<?php

namespace auctionforge\ajax;

use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\InstanceDB;

/**
 * Two endpoints for syncing leadingBid values:
 * 1. bp_check_bids_freshness - checks if data is stale, returns all lot indexes if stale
 * 2. bp_update_leading_bids - receives bid data from JS and bulk-updates DB
 */
class CheckBidsFreshness extends AjaxHandler
{
    const FRESHNESS_TTL = 120; // 2 minutes

    function callback()
    {
        $data = $_POST;
        $termId = intval($data['termId'] ?? 0);

        if ($termId <= 0) {
            wp_send_json_error(array('message' => 'Invalid termId'));
            return;
        }

        $transientKey = 'bp_bids_updated_' . $termId;
        $lastUpdated = get_transient($transientKey);

        if ($lastUpdated !== false) {
            wp_send_json_success(array('stale' => false));
            return;
        }

        // Data is stale — return ALL lot indexes so JS can fetch bids for them
        $db = InstanceDB::getInstanceDB();
        $table = $db->prefix . 'bp_meta_data';
        $allLots = $db->get_results($db->prepare(
            "SELECT DISTINCT itemIndex FROM {$table} WHERE termId = %d AND lang = 'en' ORDER BY itemIndex+0 ASC",
            $termId
        ));

        $indexes = array();
        foreach ($allLots as $lot) {
            $indexes[] = $lot->itemIndex;
        }

        wp_send_json_success(array(
            'stale' => true,
            'indexes' => $indexes
        ));
    }
}

class UpdateBids extends AjaxHandler
{
    const FRESHNESS_TTL = 120; // 2 minutes

    function callback()
    {
        $data = $_POST;
        $termId = intval($data['termId'] ?? 0);

        if ($termId <= 0) {
            wp_send_json_error(array('message' => 'Invalid termId'));
            return;
        }

        $bidsJson = $data['bids'] ?? '';
        $bids = json_decode(stripslashes($bidsJson), true);

        if (empty($bids) || !is_array($bids)) {
            wp_send_json_error(array('message' => 'No bid data'));
            return;
        }

        $db = InstanceDB::getInstanceDB();
        $table = $db->prefix . 'bp_meta_data';

        // Bulk update using CASE statement
        $cases = '';
        $updateIndexes = array();
        $bidCount = 0;

        foreach ($bids as $itemIndex => $bidPrice) {
            $idx = intval($itemIndex);
            $price = intval($bidPrice);
            if ($price > 0) $bidCount++;
            $cases .= $db->prepare(" WHEN itemIndex = %s AND termId = %d THEN %d", strval($idx), $termId, $price);
            $updateIndexes[] = $db->prepare("%s", strval($idx));
        }

        if (!empty($cases) && !empty($updateIndexes)) {
            $indexList = implode(',', $updateIndexes);
            $sql = "UPDATE {$table} SET leadingBid = CASE {$cases} ELSE leadingBid END WHERE termId = %d AND itemIndex IN ({$indexList})";
            $db->query($db->prepare($sql, $termId));
        }

        // Set freshness transient
        $transientKey = 'bp_bids_updated_' . $termId;
        set_transient($transientKey, time(), self::FRESHNESS_TTL);

        wp_send_json_success(array(
            'updated' => true,
            'totalLots' => count($bids),
            'lotsWithBids' => $bidCount
        ));
    }
}

$checkFreshness = new CheckBidsFreshness();
$checkFreshness->init('bp_check_bids_freshness');

$updateBids = new UpdateBids();
$updateBids->init('bp_update_leading_bids');
