<?php

namespace App\Console\Commands;

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

class BackupDatabase extends Command
{
    protected $signature = 'backup:database';
    protected $description = 'Backup the MySQL database';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $database = config('database.connections.mysql.database');
        $username = config('database.connections.mysql.username');
        $password = config('database.connections.mysql.password');
        $host = config('database.connections.mysql.host');
        $backupPath = storage_path('app/db_backups/backup_' . date('Ymd_His') . '.sql');

        $excludedTables = [
            'migrations',
            'personal_access_tokens',
            'password_reset_tokens',
            'password_resets',
        ];

        $ignoreTableCommands = '';
        foreach ($excludedTables as $table) {
            $ignoreTableCommands .= " --ignore-table={$database}.{$table}";
        }

        $command = "mysqldump --user={$username} --password='{$password}' --host={$host}{$ignoreTableCommands} {$database} > {$backupPath}";

        $result = null;
        $output = null;

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

        if ($result === 0) {
            $this->info('Backup successful!');
        } else {
            $this->error('Backup failed!');
        }
    }
}

