<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

class SetupController extends Controller
{
    public function showInstallForm()
    {
        return view('install'); // We will create a Blade view for the form
    }

    public function processInstall(Request $request)
    {
        $request->validate([
            'db_host' => 'required',
            'db_name' => 'required',
            'db_user' => 'required',
            'db_password' => 'nullable',
        ]);

        // 1. Write to .env
        $this->updateEnv([
            'DB_HOST' => $request->db_host,
            'DB_DATABASE' => $request->db_name,
            'DB_USERNAME' => $request->db_user,
            'DB_PASSWORD' => $request->db_password,
        ]);

        // 2. Clear cache to make sure new env is loaded (might tricky in same request)
        Artisan::call('config:clear');

        try {
            // 3. Run Migrations
            // Force is needed if in production
            Artisan::call('migrate', ['--force' => true]);
            
            // 4. Seed (Optional)
            // Artisan::call('db:seed', ['--force' => true]);
            
            return response()->json(['message' => 'Installation successful!']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Migration failed: ' . $e->getMessage()], 500);
        }
    }

    protected function updateEnv($data)
    {
        $path = base_path('.env');
        if (File::exists($path)) {
            $content = File::get($path);
            foreach ($data as $key => $value) {
                $value = '"' . trim($value) . '"'; 
                $content = preg_replace("/^{$key}=.*/m", "{$key}={$value}", $content);
            }
            File::put($path, $content);
        }
    }
}
