<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cashier Dashboard - {{ app_name }}</title>
    
    <!-- CSS from CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">
</head>
<body>
    <!-- Simplified Navigation Bar for Cashier -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-cash-register me-2"></i>{{ app_name }} - Cashier
            </a>
            
            <ul class="navbar-nav ms-auto">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('auth.logout') }}">
                        <i class="fas fa-sign-out-alt me-1"></i>Logout
                    </a>
                </li>
            </ul>
        </div>
    </nav>
    
    <main class="container-fluid mt-4">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show" role="alert">
                        {% if category == 'error' %}
                            <i class="fas fa-exclamation-triangle me-2"></i>
                        {% elif category == 'success' %}
                            <i class="fas fa-check-circle me-2"></i>
                        {% elif category == 'info' %}
                            <i class="fas fa-info-circle me-2"></i>
                        {% endif %}
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
        
        <div class="row">
            <div class="col-12">
                <h1 class="mb-4">
                    <i class="fas fa-cash-register me-2"></i>Cashier Dashboard
                    <small class="text-muted">Welcome, {{ current_user.username }}</small>
                </h1>
            </div>
        </div>

        <!-- Quick Actions for Cashier -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-bolt me-2"></i>Cashier Controls
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <button class="btn btn-outline-primary w-100" id="btn-play-video">
                                    <i class="fas fa-play me-2"></i>Start Video Display
                                </button>
                            </div>
                            <div class="col-md-6 mb-3">
                                <button class="btn btn-outline-success w-100" id="btn-update-overlay">
                                    <i class="fas fa-edit me-2"></i>Update Display Overlay
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Current Display Status -->
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-desktop me-2"></i>Current Display Status
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="d-flex flex-column align-items-center">
                                    <i class="fas fa-video text-primary mb-2" style="font-size: 2rem;"></i>
                                    <h5 class="text-primary mb-1" id="video-status-text">Stopped</h5>
                                    <small class="text-muted">Video Status</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="d-flex flex-column align-items-center">
                                    <i class="fas fa-layer-group text-success mb-2" style="font-size: 2rem;"></i>
                                    <h5 class="text-success mb-1" id="overlay-status-text">Ready</h5>
                                    <small class="text-muted">Overlay Status</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <strong>Current Video:</strong>
                                <span id="current-video-path" class="text-muted">No video loaded</span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <strong>Current Template:</strong>
                                <span id="current-template-name" class="text-muted">default</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-user me-2"></i>Session Information
                        </h5>
                    </div>
                    <div class="card-body">
                        <dl class="mb-0">
                            <dt class="text-muted">User</dt>
                            <dd>{{ current_user.username }}</dd>
                            
                            <dt class="text-muted">Role</dt>
                            <dd>
                                <span class="badge bg-info">Cashier</span>
                            </dd>
                            
                            <dt class="text-muted">Login Time</dt>
                            <dd id="login-time">{{ current_user.last_login.strftime('%H:%M') if current_user.last_login else 'Just now' }}</dd>
                            
                            <dt class="text-muted">System Status</dt>
                            <dd>
                                <span class="badge bg-success" id="system-status">Online</span>
                            </dd>
                        </dl>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-bar me-2"></i>Today's Activity
                        </h5>
                    </div>
                    <div class="card-body text-center">
                        <div class="row">
                            <div class="col-12 mb-3">
                                <h4 class="text-primary" id="videos-played">0</h4>
                                <small class="text-muted">Videos Played</small>
                            </div>
                            <div class="col-12">
                                <h4 class="text-success" id="overlays-updated">0</h4>
                                <small class="text-muted">Overlays Updated</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Video Control Modal -->
    <div class="modal fade" id="playVideoModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Start Video Display</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="play-video-form">
                        <div class="mb-3">
                            <label class="form-label">Video File Path</label>
                            <input type="text" class="form-control" id="video-file-path" 
                                   placeholder="/path/to/video.mp4">
                            <div class="form-text">Enter the full path to the video file you want to display</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Display Template</label>
                            <select class="form-select" id="video-template">
                                <option value="">Loading templates...</option>
                            </select>
                            <div class="form-text">Choose the template for displaying information over the video</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" id="confirm-play-video">
                        <i class="fas fa-play me-1"></i>Start Display
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Overlay Update Modal -->
    <div class="modal fade" id="updateOverlayModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Update Display Overlay</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="update-overlay-form">
                        <div class="mb-3">
                            <label class="form-label">Display Template</label>
                            <select class="form-select" id="overlay-template">
                                <option value="">Loading templates...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Main Message</label>
                            <input type="text" class="form-control" id="overlay-headline" 
                                   placeholder="Special Offer">
                            <div class="form-text">The main headline or title to display</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Additional Information</label>
                            <textarea class="form-control" id="overlay-text" rows="3" 
                                      placeholder="20% off all items today only!"></textarea>
                            <div class="form-text">Additional text or details to show</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-success" id="confirm-update-overlay">
                        <i class="fas fa-edit me-1"></i>Update Display
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- System Status Bar -->
    <div id="status-bar" class="fixed-bottom bg-light border-top p-2 d-none d-lg-block">
        <div class="container-fluid">
            <div class="row align-items-center text-small">
                <div class="col-auto">
                    <span class="text-muted">Status:</span>
                    <span id="system-status" class="badge bg-success">Online</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Video:</span>
                    <span id="video-status" class="badge bg-secondary">Stopped</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Last Updated:</span>
                    <span id="last-updated" class="text-muted">--</span>
                </div>
                <div class="col text-end">
                    <small class="text-muted">{{ app_name }} v{{ app_version }}</small>
                </div>
            </div>
        </div>
    </div>
    
    <!-- JavaScript from CDN and local -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
    
    <script id="dashboard-config" type="application/json">
        {
            "statusUpdateInterval": 30000,
            "apiEndpoint": "/api",
            "user": {
                "id": {{ current_user.id | tojson }},
                "username": {{ current_user.username | tojson }},
                "is_admin": {{ current_user.is_admin | tojson }}
            }
        }
    </script>
    <script>
        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Dashboard !== 'undefined') {
                var config = JSON.parse(document.getElementById('dashboard-config').textContent);
                Dashboard.init(config);
            }
        });
    </script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Load available templates on page load
        loadAvailableTemplates();
        
        // Quick action buttons
        document.getElementById('btn-play-video').addEventListener('click', function() {
            new bootstrap.Modal(document.getElementById('playVideoModal')).show();
        });
        
        document.getElementById('btn-update-overlay').addEventListener('click', function() {
            new bootstrap.Modal(document.getElementById('updateOverlayModal')).show();
        });
        
        // Confirm actions
        document.getElementById('confirm-play-video').addEventListener('click', function() {
            const filePath = document.getElementById('video-file-path').value;
            const template = document.getElementById('video-template').value;
            
            if (!filePath) {
                alert('Please enter a video file path');
                return;
            }
            
            fetch('/api/video/control', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'play',
                    file_path: filePath,
                    template: template
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('playVideoModal')).hide();
                    updateVideoStatus();
                    updateCurrentVideoPath(filePath);
                    updateCurrentTemplate(template || 'default');
                    // Increment counter
                    const videosCount = parseInt(document.getElementById('videos-played').textContent) + 1;
                    document.getElementById('videos-played').textContent = videosCount;
                } else {
                    alert('Failed to start video: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        });
        
        document.getElementById('confirm-update-overlay').addEventListener('click', function() {
            const template = document.getElementById('overlay-template').value;
            const headline = document.getElementById('overlay-headline').value;
            const text = document.getElementById('overlay-text').value;
            
            fetch('/api/overlay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    template: template,
                    data: {
                        headline: headline,
                        ticker_text: text,
                        title: headline,
                        text: text
                    }
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('updateOverlayModal')).hide();
                    updateCurrentTemplate(template || 'default');
                    // Increment counter
                    const overlaysCount = parseInt(document.getElementById('overlays-updated').textContent) + 1;
                    document.getElementById('overlays-updated').textContent = overlaysCount;
                    
                    // Show success message
                    showNotification('Overlay updated successfully!', 'success');
                } else {
                    alert('Failed to update overlay: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        });
        
        // Status update functions
        function updateVideoStatus() {
            fetch('/api/video/status')
            .then(response => response.json())
            .then(data => {
                const status = data.player_status || 'stopped';
                document.getElementById('video-status-text').textContent = 
                    status.charAt(0).toUpperCase() + status.slice(1);
            })
            .catch(error => {
                document.getElementById('video-status-text').textContent = 'Unknown';
            });
        }
        
        function updateCurrentVideoPath(path) {
            const fileName = path.split('/').pop() || path;
            document.getElementById('current-video-path').textContent = fileName;
        }
        
        function updateCurrentTemplate(template) {
            document.getElementById('current-template-name').textContent = template;
        }
        
        function showNotification(message, type = 'info') {
            // Simple notification system - could be enhanced with toast notifications
            const alertClass = type === 'success' ? 'alert-success' : 'alert-info';
            const notification = document.createElement('div');
            notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.zIndex = '9999';
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(notification);
            
            // Auto-remove after 3 seconds
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 3000);
        }
        
        // Initial status update
        updateVideoStatus();
        
        // Periodic status updates
        setInterval(updateVideoStatus, 10000);  // Every 10 seconds
    });

    function loadAvailableTemplates() {
        fetch('/api/templates')
            .then(response => response.json())
            .then(data => {
                const videoTemplateSelect = document.getElementById('video-template');
                const overlayTemplateSelect = document.getElementById('overlay-template');
                
                // Clear loading options
                videoTemplateSelect.innerHTML = '';
                overlayTemplateSelect.innerHTML = '';
                
                if (data.templates && Array.isArray(data.templates)) {
                    data.templates.forEach(template => {
                        // Add to video template select
                        const videoOption = document.createElement('option');
                        videoOption.value = template.name;
                        videoOption.textContent = template.display_name || template.name;
                        videoTemplateSelect.appendChild(videoOption);
                        
                        // Add to overlay template select
                        const overlayOption = document.createElement('option');
                        overlayOption.value = template.name;
                        overlayOption.textContent = template.display_name || template.name;
                        overlayTemplateSelect.appendChild(overlayOption);
                    });
                    
                    // Select default template if available
                    const defaultVideoOption = videoTemplateSelect.querySelector('option[value="default"]');
                    if (defaultVideoOption) {
                        defaultVideoOption.selected = true;
                    }
                    
                    const defaultOverlayOption = overlayTemplateSelect.querySelector('option[value="default"]');
                    if (defaultOverlayOption) {
                        defaultOverlayOption.selected = true;
                    }
                } else {
                    // Fallback if no templates found
                    const videoOption = document.createElement('option');
                    videoOption.value = 'default';
                    videoOption.textContent = 'Default';
                    videoTemplateSelect.appendChild(videoOption);
                    
                    const overlayOption = document.createElement('option');
                    overlayOption.value = 'default';
                    overlayOption.textContent = 'Default';
                    overlayTemplateSelect.appendChild(overlayOption);
                }
            })
            .catch(error => {
                console.error('Error loading templates:', error);
                // Fallback template options
                const videoTemplateSelect = document.getElementById('video-template');
                const overlayTemplateSelect = document.getElementById('overlay-template');
                
                videoTemplateSelect.innerHTML = '<option value="default">Default</option>';
                overlayTemplateSelect.innerHTML = '<option value="default">Default</option>';
            });
    }
    </script>
</body>
</html>