<?php

namespace Daylight\Core\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Carbon;

class PublishControllersCommand extends Command
{
    protected $signature = 'daylight:publish-controllers';

    protected $description = 'Genereer lege controllers die extenden van Daylight Core controllers';

    public function handle()
    {
        $files = new Filesystem;

        $stub = $files->get(__DIR__.'/../../stubs/DummyController.stub');
        $packageControllerRoot = realpath(__DIR__.'/../../src/Http/Controllers');
        $publishRoot = app_path('Http/Controllers');

        foreach ($files->allFiles($packageControllerRoot) as $file) {
            if ($file->getExtension() !== 'php') {
                continue;
            }

            // Bepaal het pad relatief aan de controller-root (niet de volledige package-root)
            $absolutePath = $file->getRealPath();
            $relativePath = str_replace($packageControllerRoot.DIRECTORY_SEPARATOR, '', $absolutePath);
            $relativeDir = dirname($relativePath);
            $className = $file->getBasename('.php');

            // Volledige use class op basis van relatieve locatie
            $baseNamespace = 'Daylight\\Core\\Http\\Controllers';
            $subNamespace = str_replace('/', '\\', $relativeDir !== '.' ? $relativeDir : '');
            $fullBaseClass = rtrim($baseNamespace.($subNamespace ? '\\'.$subNamespace : '').'\\'.$className, '\\');

            // Volledige namespace voor de nieuwe controller
            $targetNamespace = 'App\\Http\\Controllers'.($subNamespace ? '\\'.$subNamespace : '');

            // Maak outputmap aan
            $destinationDir = $publishRoot.($relativeDir !== '.' ? '/'.$relativeDir : '');
            $destinationFile = $destinationDir.'/'.$className.'.php';

            if (! $files->isDirectory($destinationDir)) {
                $files->makeDirectory($destinationDir, 0755, true);
            }

            if ($files->exists($destinationFile)) {
                $this->warn("Bestaat al: {$relativePath} — overgeslagen");

                continue;
            }

            $output = str_replace(
                ['DummyNamespace', 'DummyClass', 'DummyFullBaseClass', 'DummyShortBaseClass', 'DummyTimestamp'],
                [$targetNamespace, $className, $fullBaseClass, $className, Carbon::now()],
                $stub
            );

            $files->put($destinationFile, $output);
            $this->info("Gegenereerd: {$relativePath}");
        }

        $this->info('Alle controllers succesvol gegenereerd.');
    }
}
