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

class ReputationSnapshot extends Model
{
    public function recent(int $limit = 30): array
    {
        $stmt = $this->db->prepare('SELECT rs.*, u.name AS created_by_name FROM reputation_snapshots rs LEFT JOIN users u ON u.id = rs.created_by ORDER BY rs.observed_on DESC, rs.id DESC LIMIT ?');
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function latestByDomain(): array
    {
        $rows = $this->recent(200);
        $latest = [];
        foreach ($rows as $row) {
            $key = strtolower((string)($row['domain_name'] ?? 'global'));
            if (!isset($latest[$key])) {
                $latest[$key] = $row;
            }
        }
        return array_values($latest);
    }

    public function summary(): array
    {
        $rows = $this->latestByDomain();
        if (!$rows) {
            return ['domain_count' => 0, 'avg_reputation_score' => 0, 'avg_inbox_rate' => 0, 'avg_spam_rate' => 0, 'avg_complaint_rate' => 0];
        }
        $totalScore = $totalInbox = $totalSpam = $totalComplaint = 0.0;
        foreach ($rows as $row) {
            $totalScore += (float)($row['reputation_score'] ?? 0);
            $totalInbox += (float)($row['inbox_rate'] ?? 0);
            $totalSpam += (float)($row['spam_rate'] ?? 0);
            $totalComplaint += (float)($row['complaint_rate'] ?? 0);
        }
        $count = count($rows);
        return [
            'domain_count' => $count,
            'avg_reputation_score' => round($totalScore / $count, 1),
            'avg_inbox_rate' => round($totalInbox / $count, 1),
            'avg_spam_rate' => round($totalSpam / $count, 2),
            'avg_complaint_rate' => round($totalComplaint / $count, 2),
        ];
    }

    public function save(array $data): int
    {
        $domain = trim((string)($data['domain_name'] ?? '')) ?: 'global';
        $provider = trim((string)($data['provider'] ?? 'manual')) ?: 'manual';
        $source = trim((string)($data['source_name'] ?? 'Manual import')) ?: 'Manual import';
        $stmt = $this->db->prepare('INSERT INTO reputation_snapshots (provider, domain_name, source_name, inbox_rate, spam_rate, bounce_rate, complaint_rate, reputation_score, sample_size, observed_on, metadata_json, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $provider,
            $domain,
            $source,
            (float)($data['inbox_rate'] ?? 0),
            (float)($data['spam_rate'] ?? 0),
            (float)($data['bounce_rate'] ?? 0),
            (float)($data['complaint_rate'] ?? 0),
            (float)($data['reputation_score'] ?? 0),
            (int)($data['sample_size'] ?? 0),
            trim((string)($data['observed_on'] ?? date('Y-m-d'))) ?: date('Y-m-d'),
            json_encode($data['metadata_json'] ?? [], JSON_UNESCAPED_SLASHES),
            (int)(current_user()['id'] ?? 0) ?: null,
        ]);
        return (int)$this->db->lastInsertId();
    }
}
