<?php

namespace App\Services\Reports;

class ReportCsvWriter
{
    public function build(array $dataset, array $summary): string
    {
        $handle = fopen('php://temp', 'r+');

        $this->write($handle, ['DW Ads Reporter']);
        $this->write($handle, ['Müşteri', $dataset['client']->company_name ?? '-']);
        $this->write($handle, ['Tarih Aralığı', ($dataset['period']['from'] ?? '-') . ' / ' . ($dataset['period']['to'] ?? '-')]);
        $this->write($handle, []);

        $this->write($handle, ['Genel Özet']);
        foreach (($summary['overview'] ?? []) as $key => $value) {
            $this->write($handle, [$key, $value]);
        }
        $this->write($handle, []);

        $this->section($handle, 'Google Ads Kampanyalar', $dataset['google_ads']['campaigns'] ?? []);
        $this->section($handle, 'Google Ads Anahtar Kelimeler', $dataset['google_ads']['keywords'] ?? []);
        $this->section($handle, 'Google Ads Arama Terimleri', $dataset['google_ads']['search_terms'] ?? []);
        $this->section($handle, 'Meta Kampanyalar', $dataset['meta_ads']['campaigns'] ?? []);
        $this->section($handle, 'Meta Reklam Setleri', $dataset['meta_ads']['adsets'] ?? []);
        $this->section($handle, 'Meta Reklamlar', $dataset['meta_ads']['ads'] ?? []);
        $this->section($handle, 'Search Console Sorgular', $dataset['search_console']['queries'] ?? []);
        $this->section($handle, 'Search Console Sayfalar', $dataset['search_console']['pages'] ?? []);
        $this->section($handle, 'GA4 Kanallar', $dataset['ga4']['channels'] ?? []);

        rewind($handle);
        $content = stream_get_contents($handle) ?: '';
        fclose($handle);

        return $content;
    }

    /**
     * @param resource $handle
     * @param array<int, mixed> $row
     */
    private function write($handle, array $row): void
    {
        fputcsv($handle, $row, ';');
    }

    /**
     * @param resource $handle
     * @param array<int, array<string, mixed>> $rows
     */
    private function section($handle, string $title, array $rows): void
    {
        $this->write($handle, [$title]);

        if ($rows === []) {
            $this->write($handle, ['Kayıt bulunamadı']);
            $this->write($handle, []);
            return;
        }

        $headers = array_keys($rows[0]);
        $this->write($handle, $headers);

        foreach ($rows as $row) {
            $this->write($handle, array_values($row));
        }

        $this->write($handle, []);
    }
}
