@extends('install.layout')

@section('content')
    <h1>Database Configuration</h1>
    <p>Step 2: Enter database credentials. Installer will save `.env` and run migrations.</p>

    <form method="post" action="{{ route('install.database.store') }}">
        @csrf
        <div class="row">
            <div>
                <label for="db_host">DB Host</label>
                <input id="db_host" name="db_host" value="{{ old('db_host', $defaults['db_host']) }}" required>
            </div>
            <div>
                <label for="db_port">DB Port</label>
                <input id="db_port" name="db_port" value="{{ old('db_port', $defaults['db_port']) }}" required>
            </div>
        </div>

        <div class="row">
            <div>
                <label for="db_database">Database Name</label>
                <input id="db_database" name="db_database" value="{{ old('db_database', $defaults['db_database']) }}" required>
            </div>
            <div>
                <label for="db_username">Database User</label>
                <input id="db_username" name="db_username" value="{{ old('db_username', $defaults['db_username']) }}" required>
            </div>
        </div>

        <label for="db_password">Database Password</label>
        <input id="db_password" name="db_password" type="password" value="{{ old('db_password', $defaults['db_password']) }}">

        <div id="db-test" class="alert" style="display:none;"></div>

        <div class="actions">
            <button type="button" id="db-test-btn" class="btn btn-outline">Test Connection</button>
            <button type="submit" class="btn btn-primary">Save & Run Migrations</button>
            <a href="{{ route('install.requirements') }}" class="btn btn-outline">Back</a>
        </div>
    </form>

    <script>
        (function () {
            const button = document.getElementById('db-test-btn');
            const alertBox = document.getElementById('db-test');
            if (!button || !alertBox) {
                return;
            }

            const form = button.closest('form');
            const originalText = button.textContent;

            const showMessage = (message, ok) => {
                alertBox.style.display = 'block';
                alertBox.className = ok ? 'alert alert-success' : 'alert alert-danger';
                alertBox.textContent = message;
            };

            button.addEventListener('click', async () => {
                button.disabled = true;
                button.textContent = 'Testing...';

                try {
                    const formData = new FormData(form);
                    const response = await fetch("{{ route('install.database.test') }}", {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json'
                        },
                        body: formData
                    });

                    const data = await response.json().catch(() => ({}));
                    if (response.ok && data.ok) {
                        showMessage(data.message || 'Database connection successful.', true);
                    } else {
                        showMessage(data.message || 'Database connection failed.', false);
                    }
                } catch (error) {
                    showMessage('Database connection failed: ' + error.message, false);
                } finally {
                    button.disabled = false;
                    button.textContent = originalText;
                }
            });
        })();
    </script>
@endsection
