@extends('layouts.developer')

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

@section('content')
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <!-- Page Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">Database Information</h1>
        <p class="mt-2 text-gray-600">Monitor database performance, size, and table information</p>
    </div>

    <!-- Database Overview -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <!-- Database Size -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="h-12 w-12 bg-blue-500 rounded-lg flex items-center justify-center">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7l8-4m0 0l8 4m0-4l-8 4"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Database Size</dt>
                            <dd class="text-lg font-medium text-gray-900">{{ number_format($databaseInfo['size'], 2) }} MB</dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm text-gray-500">
                    Total storage used
                </div>
            </div>
        </div>

        <!-- Total Tables -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="h-12 w-12 bg-green-500 rounded-lg flex items-center justify-center">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M9 21v-6m0 0h6m-6 6h6m-9-18h6"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Total Tables</dt>
                            <dd class="text-lg font-medium text-gray-900">{{ $databaseInfo['total_tables'] }}</dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm text-gray-500">
                    All tables in database
                </div>
            </div>
        </div>

        <!-- Connection Info -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="h-12 w-12 bg-purple-500 rounded-lg flex items-center justify-center">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14l7-7 7 7V7"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Connection</dt>
                            <dd class="text-lg font-medium text-gray-900">{{ $databaseInfo['connection']['driver'] }}</dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm text-gray-500">
                    Database driver
                </div>
            </div>
        </div>

        <!-- Performance -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="h-12 w-12 bg-yellow-500 rounded-lg flex items-center justify-center">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14l7-7 7 7V7"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Status</dt>
                            <dd class="text-lg font-medium text-gray-900">
                                @if(isset($databaseInfo['error']) && $databaseInfo['error'])
                                    <span class="text-red-600">Error</span>
                                @else
                                    <span class="text-green-600">Connected</span>
                                @endif
                            </dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm text-gray-500">
                    Connection status
                </div>
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="mt-8" x-data="databaseActions()">
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:px-6 flex flex-col md:flex-row justify-between items-start md:items-center space-y-4 md:space-y-0">
                <div>
                    <h3 class="text-lg font-medium text-gray-900">Database Actions</h3>
                    <p class="text-sm text-gray-500">Perform maintenance on main or tenant databases</p>
                </div>

                <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                        <label for="tenant_id" class="mr-2 text-sm font-medium text-gray-700">Target:</label>
                        <select id="tenant_id" x-model="selectedTenant" @change="$dispatch('tenant-changed', selectedTenant)" class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                            <option value="">Main Database</option>
                            <option value="all">All Tenant Databases</option>
                            <optgroup label="Specific Tenant">
                                @foreach($tenants as $tenant)
                                    <option value="{{ $tenant->id }}">{{ $tenant->name }} ({{ $tenant->database_name }})</option>
                                @endforeach
                            </optgroup>
                        </select>
                    </div>

                    <div x-show="loading" class="flex items-center text-sm text-blue-600">
                        <svg class="animate-spin h-5 w-5 mr-2" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    </div>
                </div>
            </div>
            <div class="border-t border-gray-200">
                <div class="px-4 py-5 sm:px-6">
                    <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
                        <button @click="performAction('{{ route('developer.database.backup') }}', 'backup')" 
                                :disabled="loading"
                                class="flex flex-col items-center justify-center p-4 bg-indigo-50 text-indigo-700 rounded-lg hover:bg-indigo-100 transition disabled:opacity-50">
                            <span class="text-2xl mb-2">💾</span>
                            <span class="text-sm font-semibold">Backup</span>
                        </button>

                        <button @click="$refs.dbUpload.click()" 
                                :disabled="loading || selectedTenant === 'all'"
                                class="flex flex-col items-center justify-center p-4 bg-amber-50 text-amber-700 rounded-lg hover:bg-amber-100 transition disabled:opacity-50 disabled:cursor-not-allowed"
                                :title="selectedTenant === 'all' ? 'Upload not available for All Tenants' : ''">
                            <span class="text-2xl mb-2">📤</span>
                            <span class="text-sm font-semibold">Upload SQL</span>
                            <input type="file" x-ref="dbUpload" class="hidden" accept=".sql" @change="uploadDatabase($event)">
                        </button>

                        <button @click="performAction('{{ route('developer.database.optimize') }}', 'optimize')" 
                                :disabled="loading"
                                class="flex flex-col items-center justify-center p-4 bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition disabled:opacity-50">
                            <span class="text-2xl mb-2">⚡</span>
                            <span class="text-sm font-semibold">Optimize</span>
                        </button>
                        
                        <button @click="performAction('{{ route('developer.database.analyze') }}', 'analyze')" 
                                :disabled="loading || selectedTenant === 'all'"
                                class="flex flex-col items-center justify-center p-4 bg-green-50 text-green-700 rounded-lg hover:bg-green-100 transition disabled:opacity-50 disabled:cursor-not-allowed"
                                :title="selectedTenant === 'all' ? 'Analyze not available for All Tenants' : ''">
                            <span class="text-2xl mb-2">🔍</span>
                            <span class="text-sm font-semibold">Analyze</span>
                        </button>
                        
                        <button @click="performAction('{{ route('developer.database.clear-cache') }}', 'clear-cache')" 
                                :disabled="loading"
                                class="flex flex-col items-center justify-center p-4 bg-yellow-50 text-yellow-700 rounded-lg hover:bg-yellow-100 transition disabled:opacity-50">
                            <span class="text-2xl mb-2">🧹</span>
                            <span class="text-sm font-semibold">Clear Cache</span>
                        </button>
                        
                        <button @click="exportSchema()" 
                                :disabled="loading || selectedTenant === 'all'"
                                class="flex flex-col items-center justify-center p-4 bg-purple-50 text-purple-700 rounded-lg hover:bg-purple-100 transition disabled:opacity-50 disabled:cursor-not-allowed"
                                :title="selectedTenant === 'all' ? 'Export not available for All Tenants' : ''">
                            <span class="text-2xl mb-2">📤</span>
                            <span class="text-sm font-semibold">Export Schema</span>
                        </button>
                    </div>

                    <!-- Result Panel -->
                    <div x-show="result" x-transition class="mt-6 p-4 rounded-lg" :class="resultClass">
                        <div class="flex justify-between items-start">
                            <div class="flex">
                                <span x-text="resultIcon" class="text-xl mr-3"></span>
                                <div>
                                    <h4 class="font-bold" x-text="resultTitle"></h4>
                                    <p class="text-sm mt-1" x-text="resultMessage"></p>
                                </div>
                            </div>
                            <button @click="result = null" class="text-gray-400 hover:text-gray-600">
                                <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        
                        <!-- Extra Data (like query analysis) -->
                        <div x-show="extraData" class="mt-4 overflow-x-auto">
                            <template x-if="extraData && extraData.active_queries">
                                <table class="min-w-full divide-y divide-gray-200 text-xs">
                                    <thead>
                                        <tr class="bg-black bg-opacity-5">
                                            <th class="px-2 py-1 text-left">DB</th>
                                            <th class="px-2 py-1 text-left">Time</th>
                                            <th class="px-2 py-1 text-left">State</th>
                                            <th class="px-2 py-1 text-left">Query</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <template x-for="q in extraData.active_queries" :key="q.ID">
                                            <tr>
                                                <td class="px-2 py-1" x-text="q.DB"></td>
                                                <td class="px-2 py-1" x-text="q.TIME"></td>
                                                <td class="px-2 py-1" x-text="q.STATE"></td>
                                                <td class="px-2 py-1 truncate max-w-xs" x-text="q.INFO"></td>
                                            </tr>
                                        </template>
                                    </tbody>
                                </table>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tables List -->
    <div class="bg-white shadow overflow-hidden sm:rounded-md" 
         x-data="tableManager()" 
         @tenant-changed.window="onTenantChanged($event.detail)">
        <div class="px-4 py-5 sm:px-6 flex justify-between items-center">
            <h3 class="text-lg font-medium text-gray-900">Table Management</h3>
            <div class="flex space-x-2">
                <button @click="loadTables()" class="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition text-sm">Refresh Tables</button>
            </div>
        </div>
        <div class="border-t border-gray-200">
            <div class="grid grid-cols-1 md:grid-cols-3 divide-x divide-gray-200 h-[600px]">
                <!-- Tables Column -->
                <div class="overflow-y-auto p-4 bg-gray-50">
                    <h4 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-3">Tables</h4>
                    <div class="space-y-1">
                        <template x-for="table in tables" :key="table.name">
                            <button @click="selectTable(table)" 
                                    :class="selectedTable?.name === table.name ? 'bg-indigo-600 text-white shadow-sm' : 'bg-white text-gray-700 hover:bg-gray-100 border-gray-200'"
                                    class="w-full text-left px-4 py-3 rounded-lg border transition flex justify-between items-center group">
                                <span class="font-medium truncate" x-text="table.name"></span>
                                <span class="text-xs opacity-60" x-text="table.rows + ' rows'"></span>
                            </button>
                        </template>
                    </div>
                </div>

                <!-- Columns Column -->
                <div class="md:col-span-2 overflow-y-auto p-4 bg-white">
                    <template x-if="!selectedTable">
                        <div class="h-full flex flex-col items-center justify-center text-gray-400">
                            <span class="text-4xl mb-4">📊</span>
                            <p>Select a table to view and manage columns</p>
                        </div>
                    </template>

                    <template x-if="selectedTable">
                        <div class="h-full flex flex-col">
                            <!-- Table Header & Tabs -->
                            <div class="flex flex-col mb-4">
                                <div class="flex justify-between items-center mb-4">
                                    <div>
                                        <h4 class="text-xl font-bold text-gray-800" x-text="selectedTable.name"></h4>
                                        <p class="text-sm text-gray-500" x-text="'Engine: ' + selectedTable.engine + ' | Collation: ' + selectedTable.collation"></p>
                                    </div>
                                    <div class="flex space-x-2">
                                        <template x-if="activeTab === 'data'">
                                            <button @click="prepareAddRow()" class="px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 transition text-sm flex items-center">
                                                <span class="mr-1">+</span> Add Row
                                            </button>
                                        </template>
                                        <button @click="activeTab === 'structure' ? loadColumns() : loadData(dataPagination.page)" class="p-1 text-gray-500 hover:text-gray-700">
                                            <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                                
                                <!-- Tabs -->
                                <div class="flex border-b border-gray-200">
                                    <button @click="setTab('structure')" 
                                            :class="activeTab === 'structure' ? 'border-indigo-500 text-indigo-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                                            class="py-2 px-4 border-b-2 font-medium text-sm transition">
                                        Structure
                                    </button>
                                    <button @click="setTab('data')" 
                                            :class="activeTab === 'data' ? 'border-indigo-500 text-indigo-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                                            class="py-2 px-4 border-b-2 font-medium text-sm transition">
                                        Data
                                    </button>
                                </div>
                            </div>

                            <!-- Tab Content: Structure -->
                            <div x-show="activeTab === 'structure'" class="overflow-y-auto">
                                <div class="overflow-x-auto">
                                    <table class="min-w-full divide-y divide-gray-200">
                                        <thead class="bg-gray-50">
                                            <tr>
                                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Field</th>
                                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nullable</th>
                                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Key</th>
                                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody class="bg-white divide-y divide-gray-200">
                                            <template x-for="column in columns" :key="column.field">
                                                <tr class="hover:bg-gray-50">
                                                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900" x-text="column.field"></td>
                                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                        <span class="px-2 py-0.5 bg-gray-100 rounded text-xs" x-text="column.type"></span>
                                                    </td>
                                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500" x-text="column.null"></td>
                                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                        <span x-show="column.key" class="px-2 py-0.5 bg-yellow-100 text-yellow-800 rounded text-xs font-bold" x-text="column.key"></span>
                                                    </td>
                                                    <td class="px-4 py-3 whitespace-nowrap text-right text-sm font-medium">
                                                        <button @click="editColumn(column)" class="text-indigo-600 hover:text-indigo-900">Edit</button>
                                                    </td>
                                                </tr>
                                            </template>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Tab Content: Data -->
                            <div x-show="activeTab === 'data'" class="flex flex-col h-full overflow-hidden">
                                <div class="overflow-auto flex-grow">
                                    <table class="min-w-full divide-y divide-gray-200">
                                        <thead class="bg-gray-50 sticky top-0 z-10">
                                            <tr>
                                                <template x-for="column in columns" :key="column.field">
                                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" x-text="column.field"></th>
                                                </template>
                                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody class="bg-white divide-y divide-gray-200">
                                            <template x-for="(row, rowIndex) in tableData" :key="rowIndex">
                                                <tr class="hover:bg-gray-50">
                                                    <template x-for="column in columns" :key="column.field">
                                                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                                            <template x-if="editingRow && editingRow[primaryKeyField] === row[primaryKeyField]">
                                                                <input type="text" x-model="editingRow[column.field]" 
                                                                       class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm p-1">
                                                            </template>
                                                            <template x-if="!editingRow || editingRow[primaryKeyField] !== row[primaryKeyField]">
                                                                <span x-text="row[column.field] === null ? 'NULL' : row[column.field]" 
                                                                      :class="row[column.field] === null ? 'text-gray-400 italic' : ''"></span>
                                                            </template>
                                                        </td>
                                                    </template>
                                                    <td class="px-4 py-3 whitespace-nowrap text-right text-sm font-medium">
                                                        <template x-if="editingRow && editingRow[primaryKeyField] === row[primaryKeyField]">
                                                            <div class="flex justify-end space-x-2">
                                                                <button @click="saveRow(row)" class="text-green-600 hover:text-green-900">Save</button>
                                                                <button @click="editingRow = null" class="text-gray-600 hover:text-gray-900">Cancel</button>
                                                            </div>
                                                        </template>
                                                        <template x-if="!editingRow || editingRow[primaryKeyField] !== row[primaryKeyField]">
                                                            <div class="flex justify-end space-x-2">
                                                                <button @click="editRow(row)" class="text-indigo-600 hover:text-indigo-900">Edit</button>
                                                                <button @click="deleteRow(row)" class="text-red-600 hover:text-red-900">Delete</button>
                                                            </div>
                                                        </template>
                                                    </td>
                                                </tr>
                                            </template>
                                        </tbody>
                                    </table>
                                </div>

                                <!-- Data Pagination -->
                                <div class="bg-gray-50 px-4 py-3 border-t border-gray-200 sm:px-6 flex items-center justify-between">
                                    <div class="text-sm text-gray-700">
                                        Showing <span class="font-medium" x-text="((dataPagination.page - 1) * dataPagination.limit) + 1"></span> 
                                        to <span class="font-medium" x-text="Math.min(dataPagination.page * dataPagination.limit, dataPagination.total)"></span> 
                                        of <span class="font-medium" x-text="dataPagination.total"></span> results
                                    </div>
                                    <div class="flex space-x-2">
                                        <button @click="loadData(dataPagination.page - 1)" 
                                                :disabled="dataPagination.page <= 1"
                                                class="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50">Prev</button>
                                        <button @click="loadData(dataPagination.page + 1)" 
                                                :disabled="dataPagination.page >= dataPagination.last_page"
                                                class="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50">Next</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Edit Column Modal -->
        <div x-show="editingColumn" class="fixed inset-0 z-50 overflow-y-auto" x-cloak>
            <div class="flex items-center justify-center min-h-screen px-4">
                <div class="fixed inset-0 bg-black opacity-50"></div>
                <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Edit Column: <span x-text="editingColumn?.field"></span></h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Column Name</label>
                            <input type="text" x-model="editForm.new_name" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Data Type</label>
                            <input type="text" x-model="editForm.type" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" x-model="editForm.is_nullable" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                            <label class="ml-2 block text-sm text-gray-900">Nullable</label>
                        </div>
                    </div>

                    <div class="mt-6 flex justify-end space-x-3">
                        <button @click="editingColumn = null" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">Cancel</button>
                        <button @click="saveColumn()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition">Save Changes</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add Row Modal -->
        <div x-show="showAddRowForm" class="fixed inset-0 z-50 overflow-y-auto" x-cloak>
            <div class="flex items-center justify-center min-h-screen px-4">
                <div class="fixed inset-0 bg-black opacity-50"></div>
                <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-2xl sm:w-full p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Add New Row to <span x-text="selectedTable?.name"></span></h3>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-h-[60vh] overflow-y-auto p-1">
                        <template x-for="column in columns" :key="column.field">
                            <div x-show="column.extra !== 'auto_increment'">
                                <label class="block text-sm font-medium text-gray-700" x-text="column.field"></label>
                                <input type="text" x-model="newRow[column.field]" 
                                       class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                       :placeholder="column.type + (column.null === 'YES' ? ' (Nullable)' : '')">
                            </div>
                        </template>
                    </div>

                    <div class="mt-6 flex justify-end space-x-3">
                        <button @click="showAddRowForm = false" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">Cancel</button>
                        <button @click="addRow()" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">Add Row</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Connection Details -->
    <div class="mt-8 bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:px-6">
            <h3 class="text-lg font-medium text-gray-900">Connection Details</h3>
        </div>
        <div class="border-t border-gray-200">
            <div class="px-4 py-5 sm:px-6">
                <dl class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-4 sm:grid-cols-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Driver</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['driver'] }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Host</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['host'] }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Port</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['port'] }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Database</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['database'] }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Charset</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['charset'] }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Collation</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ $databaseInfo['connection']['collation'] }}</dd>
                    </div>
                </dl>
                
                @if(isset($databaseInfo['error']) && $databaseInfo['error'])
                    <div class="mt-4 p-4 bg-red-50 border border-red-200 rounded-md">
                        <div class="text-sm text-red-800">
                            <strong>Error:</strong> {{ $databaseInfo['error'] }}
                        </div>
                        <div class="mt-2 text-sm text-red-600">
                            Please check your database configuration and permissions.
                        </div>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Performance Metrics -->
    <div class="mt-8 bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:px-6">
            <h3 class="text-lg font-medium text-900">Performance Metrics</h3>
        </div>
        <div class="border-t border-gray-200">
            <div class="px-4 py-5 sm:px-6">
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div class="bg-gray-50 px-4 py-3 rounded-lg">
                        <div class="text-sm font-medium text-gray-500">Query Cache Hit Rate</div>
                        <div class="mt-1 text-lg font-semibold text-gray-900">85%</div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 rounded-lg">
                        <div class="text-sm font-medium text-gray-500">Average Query Time</div>
                        <div class="mt-1 text-lg font-semibold text-gray-900">12ms</div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 rounded-lg">
                        <div class="text-sm font-medium text-gray-500">Slow Queries</div>
                        <div class="mt-1 text-lg font-semibold text-gray-900">3 / hour</div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 rounded-lg">
                        <div class="text-sm font-medium text-gray-500">Cache Size</div>
                        <div class="mt-1 text-lg font-semibold text-gray-900">256 MB</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    </div>
</div>

<script>
function databaseActions() {
    return {
        loading: false,
        selectedTenant: '',
        result: null,
        resultTitle: '',
        resultMessage: '',
        resultClass: '',
        resultIcon: '',
        extraData: null,

        async performAction(url, type) {
            if (type === 'clear-cache' && !confirm('Are you sure you want to clear the system cache?')) return;
            
            this.loading = true;
            this.result = null;
            this.extraData = null;

            try {
                const formData = new FormData();
                formData.append('tenant_id', this.selectedTenant);

                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Accept': 'application/json'
                    },
                    body: formData
                });

                if (type === 'backup' && response.ok) {
                    const blob = await response.blob();
                    const downloadUrl = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    
                    let extension = 'sql';
                    let dbName = 'main';
                    
                    if (this.selectedTenant === 'all') {
                        extension = 'zip';
                        dbName = 'all_tenants';
                    } else if (this.selectedTenant) {
                        dbName = 'tenant_' + this.selectedTenant;
                    }
                    
                    a.download = `backup-${dbName}-${new Date().toISOString().split('T')[0]}.${extension}`;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    
                    this.showSuccess('Backup Successful', 'The database backup has been downloaded.');
                } else {
                    const data = await response.json();
                    if (data.success) {
                        this.showSuccess(type.charAt(0).toUpperCase() + type.slice(1) + ' Successful', data.message);
                        if (data.active_queries || data.index_stats) {
                            this.extraData = data;
                        }
                        if ((type === 'clear-cache' || type === 'optimize') && !this.selectedTenant) {
                            setTimeout(() => location.reload(), 2000);
                        }
                    } else {
                        this.showError('Action Failed', data.message || 'An unknown error occurred');
                    }
                }
            } catch (error) {
                this.showError('Network Error', error.message);
            } finally {
                this.loading = false;
            }
        },

        async uploadDatabase(event) {
            const file = event.target.files[0];
            if (!file) return;

            if (!confirm('Are you sure you want to upload and restore this database? This will overwrite existing data!')) {
                event.target.value = '';
                return;
            }

            this.loading = true;
            this.result = null;
            this.extraData = null;

            const formData = new FormData();
            formData.append('database_file', file);
            formData.append('tenant_id', this.selectedTenant);

            try {
                const response = await fetch('{{ route('developer.database.upload') }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    this.showSuccess('Upload Successful', result.message);
                } else {
                    this.showError('Upload Failed', result.message);
                }
            } catch (error) {
                this.showError('Upload Failed', 'An error occurred during the upload process.');
            } finally {
                this.loading = false;
                event.target.value = '';
            }
        },

        async exportSchema() {
            this.loading = true;
            try {
                const formData = new FormData();
                formData.append('tenant_id', this.selectedTenant);

                const response = await fetch('{{ route('developer.database.export') }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: formData
                });
                
                if (response.ok) {
                    const text = await response.text();
                    const blob = new Blob([text], { type: 'text/plain' });
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    const dbName = this.selectedTenant ? 'tenant' : 'main';
                    a.download = `schema-${dbName}.sql`;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    this.showSuccess('Export Successful', 'Schema SQL file has been generated.');
                } else {
                    const data = await response.json();
                    this.showError('Export Failed', data.message || 'Could not generate schema export');
                }
            } catch (error) {
                this.showError('Error', error.message);
            } finally {
                this.loading = false;
            }
        },

        showSuccess(title, message) {
            this.result = 'success';
            this.resultTitle = title;
            this.resultMessage = message;
            this.resultClass = 'bg-green-50 border border-green-200 text-green-800';
            this.resultIcon = '✅';
        },

        showError(title, message) {
            this.result = 'error';
            this.resultTitle = title;
            this.resultMessage = message;
            this.resultClass = 'bg-red-50 text-red-800 border border-red-200';
            this.resultIcon = '❌';
        }
    }
}

function tableManager() {
    return {
        tables: [],
        selectedTable: null,
        primaryKeyField: 'id',
        columns: [],
        activeTab: 'structure',
        tableData: [],
        dataPagination: {
            page: 1,
            limit: 10,
            total: 0,
            last_page: 1
        },
        dataLoading: false,
        editingColumn: null,
        editForm: {
            old_name: '',
            new_name: '',
            type: '',
            is_nullable: false
        },
        // Data management state
        editingRow: null,
        newRow: {},
        showAddRowForm: false,

        init() {
            this.loadTables();
        },

        onTenantChanged(tenantId) {
            this.selectedTable = null;
            this.columns = [];
            this.tableData = [];
            this.loadTables();
        },

        async loadTables() {
            const tenantId = document.getElementById('tenant_id')?.value || '';
            try {
                const response = await fetch(`{{ route('developer.database.tables') }}?tenant_id=${tenantId}`);
                const data = await response.json();
                if (data.success) {
                    this.tables = data.tables;
                }
            } catch (error) {
                console.error('Failed to load tables', error);
            }
        },

        async selectTable(table) {
            this.selectedTable = table;
            if (this.activeTab === 'structure') {
                await this.loadColumns();
            } else {
                await this.loadData();
            }
        },

        async setTab(tab) {
            this.activeTab = tab;
            if (this.selectedTable) {
                if (tab === 'structure') {
                    await this.loadColumns();
                } else {
                    await this.loadData();
                }
            }
        },

        async loadColumns() {
            const tenantId = document.getElementById('tenant_id')?.value || '';
            try {
                const response = await fetch(`{{ route('developer.database.columns') }}?table=${this.selectedTable.name}&tenant_id=${tenantId}`);
                const data = await response.json();
                if (data.success) {
                    this.columns = data.columns;
                    const pk = this.columns.find(col => col.key === 'PRI');
                    this.primaryKeyField = pk ? pk.field : 'id';
                }
            } catch (error) {
                console.error('Failed to load columns', error);
            }
        },

        async loadData(page = 1) {
            if (!this.selectedTable) return;
            this.dataLoading = true;
            const tenantId = document.getElementById('tenant_id')?.value || '';
            try {
                const response = await fetch(`{{ route('developer.database.data') }}?table=${this.selectedTable.name}&tenant_id=${tenantId}&page=${page}&limit=${this.dataPagination.limit}`);
                const data = await response.json();
                if (data.success) {
                    this.tableData = data.data;
                    this.dataPagination.total = data.total;
                    this.dataPagination.page = data.current_page;
                    this.dataPagination.last_page = data.last_page;
                }
            } catch (error) {
                console.error('Failed to load data', error);
            } finally {
                this.dataLoading = false;
            }
        },

        editRow(row) {
            this.editingRow = JSON.parse(JSON.stringify(row));
        },

        async saveRow(row) {
            const tenantId = document.getElementById('tenant_id')?.value || '';
            const pkField = this.getPrimaryKey();
            const where = { [pkField]: row[pkField] };
            
            try {
                const response = await fetch('{{ route('developer.database.data.update') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        tenant_id: tenantId,
                        table: this.selectedTable.name,
                        where: where,
                        data: this.editingRow
                    })
                });
                const result = await response.json();
                if (result.success) {
                    this.editingRow = null;
                    await this.loadData(this.dataPagination.page);
                } else {
                    alert('Update failed: ' + result.message);
                }
            } catch (error) {
                alert('Update error: ' + error.message);
            }
        },

        async deleteRow(row) {
            if (!confirm('Are you sure you want to delete this row?')) return;
            const tenantId = document.getElementById('tenant_id')?.value || '';
            const pkField = this.getPrimaryKey();
            const where = { [pkField]: row[pkField] };
            
            try {
                const response = await fetch('{{ route('developer.database.data.delete') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        tenant_id: tenantId,
                        table: this.selectedTable.name,
                        where: where
                    })
                });
                const result = await response.json();
                if (result.success) {
                    await this.loadData(this.dataPagination.page);
                }
            } catch (error) {
                alert('Delete error: ' + error.message);
            }
        },

        getPrimaryKey() {
            const pk = this.columns.find(col => col.key === 'PRI');
            return pk ? pk.field : 'id';
        },

        prepareAddRow() {
            this.newRow = {};
            this.columns.forEach(col => {
                if (col.extra !== 'auto_increment') {
                    this.newRow[col.field] = '';
                }
            });
            this.showAddRowForm = true;
        },

        async addRow() {
            const tenantId = document.getElementById('tenant_id')?.value || '';
            try {
                const response = await fetch('{{ route('developer.database.data.add') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        tenant_id: tenantId,
                        table: this.selectedTable.name,
                        data: this.newRow
                    })
                });
                const result = await response.json();
                if (result.success) {
                    this.showAddRowForm = false;
                    await this.loadData();
                } else {
                    alert('Add failed: ' + result.message);
                }
            } catch (error) {
                alert('Add error: ' + error.message);
            }
        },

        editColumn(column) {
            this.editingColumn = column;
            this.editForm = {
                old_name: column.field,
                new_name: column.field,
                type: column.type,
                is_nullable: column.null === 'YES'
            };
        },

        async saveColumn() {
            const tenantId = document.getElementById('tenant_id')?.value || '';
            
            try {
                const response = await fetch('{{ route('developer.database.column.update') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        tenant_id: tenantId,
                        table: this.selectedTable.name,
                        ...this.editForm
                    })
                });

                const result = await response.json();
                if (result.success) {
                    this.editingColumn = null;
                    await this.selectTable(this.selectedTable);
                    alert(result.message);
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                alert('An error occurred while saving the column.');
            }
        }
    }
}
</script>
@endsection
