<?php
/**
 * sync-bids-wins (hourly)
 *
 * Drains a small bid-events queue maintained by hooks fired from the
 * BidSpirit importer / bid handlers. We don't try to retrofit historical
 * bids — only events captured after this version ships.
 *
 * Companion table: wp_af_bid_events (id, email, post_id, amount, currency,
 * is_winning, occurred_at, synced_at). Created on demand below.
 */

if (!defined('ABSPATH')) exit;

require_once __DIR__ . '/class-sync-base.php';

class AF_Bids_Sync extends AF_Sync_Base {

    protected $endpoint     = 'sync-bids-wins';
    protected $cron_hook    = 'auctionforge_sync_bids_wins';
    protected $cron_schedule = 'hourly';
    protected $batch_size   = 200;
    protected $health_key   = 'bids-wins';

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'af_bid_events';
    }

    /**
     * Public helper: queue a bid event. Called from importer / bid handlers.
     */
    public static function queue($email, $post_id, $amount, $currency = 'GBP', $is_winning = false, $occurred_at = null) {
        if (empty($email) || empty($post_id)) return false;

        global $wpdb;
        $table = $wpdb->prefix . 'af_bid_events';

        $email = strtolower(trim($email));
        if (!is_email($email)) return false;

        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
            self::ensure_table();
        }

        $occurred_at = $occurred_at ?: current_time('mysql', true);

        return $wpdb->insert($table, array(
            'user_email'  => $email,
            'lot_post_id' => (int) $post_id,
            'bid_amount'  => $amount !== null ? number_format((float) $amount, 2, '.', '') : null,
            'currency'    => substr((string) $currency, 0, 3),
            'is_winning'  => $is_winning ? 1 : 0,
            'occurred_at' => $occurred_at,
        ), array('%s','%d','%s','%s','%d','%s'));
    }

    public static function ensure_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table = $wpdb->prefix . 'af_bid_events';
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $sql = "CREATE TABLE IF NOT EXISTS $table (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            user_email varchar(190) NOT NULL,
            lot_post_id bigint(20) unsigned NOT NULL,
            bid_amount decimal(12,2) NULL DEFAULT NULL,
            currency varchar(3) NOT NULL DEFAULT 'GBP',
            is_winning tinyint(1) NOT NULL DEFAULT 0,
            occurred_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            synced_at datetime NULL DEFAULT NULL,
            PRIMARY KEY (id),
            KEY idx_email (user_email),
            KEY idx_lot (lot_post_id),
            KEY idx_synced (synced_at),
            KEY idx_occurred (occurred_at)
        ) $charset_collate;";
        dbDelta($sql);
    }

    protected function read_batch() {
        global $wpdb;
        if (!$this->table_exists($this->table)) {
            self::ensure_table();
            return array();
        }
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table} WHERE synced_at IS NULL ORDER BY id ASC LIMIT %d",
            $this->batch_size
        ), ARRAY_A);
    }

    protected function build_payload($rows) {
        return array('records' => $rows);
    }
}
