<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class GenModelController extends Controller
{
    /**
     * Generate models for all tables in the database.
     *
     * @return \Illuminate\Http\Response
     */
    public function generateModels()
    {
        // Get all table names in the database
        $tableNames = $this->getAllTableNames();

        foreach ($tableNames as $tableName) {
            // Create the model name by converting the table name to studly case
            $modelName = Str::studly(Str::singular($tableName));

            // Generate the model file content
            $modelContent = $this->generateModelContent($tableName, $modelName);

            // Define the path to save the model file
            $modelFilePath = app_path("Models/{$modelName}.php");

            // Save the model file
            file_put_contents($modelFilePath, $modelContent);

            echo "Model created for table $tableName.\n";
        }

        echo "Models generation completed.\n";
    }

    /**
     * Get all table names from the database.
     *
     * @return array
     */
    private function getAllTableNames()
    {
        $tables = [];

        // Get the database connection
        $connection = DB::connection();

        // Get the database name
        $databaseName = $connection->getDatabaseName();

        // Query to get all table names in the database
        $query = "SELECT table_name FROM information_schema.tables WHERE table_schema = '{$databaseName}'";

        // Execute the query
       
        $results = $connection->select($query);

        // Extract table names from the results
        foreach ($results as $result) {
            $tables[] = $result->table_name;
        }

        return $tables;
    }

    /**
     * Generate model content for a given table name and model name.
     *
     * @param string $tableName
     * @param string $modelName
     * @return string
     */
    private function generateModelContent($tableName, $modelName)
    {
        // Retrieve the table's column information
        $columns = Schema::getColumnListing($tableName);

        // Generate the model content
        $content = "<?php\n\n";
        $content .= "namespace App\Models;\n\n";
        $content .= "use Illuminate\Database\Eloquent\Model;\n\n";
        $content .= "class {$modelName} extends Model\n";
        $content .= "{\n";
        $content .= "    protected \$table = '{$tableName}';\n";
        $content .= "    protected \$fillable = [\n";
        
        // Generate the fillable fields
        foreach ($columns as $column) {
            $content .= "        '{$column}',\n";
        }

        $content .= "    ];\n";
        $content .= "}\n";

        return $content;
    }
}
