<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class GenerateCrudCommand extends Command
{
    protected $signature = 'generate:crud {model}';

    protected $description = 'Generate CRUD operations for a given model';

    public function handle()
    {
        $modelName = $this->argument('model');

        // Generate controller file
        Artisan::call('make:controller', [
            'name' => "{$modelName}Controller",
            '--model' => $modelName,
        ]);

        // Generate view files (create, edit, index, show)
        $this->generateViews($modelName);

        // Output success message
        $this->info("CRUD operations generated successfully for {$modelName}");
    }

    private function generateViews($modelName)
    {

        if (!file_exists(resource_path("views/components/{$modelName}"))) {
            mkdir(resource_path("views/components/{$modelName}"), 0755, true);
        }

        // Generate view files
        $viewStubPath = base_path('resources/views/components/companies');
        $views = ['create', 'edit', 'index', 'breadcrumb'];
        foreach ($views as $view) {
            $stubContent = file_get_contents("{$viewStubPath}/{$view}.blade.php");
            file_put_contents(resource_path("views/components/{$modelName}/{$view}.blade.php"), $stubContent);
        }
    }
}
