<?php

namespace App\Console\Commands;

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

class DownloadAndSendDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */

    protected $signature = 'database:download_and_send';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Download the database and send it as an email attachment';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Download the database file using your preferred method and save it to storage
        // For example, if the database backup is available via URL:
            $downloadUrl = url('/backup/ngbvd.sql');
            $contents = file_get_contents($downloadUrl);
            Storage::put('ngbvd.sql', $contents);
    
            // Send the email with the database file as an attachment
            $emailAddress = 'bbaguma650@gmail.com';
            Mail::raw('Please find the attached database backup.', function ($message) use ($emailAddress) {
                $message->to($emailAddress)
                        ->subject('Database Backup')
                        ->attach(storage_path('app/ngbvd.sql'));
            });
    
            // Delete the local database backup file after sending the email
            Storage::delete('ngbvd.sql');
    }
}
