<?php
/**
 * Backup database memakai mysqldump.
 * Jalankan dari Terminal cPanel sebelum deploy besar:
 *   php scripts/backup_database.php
 *
 * Output disimpan ke storage/backups/db_YYYYmmdd_His.sql.gz jika gzip tersedia.
 */

require_once __DIR__ . '/../config/env.php';

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo 'CLI only';
    exit(1);
}

$host = env('DB_HOST', 'localhost');
$db = env('DB_NAME', '');
$user = env('DB_USER', '');
$pass = env('DB_PASS', '');

if ($db === '' || $user === '') {
    fwrite(STDERR, "DB_NAME/DB_USER belum lengkap di .env\n");
    exit(1);
}

$backupDir = __DIR__ . '/../storage/backups';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$timestamp = date('Ymd_His');
$sqlFile = $backupDir . "/db_{$timestamp}.sql";
$gzFile = $sqlFile . '.gz';

$cmd = sprintf(
    'mysqldump --single-transaction --quick --default-character-set=utf8mb4 -h %s -u %s %s %s > %s',
    escapeshellarg($host),
    escapeshellarg($user),
    $pass !== '' ? '-p' . escapeshellarg($pass) : '',
    escapeshellarg($db),
    escapeshellarg($sqlFile)
);

passthru($cmd, $code);
if ($code !== 0 || !file_exists($sqlFile) || filesize($sqlFile) === 0) {
    fwrite(STDERR, "Backup gagal. Cek akses mysqldump/credential database.\n");
    @unlink($sqlFile);
    exit(1);
}

$gzip = trim((string) shell_exec('command -v gzip'));
if ($gzip !== '') {
    passthru('gzip -f ' . escapeshellarg($sqlFile), $gzipCode);
    if ($gzipCode === 0 && file_exists($gzFile)) {
        echo "Backup database berhasil: {$gzFile}\n";
        exit(0);
    }
}

echo "Backup database berhasil: {$sqlFile}\n";
