<?php
namespace Crawl\Repositories;

use Crawl\Lib\Database;

class CrawlImageRepository
{
    private Database $db;

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

    public function clearByPage(int $runId, string $pageUrl): void
    {
        $this->db->query('DELETE FROM crawl_images WHERE crawl_run_id = ? AND page_url = ?', [$runId, $pageUrl]);
    }

    public function insertMany(int $runId, string $pageUrl, array $images): void
    {
        if (empty($images)) {
            return;
        }

        foreach ($images as $img) {
            $this->db->query(
                'INSERT INTO crawl_images (crawl_run_id, page_url, image_url, alt_text, is_missing_alt, created_at)
                 VALUES (?, ?, ?, ?, ?, NOW())',
                [$runId, $pageUrl, $img['image_url'], $img['alt_text'], $img['is_missing_alt'] ? 1 : 0]
            );
        }
    }

    public function byPage(int $runId, string $url): array
    {
        return $this->db->fetchAll('SELECT * FROM crawl_images WHERE crawl_run_id = ? AND page_url = ? ORDER BY id DESC', [$runId, $url]);
    }

    public function tabData(int $runId, int $limit, int $offset): array
    {
        return $this->db->fetchAll("SELECT page_url, image_url, alt_text, is_missing_alt FROM crawl_images WHERE crawl_run_id = ? ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}", [$runId]);
    }

    public function allByRun(int $runId): array
    {
        return $this->db->fetchAll(
            'SELECT page_url, is_missing_alt FROM crawl_images WHERE crawl_run_id = ?',
            [$runId]
        );
    }
}
