<?php

namespace App\Core\Exports\Services;

use Dompdf\Dompdf;

class ExportService
{
    public function exportCsv(array $data, string $filename): string
    {
        $path = WRITEPATH . 'exports' . DIRECTORY_SEPARATOR . $filename;
        $this->ensureDirectory($path);
        $handle = fopen($path, 'wb');

        if ($data !== []) {
            fputcsv($handle, array_keys(reset($data)), ';');
            foreach ($data as $row) {
                fputcsv($handle, $row, ';');
            }
        }

        fclose($handle);

        return $path;
    }

    public function exportPdf(string $html, string $filename): string
    {
        $path = WRITEPATH . 'exports' . DIRECTORY_SEPARATOR . $filename;
        $this->ensureDirectory($path);
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->render();
        file_put_contents($path, $dompdf->output());

        return $path;
    }

    public function exportJson(array $data, string $filename): string
    {
        $path = WRITEPATH . 'exports' . DIRECTORY_SEPARATOR . $filename;
        $this->ensureDirectory($path);
        file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

        return $path;
    }

    private function ensureDirectory(string $path): void
    {
        $directory = dirname($path);
        if (! is_dir($directory)) {
            mkdir($directory, 0775, true);
        }
    }
}
