@extends('installer.layout')

@section('title', 'Installer: Database Config')

@section('content')
<div class="min-h-screen flex flex-col">
    <!-- Header -->
    <header class="flex items-center justify-between border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 px-6 py-4 lg:px-10">
        <div class="flex items-center gap-3">
            <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
                <span class="material-symbols-outlined text-2xl">account_balance_wallet</span>
            </div>
            <h2 class="text-xl font-bold tracking-tight text-slate-900 dark:text-white">ProInvoice Installer</h2>
        </div>
        <div class="hidden sm:flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400">
            <span class="material-symbols-outlined text-lg">help</span>
            <span>Need help?</span>
        </div>
    </header>
    
    <!-- Main Content -->
    <main class="flex-1 flex flex-col items-center justify-center p-4 sm:p-6 lg:p-8">
        <div class="w-full max-w-2xl flex flex-col gap-6">
            <!-- Progress Stepper -->
            <div class="flex flex-col gap-2">
                <div class="flex justify-between items-end mb-2">
                    <span class="text-sm font-medium text-slate-500 dark:text-slate-400">Step {{ $step }} of {{ $totalSteps }}</span>
                    <span class="text-sm font-semibold text-primary">Database Configuration</span>
                </div>
                <div class="h-2 w-full rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden">
                    <div class="h-full bg-primary transition-all duration-500 ease-out rounded-full" style="width: {{ ($step / $totalSteps) * 100 }}%"></div>
                </div>
            </div>
            
            <!-- Card -->
            <div class="rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 shadow-sm p-6 sm:p-8 lg:p-10">
                <!-- Card Header -->
                <div class="mb-8">
                    <h1 class="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white mb-2">Database Connection</h1>
                    <p class="text-slate-500 dark:text-slate-400">Please enter your database connection details below. If you aren't sure, contact your hosting provider.</p>
                </div>
                
                <!-- Form -->
                <form id="databaseForm" class="flex flex-col gap-6">
                    @csrf
                    <!-- Row 1: Host & DB Name -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <label class="flex flex-col gap-2">
                            <span class="text-sm font-medium text-slate-700 dark:text-slate-300">Database Host</span>
                            <div class="relative">
                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 material-symbols-outlined text-[20px]">dns</span>
                                <input name="host" id="db_host" class="w-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 pl-10 pr-4 py-3 text-sm text-slate-900 dark:text-white placeholder:text-slate-400 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors" placeholder="localhost or 127.0.0.1:3306" type="text" value="127.0.0.1" required/>
                            </div>
                        </label>
                        <label class="flex flex-col gap-2">
                            <span class="text-sm font-medium text-slate-700 dark:text-slate-300">Database Name</span>
                            <div class="relative">
                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 material-symbols-outlined text-[20px]">database</span>
                                <input name="database" class="w-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 pl-10 pr-4 py-3 text-sm text-slate-900 dark:text-white placeholder:text-slate-400 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors" placeholder="proinvoice_db" type="text" required/>
                            </div>
                        </label>
                    </div>
                    
                    <!-- Row 2: User & Pass -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <label class="flex flex-col gap-2">
                            <span class="text-sm font-medium text-slate-700 dark:text-slate-300">Username</span>
                            <div class="relative">
                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 material-symbols-outlined text-[20px]">person</span>
                                <input name="username" class="w-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 pl-10 pr-4 py-3 text-sm text-slate-900 dark:text-white placeholder:text-slate-400 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors" placeholder="root" type="text" required/>
                            </div>
                        </label>
                        <label class="flex flex-col gap-2">
                            <span class="text-sm font-medium text-slate-700 dark:text-slate-300">Password</span>
                            <div class="relative group/pass">
                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 material-symbols-outlined text-[20px]">key</span>
                                <input name="password" class="w-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 pl-10 pr-10 py-3 text-sm text-slate-900 dark:text-white placeholder:text-slate-400 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors" placeholder="••••••••" type="password"/>
                            </div>
                        </label>
                    </div>
                    
                    <!-- Info Box -->
                    <div class="flex items-start gap-2 p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg border border-slate-100 dark:border-slate-800">
                        <span class="material-symbols-outlined text-slate-400 text-xl mt-0.5">info</span>
                        <div class="flex-1">
                            <p class="text-sm text-slate-600 dark:text-slate-300">
                                Most installations use <span class="font-mono text-xs bg-slate-200 dark:bg-slate-700 px-1 py-0.5 rounded">3306</span> as the default port. If you need to specify a custom port, append it to the hostname like <span class="font-mono text-xs bg-slate-200 dark:bg-slate-700 px-1 py-0.5 rounded">127.0.0.1:3307</span>.
                            </p>
                        </div>
                    </div>
                    
                    <!-- Test Connection & Status -->
                    <div class="flex items-center gap-4 py-2">
                        <button type="button" id="testConnectionBtn" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors focus:outline-none focus:ring-2 focus:ring-slate-200 dark:focus:ring-slate-700">
                            <span class="material-symbols-outlined text-[18px]">wifi_tethering</span>
                            Test Connection
                        </button>
                        <div id="connectionStatus" class="hidden flex items-center gap-2 text-sm"></div>
                    </div>
                    
                    <hr class="border-slate-100 dark:border-slate-800 my-2"/>
                    
                    <!-- Footer Actions -->
                    <div class="flex items-center justify-between pt-2">
                        <a href="{{ route('installer.step1') }}" class="inline-flex items-center gap-2 text-slate-500 hover:text-slate-800 dark:text-slate-400 dark:hover:text-white transition-colors text-sm font-medium px-2 py-2">
                            <span class="material-symbols-outlined text-[18px]">arrow_back</span>
                            Back
                        </a>
                        <button type="submit" id="saveDatabaseBtn" class="inline-flex items-center gap-2 px-6 py-3 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-all shadow-md shadow-primary/20 hover:shadow-lg hover:shadow-primary/30 active:scale-[0.98]">
                            Next Step
                            <span class="material-symbols-outlined text-[18px]">arrow_forward</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

@push('scripts')
<script>
document.getElementById('testConnectionBtn').addEventListener('click', async function() {
    const form = document.getElementById('databaseForm');
    const formData = new FormData(form);
    const statusDiv = document.getElementById('connectionStatus');
    const btn = this;
    
    // Parse host and port
    const hostInput = document.getElementById('db_host').value;
    if (hostInput.includes(':')) {
        const [host, port] = hostInput.split(':');
        formData.set('host', host);
        formData.set('port', port);
    }
    
    statusDiv.classList.remove('hidden');
    statusDiv.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span><span>Testing connection...</span>';
    btn.disabled = true;
    
    try {
        const response = await fetch('{{ route("installer.database.test") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            statusDiv.className = 'flex items-center gap-2 text-sm text-emerald-600 dark:text-emerald-400';
            statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">check_circle</span><span>Connection Successful! Database credentials are valid.</span>';
        } else {
            statusDiv.className = 'flex items-center gap-2 text-sm text-red-600 dark:text-red-400';
            statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">error</span><span>' + (data.message || 'Connection failed') + '</span>';
        }
    } catch (error) {
        statusDiv.className = 'flex items-center gap-2 text-sm text-red-600 dark:text-red-400';
        statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">error</span><span>Connection failed: ' + error.message + '</span>';
    } finally {
        btn.disabled = false;
    }
});

document.getElementById('databaseForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = this;
    const formData = new FormData(form);
    const btn = document.getElementById('saveDatabaseBtn');
    const statusDiv = document.getElementById('connectionStatus');
    
    // Parse host and port
    const hostInput = document.getElementById('db_host').value;
    if (hostInput.includes(':')) {
        const [host, port] = hostInput.split(':');
        formData.set('host', host);
        formData.set('port', port);
    }
    
    btn.disabled = true;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span> Saving & Migrating...';
    
    if (statusDiv) {
        statusDiv.classList.remove('hidden');
        statusDiv.className = 'flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400';
        statusDiv.innerHTML = '<span class="material-symbols-outlined animate-spin text-[18px]">sync</span><span>Saving configuration, running migrations, and linking public storage...</span>';
    }
    
    try {
        const response = await fetch('{{ route("installer.database.save") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            if (statusDiv) {
                statusDiv.className = 'flex items-center gap-2 text-sm text-emerald-600 dark:text-emerald-400';
                statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">check_circle</span><span>Database configured successfully! Redirecting...</span>';
            }
            setTimeout(() => {
                window.location.href = '{{ route("installer.step3") }}';
            }, 1000);
        } else {
            if (statusDiv) {
                statusDiv.className = 'flex items-center gap-2 text-sm text-red-600 dark:text-red-400';
                statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">error</span><span>' + (data.message || 'Configuration failed') + '</span>';
            } else {
                alert('Error: ' + (data.message || 'Configuration failed'));
            }
            btn.disabled = false;
            btn.innerHTML = originalText;
        }
    } catch (error) {
        if (statusDiv) {
            statusDiv.className = 'flex items-center gap-2 text-sm text-red-600 dark:text-red-400';
            statusDiv.innerHTML = '<span class="material-symbols-outlined text-[18px] fill-current">error</span><span>Error: ' + error.message + '</span>';
        } else {
            alert('Error: ' + error.message);
        }
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
});
</script>
@endpush
@endsection






