<?php namespace Tps\Birzha\Console;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class DatabaseBackUp extends Command
{
    /**
     * @var string The console command name.
     */
    protected $name = 'birzha:databasebackup';

    /**
     * @var string The console command description.
     */
    protected $description = 'Makes a DB backup every week.';

    /**
     * Execute the console command.
     * @return void
     */
    public function handle()
    {
        $filename = "backup-" . Carbon::now()->format('Y-m-d_H_i_s');
  
        $command = "mysqldump --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " | gzip > " . storage_path() . "/app/backup/" . $filename . '.sql.gz';
  
        $returnVar = NULL;
        $output  = NULL;

        $path = storage_path() . "/app/backup/";

        $days = 30;

        $files = array_diff(scandir($path), array('..', '.'));
        
        while(count($files) > $days) {
            
            $max_date = $min_date = Carbon::createFromTimestamp(Storage::lastModified('backup/' . reset($files)));
            $min_date_key = key($files);
            
            foreach ($files as $key => $file) {

                $date = Carbon::createFromTimestamp(Storage::lastModified('backup/' . $file));
                
                if($date->greaterThan($max_date)) {
                    $max_date = $date;
                }

                if($date->lessThan($min_date)) {
                    $min_date = $date;
                    $min_date_key = $key;
                }
            }

            if($min_date->diffInDays($max_date) > $days) {
            
                Storage::delete("backup/{$files[$min_date_key]}");

                unset($files[$min_date_key]);

                continue;
            }

            break;
        }
        
  
        exec($command, $output, $returnVar);
    }

    /**
     * Get the console command arguments.
     * @return array
     */
    protected function getArguments()
    {
        return [];
    }

    /**
     * Get the console command options.
     * @return array
     */
    protected function getOptions()
    {
        return [];
    }
}
