<?php

declare(strict_types=1);

namespace KupShop\AdminBundle\Util\Export;

use KupShop\KupShopBundle\Util\Logging\SentryLogger;
use KupShop\KupShopBundle\Util\System\PathFinder;
use ZipStream\CompressionMethod;
use ZipStream\ZipStream;

class ExportDataFiles
{
    private array $logs = [];

    public function __construct(protected PathFinder $pathFinder, protected SentryLogger $sentry)
    {
    }

    private function addFilesToZip(ZipStream $zip, string $directory, string $relativePath = '')
    {
        $files = scandir($directory);

        $this->logs[] = [
            'directory' => $directory,
            'relativePath' => $relativePath,
        ];

        foreach ($files as $file) {
            if (
                $file === '.'
                || $file === '..'
            ) {
                continue;
            }

            $fullPath = $directory.DIRECTORY_SEPARATOR.$file;
            $zipPath = $relativePath.$file;

            $isDir = is_dir($fullPath);
            if (($isDir && in_array($file, ['backup', 'tmp']))
                || (!$isDir && $relativePath == '') // Soubory z rootu data složky nechceme)
            ) {
                continue;
            }

            if (is_dir($fullPath)) {
                $this->addFilesToZip($zip, $fullPath, $zipPath.'/');
            } else {
                $zip->addFileFromPath($zipPath, $fullPath);
            }
        }
    }

    public function export()
    {
        ini_set('max_execution_time', 21600); // 6 hours

        $zip = new ZipStream(
            defaultCompressionMethod: CompressionMethod::STORE,
            outputName: 'data.zip'
        );

        try {
            $this->addFilesToZip($zip, rtrim($this->pathFinder->getDataDir(), '/'));

            $zip->finish();
        } catch (\Exception $e) {
            \Sentry\captureException($e);
        }

        getLogger()->notice('Static files export', ['logs' => $this->logs]);

        exit;
    }
}
