<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1>SUPPORT & HELP</h1>
            <p class="welcome-text">Get assistance and submit support tickets</p>
        </div>
    </header>

    <!-- Support Overview -->
    <div class="metrics-cards">
        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-ticket-alt"></i>
            </div>
            <div class="card-content">
                <p class="card-label">OPEN TICKETS</p>
                <div class="card-data">
                    <span class="value" id="openTickets">0</span>
                    <span class="change">--</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="card-content">
                <p class="card-label">RESOLVED TICKETS</p>
                <div class="card-data">
                    <span class="value" id="resolvedTickets">0</span>
                    <span class="change positive">+0%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-clock"></i>
            </div>
            <div class="card-content">
                <p class="card-label">AVG. RESPONSE TIME</p>
                <div class="card-data">
                    <span class="value" id="avgResponseTime">--</span>
                    <span class="change">--</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-satellite-dish"></i>
            </div>
            <div class="card-content">
                <p class="card-label">SYSTEM STATUS</p>
                <div class="card-data">
                    <span class="value" id="systemStatus">Healthy</span>
                    <span class="change positive">+0%</span>
                </div>
            </div>
        </div>
    </div>

    <div class="analytics-grid">
        <!-- Left Column -->
        <div class="analytics-column">
            <!-- Create Support Ticket -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Create Support Ticket</h3>
                </div>
                <form id="supportTicketForm">
                    <div class="form-group">
                        <label class="form-label">Subject *</label>
                        <input type="text" name="subject" class="form-input" placeholder="Brief description of your issue" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Issue Type *</label>
                        <select name="issue_type" class="form-select" required>
                            <option value="">Select issue type</option>
                            <option value="bug">Bug Report</option>
                            <option value="feature">Feature Request</option>
                            <option value="technical">Technical Issue</option>
                            <option value="billing">Billing Inquiry</option>
                            <option value="general">General Question</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Priority *</label>
                        <select name="priority" class="form-select" required>
                            <option value="low">Low</option>
                            <option value="medium" selected>Medium</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Description *</label>
                        <textarea name="description" class="form-textarea" rows="6" 
                                  placeholder="Please provide detailed information about your issue..." required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Attachments (Optional)</label>
                        <div class="file-upload-container">
                            <input type="file" name="attachments[]" id="attachmentsInput" class="file-input" multiple accept=".jpg,.jpeg,.png,.pdf,.txt,.log">
                            <label for="attachmentsInput" class="file-upload-label">
                                <i class="fas fa-paperclip"></i>
                                <span>Add Attachments</span>
                            </label>
                            <div class="file-preview" id="attachmentsPreview"></div>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="clearTicketForm()">Clear</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i> Submit Ticket
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Right Column -->
        <div class="analytics-column">
            <!-- Quick Help -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Quick Help</h3>
                </div>
                <div class="help-links">
                    <a href="#" class="help-link" onclick="showHelp('pdf_processing')">
                        <i class="fas fa-file-pdf"></i>
                        <span>PDF Processing Issues</span>
                    </a>
                    <a href="#" class="help-link" onclick="showHelp('model_extraction')">
                        <i class="fas fa-users"></i>
                        <span>Model Data Extraction</span>
                    </a>
                    <a href="#" class="help-link" onclick="showHelp('performance')">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>Performance Problems</span>
                    </a>
                    <a href="#" class="help-link" onclick="showHelp('upload_issues')">
                        <i class="fas fa-upload"></i>
                        <span>File Upload Problems</span>
                    </a>
                    <a href="#" class="help-link" onclick="showHelp('api_issues')">
                        <i class="fas fa-code"></i>
                        <span>API & Integration</span>
                    </a>
                    <a href="#" class="help-link" onclick="showHelp('account_issues')">
                        <i class="fas fa-user-cog"></i>
                        <span>Account & Access</span>
                    </a>
                </div>
            </div>

            <!-- Contact Information -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Contact Information</h3>
                </div>
                <div class="contact-info">
                    <div class="contact-item">
                        <i class="fas fa-envelope"></i>
                        <div>
                            <strong>Email Support</strong>
                            <span>support@goproductions.com</span>
                        </div>
                    </div>
                    <div class="contact-item">
                        <i class="fas fa-phone"></i>
                        <div>
                            <strong>Phone Support</strong>
                            <span>+1 (555) 123-4567</span>
                        </div>
                    </div>
                    <div class="contact-item">
                        <i class="fas fa-clock"></i>
                        <div>
                            <strong>Support Hours</strong>
                            <span>Mon-Fri: 9AM-6PM IST</span>
                        </div>
                    </div>
                    <div class="contact-item">
                        <i class="fab fa-whatsapp"></i>
                        <div>
                            <strong>WhatsApp Support</strong>
                            <span>+91 80765 85915</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- System Status -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Live System Status</h3>
                    <span class="status-indicator healthy">● Operational</span>
                </div>
                <div class="system-status">
                    <div class="status-item">
                        <span class="status-label">PDF Processing</span>
                        <span class="status-value healthy">Operational</span>
                    </div>
                    <div class="status-item">
                        <span class="status-label">Database</span>
                        <span class="status-value healthy">Operational</span>
                    </div>
                    <div class="status-item">
                        <span class="status-label">File Storage</span>
                        <span class="status-value healthy">Operational</span>
                    </div>
                    <div class="status-item">
                        <span class="status-label">API Services</span>
                        <span class="status-value healthy">Operational</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Ticket History -->
    <div class="content-area">
        <div class="section-header">
            <h2>Your Support Tickets</h2>
            <button class="btn btn-secondary" onclick="loadTickets()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
        
        <div class="tickets-list" id="ticketsList">
            <div class="ticket-item loading">
                <i class="fas fa-spinner fa-spin"></i>
                <span>Loading your support tickets...</span>
            </div>
        </div>
    </div>
</main>

<!-- Help Modal -->
<div id="helpModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="helpModalTitle">Help Article</h3>
            <button class="btn-close" onclick="closeHelpModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="helpContent"></div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="createTicketFromHelp()">Create Ticket</button>
            <button class="btn btn-secondary" onclick="closeHelpModal()">Close</button>
        </div>
    </div>
</div>

<style>
.help-links {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.help-link {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    text-decoration: none;
    color: var(--text-color);
    transition: all 0.3s ease;
    border: 1px solid var(--border-color);
}

.help-link:hover {
    background: var(--hover-color);
    transform: translateX(4px);
}

.help-link i {
    width: 20px;
    text-align: center;
    color: var(--primary-color);
}

.contact-info {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.contact-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
}

.contact-item i {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--border-color);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-color);
    flex-shrink: 0;
}

.contact-item div {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.contact-item strong {
    font-size: 14px;
    color: var(--text-color);
}

.contact-item span {
    font-size: 13px;
    color: var(--light-text);
}

.system-status {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.status-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-color);
}

.status-item:last-child {
    border-bottom: none;
}

.status-label {
    font-size: 14px;
    color: var(--text-color);
}

.status-value {
    font-size: 12px;
    font-weight: 600;
    padding: 4px 8px;
    border-radius: 12px;
}

.status-value.healthy {
    background: #e8f5e8;
    color: #2e7d32;
}

.status-value.degraded {
    background: #fff3e0;
    color: #ef6c00;
}

.status-value.outage {
    background: #ffebee;
    color: #c62828;
}

.status-indicator {
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
}

.status-indicator.healthy { color: #2e7d32; }
.status-indicator.degraded { color: #ef6c00; }
.status-indicator.outage { color: #c62828; }

.status-indicator::before {
    content: '●';
    font-size: 16px;
}

.tickets-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.ticket-item {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    transition: all 0.3s ease;
}

.ticket-item:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.ticket-item.loading {
    justify-content: center;
    color: var(--light-text);
}

.ticket-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}

.ticket-icon.open { background: #fff3e0; color: #ef6c00; }
.ticket-icon.pending { background: #e3f2fd; color: #1565c0; }
.ticket-icon.resolved { background: #e8f5e8; color: #2e7d32; }
.ticket-icon.closed { background: #f0f0f0; color: #666; }

.ticket-content {
    flex: 1;
}

.ticket-subject {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-color);
    margin-bottom: 4px;
}

.ticket-meta {
    display: flex;
    gap: 16px;
    font-size: 12px;
    color: var(--light-text);
}

.ticket-priority {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.priority-low { background: #e8f5e8; color: #2e7d32; }
.priority-medium { background: #fff3e0; color: #ef6c00; }
.priority-high { background: #ffebee; color: #c62828; }
.priority-urgent { background: #fce4ec; color: #c2185b; }

.ticket-actions {
    display: flex;
    gap: 8px;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>

<script>
let currentHelpTopic = '';

document.addEventListener('DOMContentLoaded', function() {
    loadSupportStats();
    loadTickets();
    
    // Handle file attachments preview
    document.getElementById('attachmentsInput').addEventListener('change', function(e) {
        const files = e.target.files;
        const preview = document.getElementById('attachmentsPreview');
        preview.innerHTML = '';
        
        for (let file of files) {
            const fileElement = document.createElement('div');
            fileElement.className = 'file-item';
            fileElement.innerHTML = `
                <i class="fas fa-file"></i>
                <span>${file.name}</span>
                <small>(${(file.size / 1024).toFixed(1)} KB)</small>
            `;
            preview.appendChild(fileElement);
        }
    });
});

document.getElementById('supportTicketForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    try {
        const response = await fetch('<?php echo base_url('admin/create_support_ticket'); ?>', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification('Support ticket created successfully! We will contact you soon.', 'success');
            this.reset();
            document.getElementById('attachmentsPreview').innerHTML = '';
            loadTickets();
            loadSupportStats();
        } else {
            showNotification(data.message || 'Failed to create ticket. Please try again.', 'error');
        }
    } catch (error) {
        console.error('Error creating support ticket:', error);
        showNotification('Sent successfully', 'error');
    }
});

async function loadSupportStats() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_support_stats'); ?>');
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('openTickets').textContent = data.stats.open_tickets || 0;
            document.getElementById('resolvedTickets').textContent = data.stats.resolved_tickets || 0;
            document.getElementById('avgResponseTime').textContent = data.stats.avg_response_time || '--';
        }
    } catch (error) {
        console.error('Error loading support stats:', error);
    }
}

async function loadTickets() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_support_tickets'); ?>');
        const data = await response.json();
        
        const ticketsList = document.getElementById('ticketsList');
        
        if (data.success && data.tickets.length > 0) {
            ticketsList.innerHTML = data.tickets.map(ticket => `
                <div class="ticket-item">
                    <div class="ticket-icon ${ticket.status}">
                        <i class="fas fa-ticket-alt"></i>
                    </div>
                    <div class="ticket-content">
                        <div class="ticket-subject">${ticket.subject}</div>
                        <div class="ticket-meta">
                            <span>#${ticket.ticket_number}</span>
                            <span>${ticket.issue_type}</span>
                            <span>${new Date(ticket.created_at).toLocaleDateString()}</span>
                            <span class="ticket-priority priority-${ticket.priority}">${ticket.priority}</span>
                        </div>
                    </div>
                    <div class="ticket-actions">
                        <span class="status-badge ${ticket.status}">${ticket.status}</span>
                    </div>
                </div>
            `).join('');
        } else {
            ticketsList.innerHTML = `
                <div class="ticket-item" style="text-align: center; color: var(--light-text);">
                    <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                    <p>No support tickets found</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading tickets:', error);
        document.getElementById('ticketsList').innerHTML = `
            <div class="ticket-item" style="text-align: center; color: var(--light-text);">
                <i class="fas fa-exclamation-triangle"></i>
                <p>Error loading tickets</p>
            </div>
        `;
    }
}

function showHelp(topic) {
    currentHelpTopic = topic;
    const helpContent = document.getElementById('helpContent');
    
    const helpArticles = {
        'pdf_processing': {
            title: 'PDF Processing Issues',
            content: `
                <h4>Common PDF Processing Solutions</h4>
                <ul>
                    <li><strong>PDF not uploading:</strong> Check file size (max 10MB) and ensure it's a valid PDF</li>
                    <li><strong>Processing stuck:</strong> Try re-uploading the file or check server status</li>
                    <li><strong>Poor quality extraction:</strong> Ensure PDF has clear, readable text</li>
                    <li><strong>Missing model data:</strong> Verify PDF contains model information in readable format</li>
                </ul>
                <p>If issues persist, please create a support ticket with the problematic PDF attached.</p>
            `
        },
        'model_extraction': {
            title: 'Model Data Extraction',
            content: `
                <h4>Model Data Extraction Guide</h4>
                <p>Our system automatically extracts model information from PDFs. For best results:</p>
                <ul>
                    <li>Ensure model details are in clear, structured format</li>
                    <li>Include measurements, contact info, and social media handles</li>
                    <li>Use high-quality images for better recognition</li>
                    <li>Verify extracted data matches the PDF content</li>
                </ul>
            `
        },
        // Add more help articles as needed
    };
    
    const article = helpArticles[topic] || {
        title: 'Help Article',
        content: '<p>Help content not available for this topic.</p>'
    };
    
    document.getElementById('helpModalTitle').textContent = article.title;
    helpContent.innerHTML = article.content;
    document.getElementById('helpModal').style.display = 'flex';
}

function closeHelpModal() {
    document.getElementById('helpModal').style.display = 'none';
}

function createTicketFromHelp() {
    const article = {
        'pdf_processing': 'PDF Processing Issue',
        'model_extraction': 'Model Data Extraction Help'
    }[currentHelpTopic];
    
    if (article) {
        document.querySelector('input[name="subject"]').value = article;
        document.querySelector('select[name="issue_type"]').value = 'technical';
        document.querySelector('textarea[name="description"]').value = `I need assistance with: ${article}\n\nIssue details: `;
    }
    
    closeHelpModal();
    
    // Scroll to ticket form
    document.getElementById('supportTicketForm').scrollIntoView({ 
        behavior: 'smooth' 
    });
}

function clearTicketForm() {
    document.getElementById('supportTicketForm').reset();
    document.getElementById('attachmentsPreview').innerHTML = '';
}

function showNotification(message, type) {
    // Use your existing notification system
    alert(message); // Replace with your notification system
}

// Auto-refresh support data every 2 minutes
setInterval(() => {
    loadSupportStats();
    loadTickets();
}, 120000);
</script>