<?php
namespace Analytics\Repositories;

use Analytics\Lib\Database;

class EventDataRepository
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function insertMany(int $snapshotId, int $projectId, array $events): void
    {
        foreach ($events as $e) {
            $this->db->insert('analytics_event_data', [
                'snapshot_id'   => $snapshotId,
                'project_id'    => $projectId,
                'category_key'  => $e['category_key'],
                'event_name'    => $e['event_name'],
                'organic_count' => (int)$e['organic_count'],
                'created_at'    => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function bySnapshot(int $snapshotId): array
    {
        return $this->db->fetchAll(
            'SELECT category_key, event_name, organic_count FROM analytics_event_data WHERE snapshot_id = ? ORDER BY category_key, organic_count DESC',
            [$snapshotId]
        );
    }

    public function deleteBySnapshot(int $snapshotId): void
    {
        $this->db->query('DELETE FROM analytics_event_data WHERE snapshot_id = ?', [$snapshotId]);
    }
}
