<?php

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

$db_host = "localhost";
$db_name = "xeznqcyz_swiftotp";
$db_user = "xeznqcyz_swiftotp";
$db_pass = "xeznqcyz_swiftotp";

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

$backup_dir = __DIR__ . "/db_backups";

/* ================= CREATE FOLDER ================= */

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

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

$date = date("Y-m-d_H-i");
$backup_file = $backup_dir . "/backup_{$date}.sql";

/* ================= CREATE BACKUP ================= */

$command = "mysqldump -h {$db_host} -u {$db_user} -p{$db_pass} {$db_name} > {$backup_file} 2>&1";
exec($command, $output, $result);

if ($result !== 0) {
    echo "❌ Backup failed\n";
    exit;
}

echo "✅ Backup created\n";

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

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

$post_fields = [
    'chat_id' => $chat_id,
    'caption' => "📦 Database Backup\n🗓 {$date}",
    'document' => new CURLFile(realpath($backup_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 . "/*.sql");

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