<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rewards Catalog - Admin - LocalLendables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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>
        .reward-row {
            transition: background-color 0.3s ease;
        }
        
        .reward-row:hover {
            background-color: #f8f9fa;
        }
        
        .category-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .points-badge {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-weight: bold;
        }
        
        .status-active {
            color: #28a745;
        }
        
        .status-inactive {
            color: #dc3545;
        }
        
        .quantity-warning {
            color: #ffc107;
        }
        
        .quantity-danger {
            color: #dc3545;
        }
    </style>
</head>
<body class="bg-light">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container">
            <a class="navbar-brand fw-bold" href="/admin/dashboard">
                <i class="fas fa-leaf me-2"></i>LocalLendables Admin
            </a>
            <div class="d-flex align-items-center text-white">
                <a href="/admin/site-config" class="btn btn-outline-light btn-sm me-2">
                    <i class="fas fa-cog me-1"></i>Site Config
                </a>
                <a href="/admin/dashboard" class="btn btn-outline-light btn-sm">
                    <i class="fas fa-home me-1"></i>Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-gift me-2 text-primary"></i>Rewards Catalog Management
            </h2>
            <button class="btn btn-primary" onclick="showAddRewardModal()">
                <i class="fas fa-plus me-1"></i>Add New Reward
            </button>
        </div>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-primary">{{ rewards|length }}</h3>
                        <p class="mb-0">Total Rewards</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-success">{{ rewards|filter(r => r.is_active)|length }}</h3>
                        <p class="mb-0">Active Rewards</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-warning">{{ rewards|filter(r => r.quantity_available and r.quantity_available <= 5)|length }}</h3>
                        <p class="mb-0">Low Stock</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-info">{{ rewards|map(r => r.category)|unique|length }}</h3>
                        <p class="mb-0">Categories</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rewards Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>All Rewards
                </h5>
            </div>
            <div class="card-body p-0">
                {% if rewards|length > 0 %}
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Reward</th>
                                <th>Category</th>
                                <th>Points Cost</th>
                                <th>Sponsor</th>
                                <th>Stock</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for reward in rewards %}
                            <tr class="reward-row" id="reward-{{ reward.id }}">
                                <td>
                                    <div class="d-flex align-items-center">
                                        {% if reward.image_url %}
                                            <img src="{{ reward.image_url }}" class="me-3 rounded" style="width: 40px; height: 40px; object-fit: cover;" alt="{{ reward.name }}">
                                        {% else %}
                                            <div class="me-3 bg-secondary rounded d-flex align-items-center justify-content-center text-white" style="width: 40px; height: 40px;">
                                                <i class="fas fa-gift"></i>
                                            </div>
                                        {% endif %}
                                        <div>
                                            <h6 class="mb-0">{{ reward.name }}</h6>
                                            {% if reward.description %}
                                                <small class="text-muted">{{ reward.description[:50] }}{% if reward.description|length > 50 %}...{% endif %}</small>
                                            {% endif %}
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="category-badge bg-light text-dark">{{ reward.category }}</span>
                                </td>
                                <td>
                                    <span class="points-badge">{{ reward.points_cost }} pts</span>
                                </td>
                                <td>
                                    {% if reward.sponsor_name %}
                                        <small class="text-muted">
                                            <i class="fas fa-handshake me-1"></i>{{ reward.sponsor_name }}
                                        </small>
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if reward.quantity_available is null %}
                                        <span class="text-success">
                                            <i class="fas fa-infinity"></i> Unlimited
                                        </span>
                                    {% elseif reward.quantity_available <= 0 %}
                                        <span class="quantity-danger">
                                            <i class="fas fa-times-circle"></i> Out of Stock
                                        </span>
                                    {% elseif reward.quantity_available <= 5 %}
                                        <span class="quantity-warning">
                                            <i class="fas fa-exclamation-triangle"></i> {{ reward.quantity_available }} left
                                        </span>
                                    {% else %}
                                        <span class="text-muted">{{ reward.quantity_available }} available</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if reward.is_active %}
                                        <i class="fas fa-check-circle status-active"></i> Active
                                    {% else %}
                                        <i class="fas fa-times-circle status-inactive"></i> Inactive
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" onclick="editReward({{ reward.id }})">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-{{ reward.is_active ? 'warning' : 'success' }}" onclick="toggleRewardStatus({{ reward.id }}, {{ reward.is_active ? 'false' : 'true' }})">
                                            <i class="fas fa-{{ reward.is_active ? 'pause' : 'play' }}"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="deleteReward({{ reward.id }}, '{{ reward.name }}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-gift fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">No rewards configured</h4>
                    <p class="text-muted">Add your first reward to get started!</p>
                    <button class="btn btn-primary" onclick="showAddRewardModal()">
                        <i class="fas fa-plus me-1"></i>Add First Reward
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Add/Edit Reward Modal -->
    <div class="modal fade" id="rewardModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="rewardModalTitle">Add New Reward</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="rewardForm">
                        <input type="hidden" id="rewardId" name="id">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Reward Name *</label>
                                    <input type="text" class="form-control" name="name" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Points Cost *</label>
                                    <input type="number" class="form-control" name="points_cost" min="1" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Category *</label>
                                    <select class="form-control" name="category" required>
                                        <option value="">Select Category</option>
                                        <option value="Food & Treats">Food & Treats</option>
                                        <option value="Gift Cards">Gift Cards</option>
                                        <option value="Experiences">Experiences</option>
                                        <option value="Merchandise">Merchandise</option>
                                        <option value="Services">Services</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Sponsor Name</label>
                                    <input type="text" class="form-control" name="sponsor_name">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Quantity Available</label>
                                    <input type="number" class="form-control" name="quantity_available" min="1">
                                    <div class="form-text">Leave empty for unlimited quantity</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Image URL</label>
                                    <input type="url" class="form-control" name="image_url">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" 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="saveReward()">Save Reward</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function showAddRewardModal() {
            document.getElementById('rewardModalTitle').textContent = 'Add New Reward';
            document.getElementById('rewardForm').reset();
            document.getElementById('rewardId').value = '';
            new bootstrap.Modal(document.getElementById('rewardModal')).show();
        }

        async function saveReward() {
            try {
                const formData = new FormData(document.getElementById('rewardForm'));
                const rewardData = Object.fromEntries(formData);
                
                const isEdit = rewardData.id && rewardData.id !== '';
                const url = isEdit ? `/admin/api/rewards/${rewardData.id}` : '/admin/api/rewards';
                const method = isEdit ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(rewardData)
                });
                
                if (response.ok) {
                    showAlert(isEdit ? 'Reward updated successfully!' : 'Reward added successfully!', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('rewardModal')).hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    throw new Error('Failed to save reward');
                }
            } catch (error) {
                console.error('Error saving reward:', error);
                showAlert('Error saving reward. Please try again.', 'error');
            }
        }

        async function toggleRewardStatus(rewardId, newStatus) {
            try {
                const response = await fetch(`/admin/api/rewards/${rewardId}/status`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ is_active: newStatus === 'true' })
                });
                
                if (response.ok) {
                    showAlert('Reward status updated!', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    throw new Error('Failed to update status');
                }
            } catch (error) {
                console.error('Error updating reward status:', error);
                showAlert('Error updating status. Please try again.', 'error');
            }
        }

        async function deleteReward(rewardId, rewardName) {
            if (!confirm(`Are you sure you want to delete "${rewardName}"? This action cannot be undone.`)) {
                return;
            }
            
            try {
                const response = await fetch(`/admin/api/rewards/${rewardId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    showAlert('Reward deleted successfully!', 'success');
                    document.getElementById(`reward-${rewardId}`).remove();
                } else {
                    throw new Error('Failed to delete reward');
                }
            } catch (error) {
                console.error('Error deleting reward:', error);
                showAlert('Error deleting reward. Please try again.', 'error');
            }
        }

        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
    </script>
</body>
</html>