<?php

require_once __DIR__ . '/includes/config.php';

if (!class_exists('ZipArchive')) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'The PHP Zip extension is required to build this download.';
    exit;
}

$temporaryFile = tempnam(sys_get_temp_dir(), 'dispelled-ca-');
if ($temporaryFile === false) {
    http_response_code(500);
    exit('Could not create the package.');
}

$zip = new ZipArchive();
if ($zip->open($temporaryFile, ZipArchive::OVERWRITE) !== true) {
    @unlink($temporaryFile);
    http_response_code(500);
    exit('Could not create the package.');
}

$root = realpath(__DIR__);
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($iterator as $file) {
    if (!$file->isFile()) continue;
    $absolute = $file->getPathname();
    $relative = str_replace(DIRECTORY_SEPARATOR, '/', substr($absolute, strlen($root) + 1));
    if (str_starts_with($relative, 'cache/')) continue;

    if ($relative === 'includes/config.php') {
        $zip->addFromString('dispelled-ca/' . $relative, <<<'PHP'
<?php
define('BASE_PATH', '');
define('CACHE_DIR', __DIR__ . '/../cache');
define('CACHE_TTL_FEED', 300);
define('CACHE_TTL_WEATHER', 300);
PHP);
    } else {
        $zip->addFile($absolute, 'dispelled-ca/' . $relative);
    }
}

$zip->addEmptyDir('dispelled-ca/cache');
$zip->addFromString('dispelled-ca/cache/.htaccess', "Require all denied\n");
$zip->addFromString('dispelled-ca/.htaccess', <<<'HTACCESS'
Options -Indexes
DirectoryIndex index.php

<FilesMatch "\.(json|log|md|sh|gitkeep)$">
    Require all denied
</FilesMatch>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^\.]+)/?$ $1.php [NC,L]
</IfModule>
HTACCESS);
$zip->addFromString('dispelled-ca/README.md', <<<'README'
# dispelled.ca — PHP Edition

Plain PHP 8 with no Node.js runtime or JavaScript build step.

## Namecheap Stellar deployment

1. Upload this package's contents to `public_html/`.
2. Select PHP 8.0 or newer in cPanel.
3. Confirm `allow_url_fopen` and the PHP Zip extension are enabled.
4. Make the `cache/` directory writable by PHP (normally permissions `755`).
5. Enable HTTPS for the domain.

The weather, RSS, Reddit, and GitHub requests run directly through PHP and use
the writable cache directory to reduce provider traffic.
README);
$zip->close();

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="dispelled-ca.zip"');
header('Content-Length: ' . filesize($temporaryFile));
header('Cache-Control: no-store');
readfile($temporaryFile);
@unlink($temporaryFile);
exit;