<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="fw-bold text-primary">
                    <i class="fas fa-crown me-2"></i>Plan Management
                </h1>
                <div class="d-flex gap-2">
                    <a href="/admin/assign-plans" class="btn btn-success">
                        <i class="fas fa-user-tag me-2"></i>Assign Plans to Users
                    </a>
                    <button class="btn btn-primary" onclick="showAddPlanModal()">
                        <i class="fas fa-plus me-2"></i>Add New Plan
                    </button>
                </div>
            </div>

            <!-- Warning if no default plan is configured -->
            <% if (!hasDefaultPlan) { %>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Warning:</strong> No default plan is configured!
                    Users with expired plans cannot be downgraded automatically.
                    Please set one plan as the default (free tier) plan.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <% } %>

                    <!-- Plans Table -->
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Plan Name</th>
                                            <th>Price ($)</th>
                                            <th>Expiry (Days)</th>
                                            <th>Total Messages</th>
                                            <th>Sessions</th>
                                            <th>Contacts</th>
                                            <th>Number Checks</th>
                                            <th>API Rate Limit</th>
                                            <th>AI Assistant</th>
                                            <th>Auto Reply</th>
                                            <th>API Access</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% tiers.forEach(tier=> { %>
                                            <tr>
                                                <td>
                                                    <strong>
                                                        <%= tier.name %>
                                                    </strong>
                                                    <% if (tier.isDefault) { %>
                                                        <span class="badge bg-info ms-2"
                                                            title="Default plan for new users and downgrades">Default</span>
                                                        <% } %>
                                                            <% if (tier.popular) { %>
                                                                <span class="badge bg-success ms-2">Popular</span>
                                                                <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.price==='Custom' ) { %>
                                                        <span class="text-muted">Custom</span>
                                                        <% } else if (tier.price===0) { %>
                                                            <span class="text-success fw-bold">Free</span>
                                                            <% } else { %>
                                                                $<%= tier.price.toLocaleString() %>
                                                                    <% } %>
                                                </td>
                                                <td>
                                                    <%= tier.expiryDays || 'Lifetime' %>
                                                </td>
                                                <td>
                                                    <% if (tier.totalMessages===-1) { %>
                                                        <span class="text-success">Unlimited</span>
                                                        <% } else { %>
                                                            <%= tier.totalMessages?.toLocaleString() || 'N/A' %>
                                                                <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.totalSessions===-1) { %>
                                                        <span class="text-success">Unlimited</span>
                                                        <% } else { %>
                                                            <%= tier.totalSessions || 'N/A' %>
                                                                <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.totalContacts===-1) { %>
                                                        <span class="text-success">Unlimited</span>
                                                        <% } else { %>
                                                            <%= tier.totalContacts?.toLocaleString() || 'N/A' %>
                                                                <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.totalNumberCheckers===-1) { %>
                                                        <span class="text-success">Unlimited</span>
                                                        <% } else { %>
                                                            <%= tier.totalNumberCheckers || 'N/A' %>
                                                                <% } %>
                                                </td>
                                                <td>
                                                    <% if (!tier.features?.apiAccess) { %>
                                                        <span class="text-muted">No Access</span>
                                                        <% } else if (tier.apiRequestsPerHour===-1) { %>
                                                            <span class="text-success">Unlimited</span>
                                                            <% } else if (tier.apiRequestsPerHour===0) { %>
                                                                <span class="text-muted">No Access</span>
                                                                <% } else { %>
                                                                    <%= tier.apiRequestsPerHour %>/hour
                                                                        <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.features?.aiAssistant) { %>
                                                        <i class="fas fa-check-circle text-success"></i>
                                                        <% } else { %>
                                                            <i class="fas fa-times-circle text-danger"></i>
                                                            <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.features?.autoReply) { %>
                                                        <i class="fas fa-check-circle text-success"></i>
                                                        <% } else { %>
                                                            <i class="fas fa-times-circle text-danger"></i>
                                                            <% } %>
                                                </td>
                                                <td>
                                                    <% if (tier.features?.apiAccess) { %>
                                                        <i class="fas fa-check-circle text-success"></i>
                                                        <% } else { %>
                                                            <i class="fas fa-times-circle text-danger"></i>
                                                            <% } %>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-primary me-1"
                                                        data-tier='<%- JSON.stringify(tier) %>'
                                                        onclick="editPlan(this)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <% if (!tier.isDefault) { %>
                                                        <button class="btn btn-sm btn-danger"
                                                            onclick="deletePlan('<%= tier.id %>')">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                        <% } %>
                                                </td>
                                            </tr>
                                            <% }) %>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
        </div>
    </div>
</div>

<!-- Add/Edit Plan Modal -->
<div class="modal fade" id="planModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="planModalTitle">Add New Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="planForm">
                <input type="hidden" id="planId">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Plan Name *</label>
                            <input type="text" class="form-control" id="planName" required>
                            <small class="text-muted">e.g., Starter, Professional</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Plan ID (slug) *</label>
                            <input type="text" class="form-control" id="planSlug" required>
                            <small class="text-muted">e.g., starter, professional (lowercase, no spaces)</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Price ($) *</label>
                            <input type="number" class="form-control" id="planPrice" min="0" required>
                            <small class="text-muted">Enter 0 for free plan</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Expiry (Days)</label>
                            <input type="number" class="form-control" id="planExpiryDays" min="1">
                            <small class="text-muted">Leave empty for lifetime</small>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="form-label fw-bold">Popular?</label>
                            <select class="form-select" id="planPopular">
                                <option value="false">No</option>
                                <option value="true">Yes</option>
                            </select>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="form-label fw-bold">Default?</label>
                            <select class="form-select" id="planIsDefault">
                                <option value="false">No</option>
                                <option value="true">Yes</option>
                            </select>
                            <small class="text-muted">Free tier</small>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="form-label fw-bold">Color</label>
                            <input type="color" class="form-control form-control-color" id="planColor" value="#667eea"
                                title="Choose plan color">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Total Messages *</label>
                            <input type="number" class="form-control" id="planMessages" min="-1" required>
                            <small class="text-muted">Total for subscription period (-1 = unlimited)</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Total Sessions *</label>
                            <input type="number" class="form-control" id="planSessions" min="-1" required>
                            <small class="text-muted">Enter -1 for unlimited</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Total Contacts *</label>
                            <input type="number" class="form-control" id="planContacts" min="-1" required>
                            <small class="text-muted">Enter -1 for unlimited</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Total Templates *</label>
                            <input type="number" class="form-control" id="planTemplates" min="-1" required>
                            <small class="text-muted">Enter -1 for unlimited</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">Number Checks *</label>
                            <input type="number" class="form-control" id="planNumberCheckers" min="-1" required>
                            <small class="text-muted">Total contacts that can be checked (-1 = unlimited)</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold">API Rate Limit (per hour) *</label>
                            <input type="number" class="form-control" id="planApiRateLimit" min="-1" required>
                            <small class="text-muted">0 = no access, -1 = unlimited</small>
                        </div>
                    </div>

                    <hr class="my-4">
                    <h6 class="fw-bold mb-3">Features</h6>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="featureAI">
                                <label class="form-check-label" for="featureAI">
                                    <i class="fas fa-robot me-2"></i>AI Assistant
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="featureAutoReply">
                                <label class="form-check-label" for="featureAutoReply">
                                    <i class="fas fa-reply me-2"></i>Auto Reply
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="featureAPI">
                                <label class="form-check-label" for="featureAPI">
                                    <i class="fas fa-code me-2"></i>API Access
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Plan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    let planModal;

    document.addEventListener('DOMContentLoaded', function () {
        planModal = new bootstrap.Modal(document.getElementById('planModal'));
    });

    function showAddPlanModal() {
        document.getElementById('planModalTitle').textContent = 'Add New Plan';
        document.getElementById('planForm').reset();
        document.getElementById('planId').value = '';
        planModal.show();
    }

    function editPlan(button) {
        const tier = JSON.parse(button.getAttribute('data-tier'));

        document.getElementById('planModalTitle').textContent = 'Edit Plan: ' + tier.name;
        document.getElementById('planId').value = tier.id;
        document.getElementById('planName').value = tier.name;
        document.getElementById('planSlug').value = tier.id;
        document.getElementById('planPrice').value = tier.price === 'Custom' ? '' : tier.price;
        document.getElementById('planExpiryDays').value = tier.expiryDays || '';
        document.getElementById('planPopular').value = tier.popular ? 'true' : 'false';
        document.getElementById('planIsDefault').value = tier.isDefault ? 'true' : 'false';
        document.getElementById('planColor').value = tier.color || '#667eea';
        document.getElementById('planMessages').value = tier.totalMessages || -1;
        document.getElementById('planSessions').value = tier.totalSessions || -1;
        document.getElementById('planContacts').value = tier.totalContacts || -1;
        document.getElementById('planTemplates').value = tier.totalTemplates || -1;
        document.getElementById('planNumberCheckers').value = tier.totalNumberCheckers || -1;
        document.getElementById('planApiRateLimit').value = tier.apiRequestsPerHour !== undefined ? tier.apiRequestsPerHour : 0;

        // Set features
        document.getElementById('featureAI').checked = tier.features?.aiAssistant || false;
        document.getElementById('featureAutoReply').checked = tier.features?.autoReply || false;
        document.getElementById('featureAPI').checked = tier.features?.apiAccess || false;

        planModal.show();
    }

    async function deletePlan(planId) {
        ConfirmModal.show({
            title: 'Delete Plan',
            message: 'Are you sure you want to delete this plan?<br><small class="text-muted">This action cannot be undone.</small>',
            confirmText: 'Delete',
            cancelText: 'Cancel',
            type: 'danger',
            icon: 'fa-trash',
            onConfirm: async () => {
                try {
                    const response = await fetch(`/webapi/admin/plans/${planId}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                            'x-csrf-token': '<%= csrfToken %>'
                        }
                    });

                    const data = await response.json();
                    if (data.success) {
                        Toast.success('Plan deleted successfully!');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        Toast.error('Error: ' + data.error);
                    }
                } catch (error) {
                    console.error('Error:', error);
                    Toast.error('Failed to delete plan');
                }
            }
        });
    }

    document.getElementById('planForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        const planData = {
            id: document.getElementById('planId').value || document.getElementById('planSlug').value,
            name: document.getElementById('planName').value,
            price: parseInt(document.getElementById('planPrice').value),
            expiryDays: parseInt(document.getElementById('planExpiryDays').value) || null,
            popular: document.getElementById('planPopular').value === 'true',
            isDefault: document.getElementById('planIsDefault').value === 'true',
            color: document.getElementById('planColor').value,
            totalMessages: parseInt(document.getElementById('planMessages').value),
            totalSessions: parseInt(document.getElementById('planSessions').value),
            totalContacts: parseInt(document.getElementById('planContacts').value),
            totalTemplates: parseInt(document.getElementById('planTemplates').value),
            totalNumberCheckers: parseInt(document.getElementById('planNumberCheckers').value),
            apiRequestsPerHour: parseInt(document.getElementById('planApiRateLimit').value),
            features: {
                aiAssistant: document.getElementById('featureAI').checked,
                autoReply: document.getElementById('featureAutoReply').checked,
                apiAccess: document.getElementById('featureAPI').checked
            }
        };

        try {
            const response = await fetch('/webapi/admin/plans/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-csrf-token': '<%= csrfToken %>'
                },
                body: JSON.stringify(planData)
            });

            const data = await response.json();
            if (data.success) {
                Toast.success('Plan saved successfully!');
                planModal.hide();
                setTimeout(() => location.reload(), 1000);
            } else {
                Toast.error('Error: ' + data.error);
            }
        } catch (error) {
            console.error('Error:', error);
            Toast.error('Failed to save plan');
        }
    });
</script>