<?php
/**
 * EdumacFlo Automated Production Packaging & Distribution Tool
 * -------------------------------------------------------------
 * Compresses the entire application into a clean, standalone ZIP package
 * ready for cPanel, VPS, WHM, or local extraction and 1-click web installation.
 *
 * Usage:
 *   php deploy/package_release.php
 */

if (php_sapi_name() !== 'cli') {
    die("This script must be run from the command line.\n");
}

echo "\n============================================================\n";
echo "  EdumacFlo Production Distribution Package Generator\n";
echo "============================================================\n\n";

if (!extension_loaded('zip')) {
    die("❌ Error: PHP 'zip' extension is required to generate the release archive.\n");
}

$rootDir = dirname(__DIR__);
$outputDir = __DIR__;
$archiveName = 'edumacflo-v2-saas-installer.zip';
$archivePath = $outputDir . '/' . $archiveName;

if (file_exists($archivePath)) {
    echo "🗑️ Removing previous build: $archiveName\n";
    @unlink($archivePath);
}

$zip = new ZipArchive();
if ($zip->open($archivePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    die("❌ Error: Could not create zip archive at: $archivePath\n");
}

// Patterns / Directories / Files to Exclude from Production Release
$excludePatterns = [
    // Version Control & Editor metadata
    '/\.git($|\/)/',
    '/\.github($|\/)/',
    '/\.idea($|\/)/',
    '/\.vscode($|\/)/',
    '/\.gitignore$/',
    
    // Scratch & Test scripts
    '/^scratch($|\/)/',
    
    // Live Secrets & Lock files (Samples MUST be preserved!)
    '/^saas_master_config\.php$/',
    '/^db_config\.php$/',
    '/^install\/installed\.lock$/',
    '/^install\.lock$/',
    
    // Cache & Tenant isolated uploads (directories preserved, contents emptied)
    '/^public\/cache\/tenants\/(.+)/',
    '/^uploads\/tenants\/(.+)/',
    
    // Existing build archives
    '/^deploy\/.*\.zip$/',
    
    // OS & Temporary files
    '/\.DS_Store$/',
    '/Thumbs\.db$/',
    '/\.log$/',
    '/\.tmp$/',
];

echo "📦 Scanning repository files...\n";

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

$filesAdded = 0;
$totalRawSize = 0;

foreach ($iterator as $item) {
    $fullPath = str_replace('\\', '/', $item->getPathname());
    $relativePath = substr($fullPath, strlen(str_replace('\\', '/', $rootDir)) + 1);

    // Check against exclusion patterns
    $excluded = false;
    foreach ($excludePatterns as $pattern) {
        if (preg_match($pattern, $relativePath)) {
            $excluded = true;
            break;
        }
    }

    if ($excluded) {
        continue;
    }

    if ($item->isDir()) {
        $zip->addEmptyDir($relativePath);
    } elseif ($item->isFile()) {
        $zip->addFile($fullPath, $relativePath);
        $filesAdded++;
        $totalRawSize += $item->getSize();
    }
}

// Ensure necessary empty directories are created in the ZIP
$ensureDirs = [
    'uploads',
    'uploads/school',
    'uploads/students',
    'uploads/staff',
    'uploads/curriculums',
    'uploads/admissions',
    'uploads/others',
    'uploads/tenants',
    'public/cache',
    'public/cache/tenants',
    'deploy',
];

foreach ($ensureDirs as $dir) {
    $zip->addEmptyDir($dir);
}

// Add clean placeholder files to ensure directory existence in git/unzip
$zip->addFromString('public/cache/tenants/.htaccess', "Options -Indexes\nOrder Deny,Allow\nDeny from all\n");
$zip->addFromString('uploads/.htaccess', "Options -Indexes\n<FilesMatch \"\.(php|php3|php4|php5|phtml|pl|py|jsp|asp|sh|cgi)$\">\nOrder Deny,Allow\nDeny from all\n</FilesMatch>\n");

$zip->close();

if (!file_exists($archivePath)) {
    die("❌ Error: Zip archive generation failed.\n");
}

$zipSize = filesize($archivePath);

echo "\n============================================================\n";
echo "  Build Completed Successfully! 🎉\n";
echo "============================================================\n";
echo sprintf("  Archive File : %s\n", $archivePath);
echo sprintf("  Total Files  : %s files packaged\n", number_format($filesAdded));
echo sprintf("  Uncompressed : %s MB\n", number_format($totalRawSize / (1024 * 1024), 2));
echo sprintf("  Package Size : %s MB\n", number_format($zipSize / (1024 * 1024), 2));
echo sprintf("  Compression  : %s%% space saved\n", number_format((1 - ($zipSize / $totalRawSize)) * 100, 1));
echo "============================================================\n";
echo "  Deploy by uploading 'edumacflo-v2-saas-installer.zip' to\n";
echo "  your server's public_html/, extract, and visit /install/.\n";
echo "============================================================\n\n";
