<?php
require_once "../config/auth.php";
require_once "../config/db.php";

// ================= CONFIG =================
$backupDir = "../backups/";

if (!file_exists($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$date = date("Y-m-d_H-i-s");

// ================= DB CREDENTIALS =================
$dbHost = "localhost";
$dbUser = "digitalv_billing_db";
$dbPass = "0c9uws0J7pWJ";
$dbName = "digitalv_billing_db";

// ================= DATABASE BACKUP =================
$dbFile = $backupDir . "database_" . $date . ".sql";

$command = sprintf(
    'mysqldump -h %s -u %s -p%s %s > %s 2>&1',
    escapeshellarg($dbHost),
    escapeshellarg($dbUser),
    escapeshellarg($dbPass),
    escapeshellarg($dbName),
    escapeshellarg($dbFile)
);

exec($command, $output, $result);

// Check backup success
if ($result !== 0 || !file_exists($dbFile) || filesize($dbFile) == 0) {
    die("Database backup failed.<br><pre>" . implode("\n", $output) . "</pre>");
}

// ================= FILE BACKUP =================
$filesZip = $backupDir . "files_" . $date . ".zip";

$rootPath = realpath("../");

$zip = new ZipArchive();

if ($zip->open($filesZip, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
    die("Unable to create file backup.");
}

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

foreach ($files as $file) {

    if ($file->isDir()) {
        continue;
    }

    $filePath = $file->getRealPath();

    // Skip backup folder
    if (strpos($filePath, DIRECTORY_SEPARATOR . 'backups' . DIRECTORY_SEPARATOR) !== false) {
        continue;
    }

    $relativePath = substr($filePath, strlen($rootPath) + 1);

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

$zip->close();

// ================= FINAL ZIP =================
$finalZip = $backupDir . "backup_" . $date . ".zip";

$zip = new ZipArchive();

if ($zip->open($finalZip, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
    die("Unable to create final backup.");
}

$zip->addFile($dbFile, basename($dbFile));
$zip->addFile($filesZip, basename($filesZip));

$zip->close();

// ================= KEEP BACKUP FILES =================
// DO NOT DELETE AUTOMATICALLY

// ================= DOWNLOAD =================
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($finalZip));
header('Content-Disposition: attachment; filename="' . basename($finalZip) . '"');

readfile($finalZip);

exit;