<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;

class BackupDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'brentwood:backup-database';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Dump the current database to a backups directory';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $directory = env('DB_BACKUPS_DIRECTORY');

        if ($directory) {
            $file_name = (Str::endsWith($directory, '/') ? $directory : $directory.'/').now()->format('Y-m-d_H-i').'-'.env('DB_DATABASE').'.bak.sql';
            $this->info('CREATING DATABASE BACKUP: '.$file_name);
            shell_exec('mysqldump --set-gtid-purged=OFF --single-transaction -u '.env('DB_USERNAME').' -p'.env('DB_PASSWORD').' -h '.env('DB_HOST').' -P '.env('DB_PORT').' '.env('DB_DATABASE').' > '.$file_name);
            $this->newLine();
            $this->info('BACKUP COMPELETE');
        }
    }
}
