<?php
/**
 * VmpFence Custom Patterns Sync Module
 *
 * Syncs records from wp_vmpfence_custom_patterns to the backend
 * via POST /api/v1/firewall/custom-patterns/batch (payload key: 'patterns')
 *
 * @package    VMPFence
 * @subpackage Includes\Sync
 * @since      2.2.4
 */

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

class VmpFence_Custom_Patterns_Sync extends VmpFence_Base_Sync {

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

    /**
     * Constructor
     *
     * @since 2.2.4
     */
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'vmpfence_custom_patterns';
        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_custom_patterns_batch';
    }

    /**
     * Transform a database row into the API payload format.
     *
     * DB Audit (Feb 16, 2026):
     * - Server field is `match_count`, NOT `hit_count`
     * - `pattern_name` and `match_target` are NOT NULL on server — included with defaults
     *
     * Column Audit (Feb 15, 2026 — Bugfix):
     * - DB has `pattern_value` (not `pattern`) — the actual pattern text
     * - DB has `pattern_type` = match target (hostname, user_agent, referrer, ip_range)
     * - DB has `is_regex` (0=wildcard, 1=regex) — maps to server's `pattern_type`
     * - DB has `reason` (not `description`)
     * - DB has `match_count` directly (not `hit_count`)
     * - DB has `created_at` as INT unix timestamp — convert to ISO
     * - No `pattern_name` column — derive from pattern_type
     * - No `action` column — default 'block'
     *
     * @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'],
            'pattern_name'    => ucfirst(str_replace('_', ' ', $row['pattern_type'] ?? 'custom')) . ' Rule',
            'pattern'         => $row['pattern_value'] ?? '',
            'pattern_type'    => !empty($row['is_regex']) ? 'regex' : 'wildcard',
            'match_target'    => $row['pattern_type'] ?? 'url',
            'action'          => 'block',
            'description'     => $row['reason'] ?? '',
            'match_count'     => (int) ($row['match_count'] ?? 0),
            'is_active'       => (bool) ($row['is_active'] ?? true),
            'created_at'      => isset($row['created_at']) ? gmdate('Y-m-d\TH:i:s\Z', (int) $row['created_at']) : current_time('c'),
        );
    }
}
