<?php
/**
 * VmpFence Country Block Logs Sync Module
 *
 * Syncs records from wp_vmpfence_country_block_logs to the backend
 * via POST /api/v1/firewall/country-blocks/batch (payload key: 'blocks')
 *
 * @package    VMPFence
 * @subpackage Includes\Sync
 * @since      2.2.4
 */

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

class VmpFence_Country_Block_Sync extends VmpFence_Base_Sync {

    /**
     * Records per API call
     * @var int
     */
    protected $batch_size = 100;

    /**
     * Constructor
     *
     * @since 2.2.4
     */
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'vmpfence_country_block_logs';
        parent::__construct();
    }

    /**
     * Get the API client method name for this sync module.
     *
     * @since 2.2.4
     * @return string
     */
    protected function get_endpoint_method(): string {
        return 'sync_country_blocks_batch';
    }

    /**
     * Transform a database row into the API payload format.
     *
     * DB Audit (Feb 16, 2026):
     * - `country_name` is NOT NULL on server — MUST be sent
     * - `block_reason` replaces old `action` field name
     * - `request_url` replaces old `request_uri` field name
     *
     * Column Audit (Feb 15, 2026 — Bugfix):
     * - DB column is `ip` (not `ip_address`)
     * - DB column is `block_type` (not `action`)
     * - DB column is `blocked_at` (not `created_at`) — already datetime
     * - DB column is `request_uri` — maps to server's `request_url`
     * - No `request_method` column exists in table — removed
     * - `user_agent` column exists — now included
     *
     * @since 2.2.4
     * @param array $row Database row
     * @return array Transformed record
     */
    protected function transform_record(array $row): array {
        return array(
            'plugin_event_id' => (int) $row['id'],
            'ip_address'      => $row['ip'] ?? '',
            'country_code'    => $row['country_code'] ?? '',
            'country_name'    => $row['country_name'] ?? '',
            'block_reason'    => $row['block_type'] ?? 'country_rule',
            'request_url'     => $row['request_uri'] ?? '',
            'blocked_at'      => $row['blocked_at'] ?? current_time('c'),
        );
    }
}
