<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consultation Types Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .main-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 20px;
            padding: 30px;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 10px 20px;
            font-weight: 600;
        }
        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            border: none;
            border-radius: 10px;
            padding: 8px 16px;
            font-weight: 600;
        }
        .btn-danger {
            background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
            border: none;
            border-radius: 10px;
            padding: 8px 16px;
            font-weight: 600;
        }
        .btn-warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            border: none;
            border-radius: 10px;
            padding: 8px 16px;
            font-weight: 600;
        }
        .table {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }
        .table thead th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            font-weight: 600;
            padding: 15px;
        }
        .table tbody td {
            padding: 15px;
            vertical-align: middle;
            border-color: #f8f9fa;
        }
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            font-size: 14px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px 20px 0 0;
            border: none;
        }
        .modal-body {
            padding: 30px;
        }
        .alert {
            border-radius: 15px;
            border: none;
            font-weight: 500;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .spinner-border {
            color: #667eea;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="main-container">
            <div class="header">
                <h2><i class="fas fa-calendar-check me-2"></i>Consultation Types Management</h2>
                <p class="mb-0">Manage consultation types and their pricing</p>
            </div>

            <!-- Alert Messages -->
            <div id="alertContainer"></div>

            <!-- Add New Type Button -->
            <div class="row mb-4">
                <div class="col-12">
                    <button class="btn btn-primary" onclick="showAddModal()">
                        <i class="fas fa-plus me-2"></i>Add New Consultation Type
                    </button>
                    <button class="btn btn-warning ms-2" onclick="testFunction()">
                        <i class="fas fa-bug me-2"></i>Test JavaScript
                    </button>
                </div>
            </div>

            <!-- Loading Spinner -->
            <div class="loading" id="loadingSpinner">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading consultation types...</p>
            </div>

            <!-- Consultation Types Table -->
            <div class="table-responsive" id="typesTableContainer">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type Name</th>
                            <th>Type Code</th>
                            <th>Base Price</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="typesTableBody">
                        <!-- Data will be loaded here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="typeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add Consultation Type</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="typeForm">
                        <input type="hidden" id="typeId" name="id">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="typeName" class="form-label">Type Name *</label>
                                <input type="text" class="form-control" id="typeName" name="type_name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="typeCode" class="form-label">Type Code *</label>
                                <input type="text" class="form-control" id="typeCode" name="type_code" required>
                                <div class="form-text">Use lowercase with underscores (e.g., video_call)</div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="basePrice" class="form-label">Base Price (₹) *</label>
                                <input type="number" class="form-control" id="basePrice" name="base_price" step="0.01" min="0" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="isActive" class="form-label">Status</label>
                                <select class="form-select" id="isActive" name="is_active">
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveType()">
                        <i class="fas fa-save me-2"></i>Save Type
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Confirm Delete</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this consultation type?</p>
                    <p class="text-danger"><strong>This action cannot be undone!</strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                        <i class="fas fa-trash me-2"></i>Delete
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        console.log('=== SCRIPT LOADED ===');
        console.log('JavaScript is running');
        
        let consultationTypes = [];
        let deleteTypeId = null;
        
        // Test function to check if everything is working
        function testFunction() {
            console.log('=== TEST FUNCTION CALLED ===');
            alert('JavaScript is working! Check console for debug info.');
        }
        
        // Prevent any automatic form submissions
        document.addEventListener('submit', function(e) {
            console.log('Form submission prevented:', e);
            e.preventDefault();
            return false;
        });
        
        // Prevent any automatic button clicks
        document.addEventListener('click', function(e) {
            if (e.target.type === 'submit') {
                console.log('Submit button clicked:', e.target);
                e.preventDefault();
                return false;
            }
        });

        // Load consultation types on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('=== PAGE LOADED ===');
            console.log('DOM Content Loaded event fired');
            console.log('Starting to load consultation types...');
            
            // Test if elements exist
            const loadingSpinner = document.getElementById('loadingSpinner');
            const tableContainer = document.getElementById('typesTableContainer');
            const tableBody = document.getElementById('typesTableBody');
            
            console.log('Loading spinner element:', loadingSpinner);
            console.log('Table container element:', tableContainer);
            console.log('Table body element:', tableBody);
            
            if (!loadingSpinner) {
                console.error('Loading spinner element not found!');
            }
            if (!tableContainer) {
                console.error('Table container element not found!');
            }
            if (!tableBody) {
                console.error('Table body element not found!');
            }
            
            // Add a small delay to ensure everything is loaded
            setTimeout(() => {
                console.log('Starting loadConsultationTypes after delay...');
                loadConsultationTypes();
            }, 100);
        });

        // Load consultation types from API
        async function loadConsultationTypes() {
            console.log('=== LOADING CONSULTATION TYPES ===');
            console.log('Calling showLoading(true)');
            showLoading(true);
            
            try {
                console.log('Making GET API call to: ../api/consultation_types_management.php');
                const response = await fetch('../api/consultation_types_management.php', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                console.log('Response received:', response);
                console.log('Response status:', response.status);
                console.log('Response ok:', response.ok);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const responseText = await response.text();
                console.log('Raw response text:', responseText);
                
                if (!responseText.trim()) {
                    throw new Error('Empty response from server');
                }
                
                const data = JSON.parse(responseText);
                console.log('Parsed JSON data:', data);
                
                if (data.success) {
                    consultationTypes = data.consultation_types;
                    console.log('Consultation types loaded successfully:', consultationTypes);
                    console.log('Number of types:', consultationTypes.length);
                    renderTypesTable();
                } else {
                    console.error('API returned error:', data.message);
                    showAlert('Error loading consultation types: ' + data.message, 'danger');
                }
            } catch (error) {
                console.error('=== FETCH ERROR ===');
                console.error('Error type:', error.name);
                console.error('Error message:', error.message);
                console.error('Error stack:', error.stack);
                showAlert('Error loading consultation types: ' + error.message, 'danger');
            } finally {
                console.log('Calling showLoading(false)');
                showLoading(false);
            }
        }

        // Render types table
        function renderTypesTable() {
            console.log('=== RENDERING TABLE ===');
            console.log('Consultation types to render:', consultationTypes);
            console.log('Number of types:', consultationTypes.length);
            
            const tbody = document.getElementById('typesTableBody');
            console.log('Table body element:', tbody);
            
            if (!tbody) {
                console.error('Table body element not found!');
                return;
            }
            
            console.log('Clearing table body...');
            tbody.innerHTML = '';

            if (consultationTypes.length === 0) {
                console.log('No consultation types found, showing empty message');
                tbody.innerHTML = '<tr><td colspan="7" class="text-center">No consultation types found</td></tr>';
                return;
            }
            
            console.log('Creating table rows for', consultationTypes.length, 'types');

            consultationTypes.forEach((type, index) => {
                console.log(`Creating row ${index + 1} for type:`, type);
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${type.id || '-'}</td>
                    <td><strong>${type.type_name}</strong></td>
                    <td><code>${type.type_code}</code></td>
                    <td>₹${parseFloat(type.base_price).toFixed(2)}</td>
                    <td>${type.description || '-'}</td>
                    <td>
                        <span class="badge ${type.is_active == 1 ? 'bg-success' : 'bg-danger'}">
                            ${type.is_active == 1 ? 'Active' : 'Inactive'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-warning btn-sm me-2" onclick="editType(${type.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="deleteType(${type.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;
                console.log(`Appending row ${index + 1} to table body`);
                tbody.appendChild(row);
            });
            
            console.log('Table rendering completed. Total rows:', tbody.children.length);
        }

        // Show add modal
        function showAddModal() {
            document.getElementById('modalTitle').textContent = 'Add Consultation Type';
            document.getElementById('typeForm').reset();
            document.getElementById('typeId').value = '';
            new bootstrap.Modal(document.getElementById('typeModal')).show();
        }

        // Edit type
        function editType(id) {
            const type = consultationTypes.find(t => t.id == id);
            if (!type) return;

            document.getElementById('modalTitle').textContent = 'Edit Consultation Type';
            document.getElementById('typeId').value = type.id;
            document.getElementById('typeName').value = type.type_name;
            document.getElementById('typeCode').value = type.type_code;
            document.getElementById('basePrice').value = type.base_price;
            document.getElementById('description').value = type.description || '';
            document.getElementById('isActive').value = type.is_active;
            
            new bootstrap.Modal(document.getElementById('typeModal')).show();
        }

        // Delete type
        function deleteType(id) {
            deleteTypeId = id;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // Confirm delete
        async function confirmDelete() {
            if (!deleteTypeId) return;

            try {
                const response = await fetch('../api/consultation_types_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'delete',
                        id: deleteTypeId
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showAlert('Consultation type deleted successfully!', 'success');
                    loadConsultationTypes();
                } else {
                    showAlert('Error deleting consultation type: ' + data.message, 'danger');
                }
            } catch (error) {
                showAlert('Error deleting consultation type: ' + error.message, 'danger');
            } finally {
                deleteTypeId = null;
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
            }
        }

        // Save type
        async function saveType() {
            const form = document.getElementById('typeForm');
            const formData = new FormData(form);
            
            const data = {
                action: formData.get('id') ? 'update' : 'create',
                type_name: formData.get('type_name'),
                type_code: formData.get('type_code'),
                base_price: parseFloat(formData.get('base_price')),
                description: formData.get('description'),
                is_active: parseInt(formData.get('is_active'))
            };

            if (formData.get('id')) {
                data.id = parseInt(formData.get('id'));
            }

            try {
                const response = await fetch('../api/consultation_types_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();
                
                if (result.success) {
                    showAlert('Consultation type saved successfully!', 'success');
                    loadConsultationTypes();
                    bootstrap.Modal.getInstance(document.getElementById('typeModal')).hide();
                } else {
                    showAlert('Error saving consultation type: ' + result.message, 'danger');
                }
            } catch (error) {
                showAlert('Error saving consultation type: ' + error.message, 'danger');
            }
        }

        // Show/hide loading
        function showLoading(show) {
            console.log('=== SHOW LOADING ===');
            console.log('Show loading:', show);
            
            const loadingSpinner = document.getElementById('loadingSpinner');
            const tableContainer = document.getElementById('typesTableContainer');
            
            console.log('Loading spinner element:', loadingSpinner);
            console.log('Table container element:', tableContainer);
            
            if (loadingSpinner) {
                loadingSpinner.style.display = show ? 'block' : 'none';
                console.log('Loading spinner display set to:', loadingSpinner.style.display);
            } else {
                console.error('Loading spinner element not found!');
            }
            
            if (tableContainer) {
                tableContainer.style.display = show ? 'none' : 'block';
                console.log('Table container display set to:', tableContainer.style.display);
            } else {
                console.error('Table container element not found!');
            }
        }

        // Show alert
        function showAlert(message, type) {
            const alertContainer = document.getElementById('alertContainer');
            const alertId = 'alert-' + Date.now();
            
            alertContainer.innerHTML = `
                <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert">
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                const alert = document.getElementById(alertId);
                if (alert) {
                    bootstrap.Alert.getOrCreateInstance(alert).close();
                }
            }, 5000);
        }
    </script>
</body>
</html>
