<?php

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

class AIEO_Exchanger_Run_Log {

    public static function table() {
        global $wpdb;
        return $wpdb->prefix . 'aieo_dmm_exchanger_run_log';
    }

    
    public static function record($side, $job_id, $shard, $processed, $created, $updated, $skipped, array $errors = array()) {
        global $wpdb;
        $wpdb->insert(self::table(), array(
            'job_id'       => (int) $job_id,
            'side'         => substr((string) $side, 0, 10),
            'shard'        => (int) $shard,
            'started_at'   => current_time('mysql', true),
            'finished_at'  => current_time('mysql', true),
            'processed'    => (int) $processed,
            'created'      => (int) $created,
            'updated'      => (int) $updated,
            'skipped'      => (int) $skipped,
            'errors_count' => count($errors),
            'errors_json'  => empty($errors) ? null : wp_json_encode($errors),
        ));
        return (int) $wpdb->insert_id;
    }

    
    public static function recent($limit = 100, $job_id = null, $side = null) {
        global $wpdb;
        $where = array('1=1');
        $params = array();
        if ($job_id !== null) { $where[] = 'job_id = %d'; $params[] = (int) $job_id; }
        if ($side !== null && in_array($side, array('source', 'target'), true)) {
            $where[] = 'side = %s'; $params[] = $side;
        }
        $sql = 'SELECT * FROM ' . self::table()
             . ' WHERE ' . implode(' AND ', $where)
             . ' ORDER BY id DESC LIMIT %d';
        $params[] = (int) $limit;
        
        $rows = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    
    public static function prune($retention_days = 30) {
        global $wpdb;
        $cutoff = gmdate('Y-m-d H:i:s', time() - max(1, (int) $retention_days) * DAY_IN_SECONDS);
        return (int) $wpdb->query($wpdb->prepare(
            'DELETE FROM ' . self::table() . ' WHERE started_at < %s', $cutoff
        ));
    }
}
