<?php
namespace Analytics\Repositories;

use Analytics\Lib\Database;

class PageDataRepository
{
    private Database $db;

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

    public function insertMany(int $snapshotId, int $projectId, array $pages): void
    {
        foreach ($pages as $p) {
            $this->db->insert('analytics_page_data', [
                'snapshot_id'     => $snapshotId,
                'project_id'      => $projectId,
                'url'             => $p['url'],
                'ga4_sessions'    => (int)($p['ga4_sessions']    ?? 0),
                'ga4_page_views'  => (int)($p['ga4_page_views']  ?? 0),
                'gsc_clicks'      => (int)($p['gsc_clicks']      ?? 0),
                'gsc_impressions' => (int)($p['gsc_impressions'] ?? 0),
                'gsc_ctr'         => (float)($p['gsc_ctr']       ?? 0),
                'gsc_position'    => (float)($p['gsc_position']  ?? 0),
                'created_at'      => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function bySnapshot(int $snapshotId, int $limit = 200, int $offset = 0): array
    {
        return $this->db->fetchAll(
            "SELECT url, ga4_sessions, ga4_page_views, gsc_clicks, gsc_impressions, gsc_ctr, gsc_position
             FROM analytics_page_data WHERE snapshot_id = ?
             ORDER BY ga4_sessions DESC, gsc_clicks DESC
             LIMIT {$limit} OFFSET {$offset}",
            [$snapshotId]
        );
    }

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