<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quotes Management - Astro Admin</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>
        .quote-card {
            border-left: 4px solid #ffc107;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .quote-text {
            font-style: italic;
            font-size: 1.1rem;
            line-height: 1.6;
        }
        .quote-author {
            font-weight: bold;
            opacity: 0.9;
        }
        .status-badge {
            font-size: 0.8rem;
        }
        .btn-action {
            padding: 0.25rem 0.5rem;
            margin: 0.1rem;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 bg-dark text-white p-3" style="min-height: 100vh;">
                <h4 class="text-warning mb-4">Astro Admin</h4>
                <ul class="nav flex-column">
                    <li class="nav-item mb-2">
                        <a class="nav-link text-white" href="dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item mb-2">
                        <a class="nav-link text-white" href="tatkal_management.php">
                            <i class="fas fa-bolt me-2"></i>Tatkal Management
                        </a>
                    </li>
                    <li class="nav-item mb-2">
                        <a class="nav-link text-white" href="consultation_types_management.php">
                            <i class="fas fa-calendar-check me-2"></i>Consultation Types
                        </a>
                    </li>
                    <li class="nav-item mb-2">
                        <a class="nav-link text-white" href="help_settings_management.php">
                            <i class="fas fa-question-circle me-2"></i>Help Settings
                        </a>
                    </li>
                    <li class="nav-item mb-2">
                        <a class="nav-link text-warning active" href="quotes_management.php">
                            <i class="fas fa-quote-left me-2"></i>Quotes Management
                        </a>
                    </li>
                </ul>
            </div>

            <!-- Main Content -->
            <div class="col-md-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="text-primary">
                        <i class="fas fa-quote-left me-2"></i>Quotes Management
                    </h2>
                    <button class="btn btn-success" onclick="showAddQuoteModal()">
                        <i class="fas fa-plus me-2"></i>Add New Quote
                    </button>
                </div>

                <!-- Loading Spinner -->
                <div id="loadingSpinner" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading quotes...</p>
                </div>

                <!-- Quotes List -->
                <div id="quotesList" class="row" style="display: none;">
                    <!-- Quotes will be loaded here -->
                </div>

                <!-- No Quotes Message -->
                <div id="noQuotesMessage" class="text-center py-5" style="display: none;">
                    <i class="fas fa-quote-left fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">No quotes found</h4>
                    <p class="text-muted">Add your first quote to get started.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Quote Modal -->
    <div class="modal fade" id="quoteModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="modalTitle">Add New Quote</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="quoteForm">
                        <input type="hidden" id="quoteId">
                        <div class="mb-3">
                            <label for="quoteText" class="form-label">Quote Text *</label>
                            <textarea class="form-control" id="quoteText" rows="4" required 
                                placeholder="Enter the quote text..."></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="quoteAuthor" class="form-label">Author</label>
                            <input type="text" class="form-control" id="quoteAuthor" 
                                placeholder="Enter author name (optional)">
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="displayOrder" class="form-label">Display Order</label>
                                    <input type="number" class="form-control" id="displayOrder" value="0" min="0">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="isActive" checked>
                                        <label class="form-check-label" for="isActive">
                                            Active (Show in app)
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </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="saveQuote()">
                        <i class="fas fa-save me-2"></i>Save Quote
                    </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 quote?</p>
                    <div class="alert alert-warning">
                        <strong>Warning:</strong> This action cannot be undone.
                    </div>
                </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 Quote
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let quotes = [];
        let deleteQuoteId = null;

        // Load quotes on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadQuotes();
        });

        // Load quotes from API
        async function loadQuotes() {
            try {
                const response = await fetch('../api/quotes_management.php', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const data = await response.json();
                
                if (data.success) {
                    quotes = data.quotes;
                    displayQuotes();
                } else {
                    showError('Failed to load quotes: ' + data.message);
                }
            } catch (error) {
                console.error('Error loading quotes:', error);
                showError('Error loading quotes: ' + error.message);
            }
        }

        // Display quotes in the UI
        function displayQuotes() {
            const quotesList = document.getElementById('quotesList');
            const loadingSpinner = document.getElementById('loadingSpinner');
            const noQuotesMessage = document.getElementById('noQuotesMessage');

            loadingSpinner.style.display = 'none';

            if (quotes.length === 0) {
                noQuotesMessage.style.display = 'block';
                quotesList.style.display = 'none';
                return;
            }

            noQuotesMessage.style.display = 'none';
            quotesList.style.display = 'block';

            quotesList.innerHTML = quotes.map(quote => `
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card quote-card h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <span class="badge ${quote.is_active == 1 ? 'bg-success' : 'bg-secondary'} status-badge">
                                    ${quote.is_active == 1 ? 'Active' : 'Inactive'}
                                </span>
                                <span class="badge bg-info status-badge">Order: ${quote.display_order}</span>
                            </div>
                            <p class="quote-text">"${quote.text}"</p>
                            ${quote.author ? `<p class="quote-author">- ${quote.author}</p>` : ''}
                        </div>
                        <div class="card-footer bg-transparent">
                            <div class="btn-group w-100" role="group">
                                <button class="btn btn-outline-light btn-action" onclick="editQuote(${quote.id})" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-outline-light btn-action" onclick="toggleQuoteStatus(${quote.id}, ${quote.is_active})" title="Toggle Status">
                                    <i class="fas fa-${quote.is_active == 1 ? 'eye-slash' : 'eye'}"></i>
                                </button>
                                <button class="btn btn-outline-danger btn-action" onclick="deleteQuote(${quote.id})" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // Show add quote modal
        function showAddQuoteModal() {
            document.getElementById('modalTitle').textContent = 'Add New Quote';
            document.getElementById('quoteForm').reset();
            document.getElementById('quoteId').value = '';
            document.getElementById('isActive').checked = true;
            document.getElementById('displayOrder').value = quotes.length;
            
            const modal = new bootstrap.Modal(document.getElementById('quoteModal'));
            modal.show();
        }

        // Edit quote
        function editQuote(id) {
            const quote = quotes.find(q => q.id == id);
            if (!quote) return;

            document.getElementById('modalTitle').textContent = 'Edit Quote';
            document.getElementById('quoteId').value = quote.id;
            document.getElementById('quoteText').value = quote.text;
            document.getElementById('quoteAuthor').value = quote.author || '';
            document.getElementById('displayOrder').value = quote.display_order;
            document.getElementById('isActive').checked = quote.is_active == 1;

            const modal = new bootstrap.Modal(document.getElementById('quoteModal'));
            modal.show();
        }

        // Save quote
        async function saveQuote() {
            const form = document.getElementById('quoteForm');
            const formData = new FormData(form);
            
            const quoteData = {
                text: document.getElementById('quoteText').value.trim(),
                author: document.getElementById('quoteAuthor').value.trim(),
                display_order: parseInt(document.getElementById('displayOrder').value),
                is_active: document.getElementById('isActive').checked ? 1 : 0
            };

            if (!quoteData.text) {
                alert('Quote text is required');
                return;
            }

            const quoteId = document.getElementById('quoteId').value;
            const method = quoteId ? 'PUT' : 'POST';
            const url = '../api/quotes_management.php';

            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(quoteId ? { id: parseInt(quoteId), ...quoteData } : quoteData)
                });

                const data = await response.json();
                
                if (data.success) {
                    showSuccess(data.message);
                    bootstrap.Modal.getInstance(document.getElementById('quoteModal')).hide();
                    loadQuotes();
                } else {
                    showError('Failed to save quote: ' + data.message);
                }
            } catch (error) {
                console.error('Error saving quote:', error);
                showError('Error saving quote: ' + error.message);
            }
        }

        // Toggle quote status
        async function toggleQuoteStatus(id, currentStatus) {
            const newStatus = currentStatus == 1 ? 0 : 1;
            
            try {
                const response = await fetch('../api/quotes_management.php', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: id,
                        text: quotes.find(q => q.id == id).text,
                        author: quotes.find(q => q.id == id).author,
                        display_order: quotes.find(q => q.id == id).display_order,
                        is_active: newStatus
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`Quote ${newStatus == 1 ? 'activated' : 'deactivated'} successfully`);
                    loadQuotes();
                } else {
                    showError('Failed to update quote status: ' + data.message);
                }
            } catch (error) {
                console.error('Error updating quote status:', error);
                showError('Error updating quote status: ' + error.message);
            }
        }

        // Delete quote
        function deleteQuote(id) {
            deleteQuoteId = id;
            const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            modal.show();
        }

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

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

                const data = await response.json();
                
                if (data.success) {
                    showSuccess('Quote deleted successfully');
                    bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                    loadQuotes();
                } else {
                    showError('Failed to delete quote: ' + data.message);
                }
            } catch (error) {
                console.error('Error deleting quote:', error);
                showError('Error deleting quote: ' + error.message);
            } finally {
                deleteQuoteId = null;
            }
        }

        // Show success message
        function showSuccess(message) {
            // Create and show a success alert
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                <i class="fas fa-check-circle me-2"></i>${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);

            // Auto remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 5000);
        }

        // Show error message
        function showError(message) {
            // Create and show an error alert
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                <i class="fas fa-exclamation-circle me-2"></i>${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);

            // Auto remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 5000);
        }
    </script>
</body>
</html>
