<?php
// core/CLI/Commands/MakeControllerCommand.php

namespace Core\CLI\Commands;

use Core\CLI\Command;

class MakeControllerCommand implements Command
{
    public function getName(): string
    {
        return 'make:controller';
    }

    public function getDescription(): string
    {
        return 'Creates a new controller file (supports subdirectories with /). Automatically appends "Controller".';
    }

    public function execute(array $args): int
    {
        $controllerName = $args[0] ?? null;

        if (!$controllerName) {
            echo "Error: Please provide a controller name. Usage: make:controller MyController OR Acquisition/Estate\n";
            return 1;
        }

        // Normalize slashes
        $controllerName = str_replace('\\', '/', $controllerName);

        // Split into parts
        $parts = explode('/', $controllerName);
        $className = array_pop($parts); // e.g. Estate or EstateController

        // Ensure it ends with Controller
        if (substr($className, -10) !== 'Controller') {
            $className .= 'Controller';
        }

        $subNamespace = implode('\\', $parts); // e.g. Acquisition
        $subDirectory = implode(DIRECTORY_SEPARATOR, $parts); // e.g. Acquisition

        // Final namespace
        $namespace = 'App\\Controllers' . ($subNamespace ? '\\' . $subNamespace : '');

        // File path
        $directory = FS_APP_PATH . DIRECTORY_SEPARATOR . 'Controllers' .
                     ($subDirectory ? DIRECTORY_SEPARATOR . $subDirectory : '');
        $filePath = $directory . DIRECTORY_SEPARATOR . $className . '.php';

        // Ensure directory exists
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true);
        }

        if (file_exists($filePath)) {
            echo "Error: Controller '{$className}' already exists at '{$filePath}'.\n";
            return 1;
        }

        $content = <<<PHP
<?php

namespace {$namespace};

use Core\\View;

class {$className}
{
    public function index()
    {
        echo "<h1>{$className}::index()</h1>";
        // View::make('welcome')->render();
    }
}
PHP;

        if (file_put_contents($filePath, $content) !== false) {
            echo "Success: Controller '{$className}' created at '{$filePath}'.\n";
            return 0;
        } else {
            echo "Error: Failed to create controller file. Check permissions for '{$directory}'.\n";
            return 1;
        }
    }
}
