<?php

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

class AIEO_MOI_Inbound_Log {

    const RETENTION_DAYS = 30;
    const PRUNE_HOOK     = 'aieo_moi_log_prune';

    public static function init() {
        add_action(self::PRUNE_HOOK, array(__CLASS__, 'prune'));
        if (!wp_next_scheduled(self::PRUNE_HOOK)) {
            wp_schedule_event(time() + DAY_IN_SECONDS, 'daily', self::PRUNE_HOOK);
        }
    }

    
    public static function record(array $row) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['inbound_log'];
        $payload = array(
            'vendor_id'       => isset($row['vendor_id']) ? (int) $row['vendor_id'] : null,
            'event_type'      => isset($row['event_type']) ? substr((string) $row['event_type'], 0, 40) : 'unknown',
            'remote_order_id' => isset($row['remote_order_id']) ? substr((string) $row['remote_order_id'], 0, 80) : null,
            'payload_hash'    => isset($row['payload_hash']) ? substr((string) $row['payload_hash'], 0, 64) : null,
            'status'          => isset($row['status']) ? substr((string) $row['status'], 0, 20) : 'received',
            'error_text'      => isset($row['error_text']) ? (string) $row['error_text'] : null,
            'wc_order_id'     => isset($row['wc_order_id']) ? (int) $row['wc_order_id'] : null,
            'received_at'     => current_time('mysql', true),
        );
        $ok = $wpdb->insert($tbl, $payload);
        return $ok ? (int) $wpdb->insert_id : 0;
    }

    
    public static function payload_already_processed($payload_hash) {
        if ($payload_hash === '' || $payload_hash === null) { return false; }
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['inbound_log'];
        $hit = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$tbl}
             WHERE payload_hash = %s AND status IN ('processed','accepted','rejected') LIMIT 1",
            (string) $payload_hash
        ));
        return $hit > 0;
    }

    
    public static function recent($limit = 200) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['inbound_log'];
        $limit = max(1, min(500, (int) $limit));
        $rows = $wpdb->get_results(
            "SELECT * FROM {$tbl} ORDER BY id DESC LIMIT {$limit}", ARRAY_A
        );
        return is_array($rows) ? $rows : array();
    }

    public static function prune() {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['inbound_log'];
        $cutoff = gmdate('Y-m-d H:i:s', time() - (self::RETENTION_DAYS * DAY_IN_SECONDS));
        $wpdb->query($wpdb->prepare(
            "DELETE FROM {$tbl} WHERE received_at < %s",
            $cutoff
        ));
    }
}

AIEO_MOI_Inbound_Log::init();
