@extends('install.layout')

@section('title', 'Database Setup')

@section('content')
<div class="text-center mb-6">
    <h2 class="text-2xl font-bold text-gray-800">Database Setup</h2>
    <p class="text-gray-600 mt-2">Choose how to set up the database</p>
</div>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
    <!-- Option 1: Automatic -->
    <div class="bg-white border-2 border-purple-200 rounded-xl p-6 hover:border-purple-500 transition">
        <div class="text-center mb-4">
            <div class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-3">
                <i class="fas fa-magic text-2xl text-purple-600"></i>
            </div>
            <h3 class="text-lg font-semibold">Automatic Setup</h3>
            <p class="text-sm text-gray-500 mt-1">Run migrations through the browser</p>
        </div>
        
        <div id="auto-setup-area">
            <div id="progress-container" class="mb-4 hidden">
                <div class="h-3 bg-gray-200 rounded-full overflow-hidden">
                    <div id="progress-bar" class="h-full bg-purple-600 transition-all duration-500" style="width: 0%"></div>
                </div>
                <p id="progress-text" class="text-center text-xs text-gray-600 mt-2">Ready</p>
            </div>
            
            <div id="status-container" class="space-y-1 mb-4 max-h-40 overflow-y-auto text-sm"></div>
            
            <button id="start-btn" onclick="startMigrations()" class="w-full bg-purple-600 text-white py-2 rounded-lg font-semibold hover:bg-purple-700 transition">
                Start Automatic Setup
            </button>
            
            <a href="{{ route('install.admin') }}" id="next-btn" class="hidden w-full bg-green-600 text-white py-2 rounded-lg font-semibold text-center block">
                Continue <i class="fas fa-arrow-right ml-1"></i>
            </a>
        </div>
    </div>

    <!-- Option 2: Manual -->
    <div class="bg-white border-2 border-gray-200 rounded-xl p-6">
        <div class="text-center mb-4">
            <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                <i class="fas fa-terminal text-2xl text-gray-600"></i>
            </div>
            <h3 class="text-lg font-semibold">Manual Setup</h3>
            <p class="text-sm text-gray-500 mt-1">Run migrations via command line</p>
        </div>
        
        <div class="bg-gray-900 rounded-lg p-4 mb-4">
            <code class="text-green-400 text-sm">
                php artisan migrate --force
            </code>
        </div>
        
        <p class="text-sm text-gray-600 mb-4">Run this command in your terminal, then click continue.</p>
        
        <a href="{{ route('install.admin') }}" class="w-full bg-gray-600 text-white py-2 rounded-lg font-semibold text-center block hover:bg-gray-700 transition">
            I've Run Migrations
        </a>
    </div>
</div>

@push('scripts')
<script>
const migrations = [
    '0001_01_01_000000_create_users_table',
    '0001_01_01_000001_create_cache_table', 
    '0001_01_01_000002_create_jobs_table',
    '2026_04_23_104407_create_permission_tables',
    '2026_04_23_104909_add_extra_fields_to_users_table',
    '2026_04_23_200000_create_vendors_table',
    '2026_04_23_200001_create_categories_table',
    '2026_04_23_200002_create_brands_table',
    '2026_04_23_200003_create_car_tables',
    '2026_04_23_200004_create_products_table',
    '2026_04_23_200005_create_orders_table',
    '2026_04_23_200006_create_reviews_carts_wishlists_table',
    '2026_04_24_100000_create_conversations_currencies_tables',
    '2026_04_25_180000_add_symbol_position_to_currencies',
    '2026_04_25_190000_create_shipment_tracking_and_review_updates',
    '2026_04_25_210000_add_social_auth_to_users',
    '2026_04_25_220000_add_deleted_at_to_users',
    '2026_04_25_230000_create_settings_table',
    '2026_04_25_240000_add_user_id_to_login_attempts',
    '2026_04_25_250000_change_token_columns_to_text',
    '2026_04_25_260000_add_onboarding_fields_to_vendors',
    '2026_04_26_010000_add_approval_status_to_products',
    '2026_04_26_020000_add_coupons_announcements_vendor_settings',
    '2026_05_02_100000_add_paid_at_to_orders_table',
    '2026_05_02_110000_add_locale_to_users_table',
];

let currentIndex = 0;
const csrfToken = '{{ csrf_token() }}';

function addStatus(message, type) {
    const container = document.getElementById('status-container');
    const div = document.createElement('div');
    div.className = 'flex items-center text-xs ' + (type === 'success' ? 'text-green-600' : type === 'error' ? 'text-red-600' : 'text-gray-600');
    div.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check' : type === 'error' ? 'fa-times' : 'fa-circle'} mr-2"></i>
        ${message}
    `;
    container.appendChild(div);
    container.scrollTop = container.scrollHeight;
}

async function runSingleMigration(migration) {
    console.log('Running migration:', migration);
    try {
        const response = await fetch('{{ route("install.migrations.run") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
            },
            body: JSON.stringify({ migration: migration }),
        });
        
        console.log('Response status:', response.status);
        
        if (!response.ok) {
            const text = await response.text();
            console.error('Response error:', text);
            throw new Error('HTTP ' + response.status + ': ' + text.substring(0, 100));
        }
        
        const data = await response.json();
        console.log('Response data:', data);
        return data;
    } catch (error) {
        console.error('Fetch error:', error);
        return { success: false, message: error.message };
    }
}

async function startMigrations() {
    document.getElementById('start-btn').classList.add('hidden');
    document.getElementById('progress-container').classList.remove('hidden');
    
    for (let i = 0; i < migrations.length; i++) {
        currentIndex = i;
        const percent = Math.round((i / migrations.length) * 100);
        document.getElementById('progress-bar').style.width = percent + '%';
        document.getElementById('progress-text').textContent = `Migration ${i + 1} of ${migrations.length}`;
        
        const result = await runSingleMigration(migrations[i]);
        
        if (result.success) {
            addStatus(result.message, 'success');
        } else {
            addStatus('Failed: ' + result.message, 'error');
            document.getElementById('start-btn').classList.remove('hidden');
            document.getElementById('start-btn').textContent = 'Retry';
            return;
        }
        
        await new Promise(r => setTimeout(r, 200));
    }
    
    document.getElementById('progress-bar').style.width = '100%';
    document.getElementById('progress-text').textContent = 'Complete!';
    addStatus('All migrations completed successfully!', 'success');
    document.getElementById('next-btn').classList.remove('hidden');
}
</script>
@endpush
@endsection
