<?php
session_start();

// Seguridad del panel
if (!isset($_SESSION['user'])) {
    die("Acceso restringido");
}

// 🔗 Conexión del panel (ajusta si tu archivo se llama distinto)
require_once("../config.php");

// 🔐 SOLO CAMBIA ESTO
$token = "AQUI_TU_TOKEN";
$chat_id = "AQUI_TU_CHAT_ID";

// Carpeta backups
$backup_dir = __DIR__ . "/backups/";
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0777, true);
}

$date = date("Y-m-d_H-i-s");
$sql_file = $backup_dir . "backup_$date.sql";
$zip_file = $backup_dir . "backup_$date.zip";

// Backup DB (usa variables del panel)
system("mysqldump -h $host -u $user -p'$pass' $dbname > $sql_file");

// Comprimir
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE);
$zip->addFile($sql_file, basename($sql_file));
$zip->close();

// Tamaño
$size = round(filesize($zip_file)/1024/1024,2);

// Enviar a Telegram
$url = "https://api.telegram.org/bot$token/sendDocument";

$post = [
    'chat_id' => $chat_id,
    'caption' => "📦 Backup del panel\n📅 $date\n📊 {$size}MB",
    'document' => new CURLFile(realpath($zip_file))
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);

// borrar .sql (deja zip)
unlink($sql_file);

// volver al panel
header("Location: backups.php?ok=1");
exit;