<?php
// CoreFlux/core/CLI/Commands/MakeViewCommand.php

namespace Core\CLI\Commands;

use Core\CLI\Command;

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

    public function getDescription(): string
    {
        return 'Creates a new view file in app/Views/.';
    }

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

        if (!$viewName) {
            echo "Error: Please provide a view name. Usage: php bin/coreflux make:view acquisition/dashboard\n";
            return 1; // Indicate error
        }

        // Normalize slashes
        $viewName = str_replace(['\\', '//'], '/', $viewName);

        // Ensure .view.php suffix
        if (!str_ends_with($viewName, '.view')) {
            $viewName .= '.view';
        }

        $filePath = APP_PATH . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $viewName . '.php';

        // Ensure directory exists
        $dir = dirname($filePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

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

        $content = $this->getViewFileContent(basename($viewName, '.view'));

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

    /**
     * Generates boilerplate content for a new view file.
     *
     * @param string $viewBaseName The base name of the view (e.g., 'dashboard').
     */
    private function getViewFileContent(string $viewBaseName): string
    {
        $title = ucwords(str_replace(['-', '_'], ' ', $viewBaseName));
        return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$title} | CoreFlux App</title>
</head>
<body>
    <h1>{$title}</h1>
    <p>This content is from <code>{$viewBaseName}.view.php</code></p>
</body>
</html>
HTML;
    }
}
