<?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/partner.thedhms.com/';
$backupDir = '/home/itsexcna/partner.thedhms.com-backup/';

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

// Step 1 — Clear old backup
if (is_dir($backupDir)) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $backupDir,
            RecursiveDirectoryIterator::SKIP_DOTS
        ),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($iterator as $file) {
        $file->isDir() ? rmdir($file) : unlink($file);
    }
} else {
    mkdir($backupDir, 0755, true);
}

// Step 2 — Copy current live files to backup
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(
        $liveDir,
        RecursiveDirectoryIterator::SKIP_DOTS
    ),
    RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
    $filename = $item->getFilename();
    if ($filename === 'deploy.zip' || $filename === 'deploy_extract.php') {
        continue;
    }
    $target = $backupDir . $iterator->getSubPathname();
    if ($item->isDir()) {
        if (!is_dir($target)) mkdir($target, 0755, true);
    } else {
        copy($item, $target);
    }
}

// Step 3 — 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 successfully. Previous version backed up.'
    ]));
} else {
    die(json_encode([
        'status' => 'error',
        'message' => 'Failed to open zip. Live site unchanged.'
    ]));
}
?>