<?php

namespace App\Http\Controllers;

use App\Models\PaymentGateway;
use App\Models\Setting;
use App\Services\InstallerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class InstallController extends Controller
{
    public function __construct(private InstallerService $installer)
    {
    }

    public function welcome()
    {
        $requirements = $this->installer->requirements();

        return view('install.welcome', compact('requirements'));
    }

    public function testDatabase(Request $request)
    {
        $data = $request->validate([
            'driver' => 'required|string',
            'host' => 'required|string',
            'port' => 'required|string',
            'database' => 'required|string',
            'username' => 'required|string',
            'password' => 'nullable|string',
        ]);

        $this->installer->testDatabase($data);

        return response()->json(['success' => true]);
    }

    public function saveDatabase(Request $request)
    {
        $data = $request->validate([
            'driver' => 'required|string',
            'host' => 'required|string',
            'port' => 'required|string',
            'database' => 'required|string',
            'username' => 'required|string',
            'password' => 'nullable|string',
        ]);

        $this->installer->writeEnv([
            'DB_CONNECTION' => $data['driver'],
            'DB_HOST' => $data['host'],
            'DB_PORT' => $data['port'],
            'DB_DATABASE' => $data['database'],
            'DB_USERNAME' => $data['username'],
            'DB_PASSWORD' => $data['password'] ?? '',
        ]);

        return back()->with('db_saved', true);
    }

    public function migrate()
    {
        $this->installer->migrateAndSeed();

        return back()->with('migrated', true);
    }

    public function saveSettings(Request $request)
    {
        $data = $request->validate([
            'app_name' => 'required|string',
            'app_url' => 'required|url',
            'timezone' => 'required|string',
            'currency' => 'required|string|size:3',
            'mail_host' => 'nullable|string',
            'mail_username' => 'nullable|string',
        ]);

        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
        }

        return back()->with('settings_saved', true);
    }

    public function saveGateways(Request $request)
    {
        $rules = [
            'gateways' => 'required|array',
            'gateways.*.name' => 'required|string',
            'gateways.*.enabled' => 'boolean',
            'gateways.*.mode' => 'required|string',
            'gateways.*.credentials' => 'array',
        ];

        Validator::make($request->all(), $rules)->validate();

        foreach ($request->input('gateways') as $gateway) {
            PaymentGateway::updateOrCreate(
                ['name' => $gateway['name']],
                [
                    'display_name' => ucfirst($gateway['name']),
                    'mode' => $gateway['mode'],
                    'enabled' => $gateway['enabled'] ?? false,
                    'credentials' => $gateway['credentials'] ?? [],
                    'supported_currencies' => $gateway['supported_currencies'] ?? ['USD'],
                ]
            );
        }

        return back()->with('gateways_saved', true);
    }

    public function finish()
    {
        $this->installer->markInstalled();

        return redirect()->route('login')->with('status', 'Installation completed.');
    }
}
