<?php

namespace App\Service\System;

use ZipArchive;

class ZipArchiver
{
    public function createArchive(string $zipPath, string $sqlDumpPath, array $directories): void
    {
        $zip = new ZipArchive();

        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
            // Ajout SQL
            if (file_exists($sqlDumpPath)) {
                $zip->addFile($sqlDumpPath, 'database.sql');
            }

            // Ajout Dossiers
            foreach ($directories as $name => $path) {
                if (is_dir($path)) {
                    $this->addFolderToZip($path, $zip, $name);
                }
            }
            
            $zip->close();
        } else {
            throw new \Exception("Impossible d'initialiser le fichier ZIP.");
        }
    }
    
    private function addFolderToZip(string $folderPath, ZipArchive $zip, string $zipSubFolder): void
    {
        $files = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($files as $file) {
            if ($file->isDir()) {
                continue;
            }

            $filePath = $file->getRealPath();
            $fileName = $file->getFilename();

            if ($fileName === '.gitignore') {
                continue;
            }

            if ($filePath) {
                $relativeInZip = $zipSubFolder . '/' . str_replace('\\', '/', substr($filePath, strlen($folderPath) + 1));
                $zip->addFile($filePath, $relativeInZip);
            }
        }
    }
}
