<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class ExecuteReleases extends Command
{

    protected $signature = 'execute:releases {file?}';
    protected $description = 'Execute the releases that have not been executed yet';
    protected $directory = __DIR__ . '/../../../database/releases';

    public function handle()
    {
        $fileArgument = $this->argument('file');

        if ($fileArgument) {

            $filePath = $this->directory . '/' . $fileArgument;

            if (!file_exists($filePath)) {
                $this->error("No existe el archivo: $fileArgument");
                return Command::FAILURE;
            }

            $release = include $filePath;
            $release->up();

            $this->info("Ejecutado: $fileArgument");

            return Command::SUCCESS;
        }

        $releases = $this->includeFiles($this->directory);

        foreach ($releases as $release) {
            $release->up();
        }
        return Command::SUCCESS;
    }

    private function includeFiles($directory)
    {
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

        $release = [];
        foreach ($iterator as $file) {
            if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
                $release[] = include $file->getPathname();
            }
        }
        return $release;
    }
}
