<?php
$secret = getenv('DEPLOY_SECRET') ?: 'itsa-deploy-2026';
$token = $_GET['token'] ?? '';

if ($token !== $secret) {
    http_response_code(403);
    die('Forbidden');
}

$zipFile = __DIR__ . '/deploy.zip';
$liveDir = '/home/itsexcna/dev.partner.thedhms.com/';

if (!file_exists($zipFile)) {
    die(json_encode([
        'status' => 'error',
        'message' => 'deploy.zip not found'
    ]));
}

// Step 1 — Clear existing staging files (no backup needed)
if (is_dir($liveDir)) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $liveDir,
            RecursiveDirectoryIterator::SKIP_DOTS
        ),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($iterator as $item) {
        $filename = $item->getFilename();
        if ($filename === 'deploy.zip' || $filename === 'deploy_extract.php') {
            continue;
        }
        $item->isDir() ? rmdir($item) : unlink($item);
    }
}

// Step 2 — Extract new deployment into live folder
$zip = new ZipArchive;
if ($zip->open($zipFile) === TRUE) {
    $zip->extractTo($liveDir);
    $zip->close();
    unlink($zipFile);
    unlink(__FILE__);
    die(json_encode([
        'status' => 'success',
        'message' => 'Deployed to staging successfully (clean deploy).'
    ]));
} else {
    die(json_encode([
        'status' => 'error',
        'message' => 'Failed to open zip. Staging site unchanged.'
    ]));
}
?>