<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class DatabaseBackup extends Command
{
    /**
     * Nama dan deskripsi Artisan Command.
     *
     * @var string
     */
    protected $signature = 'db:backup-sql';

    protected $description = 'Backup database hanya menghasilkan file SQL';

    public function handle()
    {
        // Konfigurasi database
        $dbHost = config('database.connections.mysql.host');
        $dbPort = config('database.connections.mysql.port');
        $dbName = config('database.connections.mysql.database');
        $dbUser = config('database.connections.mysql.username');
        $dbPass = config('database.connections.mysql.password');

        // Nama file backup
        $backupFileName = 'backup-' . date('Y-m-d_H-i-s') . '.sql';
        $backupFilePath = storage_path('app/Laravel/' . $backupFileName);

        # Perintah mysqldump
        # Cpanel
        $command = sprintf(
            'mysqldump --host=%s --port=%s --user=%s --password=%s %s > %s',
            escapeshellarg($dbHost),
            escapeshellarg($dbPort),
            escapeshellarg($dbUser),
            escapeshellarg($dbPass),
            escapeshellarg($dbName),
            escapeshellarg($backupFilePath)
        );

        // Jalankan perintah
        $output = null;
        $resultCode = null;
        exec($command, $output, $resultCode);

        if ($resultCode === 0) {
            $this->info('Backup berhasil: ' . $backupFilePath);
            return Command::SUCCESS;
        } else {
            $this->error('Backup gagal.');
            return Command::FAILURE;
        }
    }
}
