<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$source = __DIR__;
$destination = __DIR__ . '/site_backup.zip';

if (file_exists($destination)) {
    unlink($destination);
}

$zip = new ZipArchive();
if ($zip->open($destination, ZipArchive::CREATE) !== TRUE) {
    die("Cannot create zip file.");
}

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($iterator as $item) {
    if ($item->getFilename() === 'site_backup.zip') continue;
    $relativePath = substr($item->getPathname(), strlen($source) + 1);
    $relativePath = str_replace('\\', '/', $relativePath);
    if ($item->isDir()) {
        $zip->addEmptyDir($relativePath);
    } else {
        $zip->addFile($item->getPathname(), $relativePath);
    }
}

$zip->close();
echo "Success";
