<?php
require_once __DIR__ . '/../Core.php';

class EventWebhookLog extends Model
{
    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO event_webhook_logs (provider, event_type, message_id, campaign_id, external_id, signature_status, replay_status, payload_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['provider'] ?? 'unknown')),
            trim((string)($data['event_type'] ?? 'other')),
            (int)($data['message_id'] ?? 0) ?: null,
            (int)($data['campaign_id'] ?? 0) ?: null,
            trim((string)($data['external_id'] ?? '')) ?: null,
            trim((string)($data['signature_status'] ?? 'unknown')) ?: 'unknown',
            trim((string)($data['replay_status'] ?? 'captured')) ?: 'captured',
            json_encode($data['payload'] ?? [], JSON_UNESCAPED_SLASHES),
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function recent(int $limit = 50): array
    {
        $stmt = $this->db->prepare('SELECT * FROM event_webhook_logs ORDER BY created_at DESC, id DESC LIMIT ?');
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function summary(): array
    {
        $row = $this->db->query('SELECT COUNT(*) total_count, SUM(signature_status = "verified") verified_count, SUM(replay_status = "replayed") replayed_count, MAX(created_at) last_event_at FROM event_webhook_logs')->fetch();
        return $row ?: ['total_count' => 0, 'verified_count' => 0, 'replayed_count' => 0, 'last_event_at' => null];
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM event_webhook_logs WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function markReplayed(int $id): void
    {
        $stmt = $this->db->prepare('UPDATE event_webhook_logs SET replay_status = "replayed" WHERE id = ?');
        $stmt->execute([$id]);
    }
}
