<?php

/* ================= CONFIG ================= */

$bot_token = "8397204636:AAGCA9Gf5ygXGMZXWseIEcFjXnchOZJcvHg";
$chat_id   = "6388548761";

/* Folder to Backup */
$source_folder = "/home/xeznqcyz/public_html"; // change if needed

$backup_dir = __DIR__ . "/site_backups";

if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

/* ================= ZIP FILE NAME ================= */

$date = date("Y-m-d_H-i");
$zip_file = $backup_dir . "/site_backup_{$date}.zip";

/* ================= CREATE ZIP ================= */

$zip = new ZipArchive();

if ($zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source_folder),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {

        if (!$file->isDir()) {

            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($source_folder) + 1);

            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();

} else {
    echo "❌ Failed to create ZIP\n";
    exit;
}

echo "✅ ZIP Created\n";

/* ================= SEND TO TELEGRAM ================= */

$telegram_url = "https://api.telegram.org/bot{$bot_token}/sendDocument";

$post_fields = [
    'chat_id' => $chat_id,
    'caption' => "📦 Public HTML Backup\n🗓 {$date}",
    'document' => new CURLFile(realpath($zip_file))
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
curl_setopt($ch, CURLOPT_URL, $telegram_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

$response = curl_exec($ch);
curl_close($ch);

echo "📤 Sent to Telegram\n";

/* ================= DELETE OLD (7 DAYS) ================= */

$files = glob($backup_dir . "/*.zip");

foreach ($files as $file) {
    if (filemtime($file) < time() - (7 * 24 * 60 * 60)) {
        unlink($file);
    }
}