<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-user-tag me-2"></i>Assign Plans to Users
                </h1>
            </div>

            <!-- Statistics Cards -->
            <div class="row g-4 mb-4">
                <div class="col-md-3">
                    <div class="card shadow-sm bg-primary text-white">
                        <div class="card-body">
                            <h5 class="card-title">Total Users</h5>
                            <h2 class="mb-0">
                                <%= users.length %>
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card shadow-sm bg-success text-white">
                        <div class="card-body">
                            <h5 class="card-title">Paid Users</h5>
                            <h2 class="mb-0">
                                <%= users.filter(u=> u.tier !== defaultPlanId).length %>
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card shadow-sm bg-info text-white">
                        <div class="card-body">
                            <h5 class="card-title">Free Users</h5>
                            <h2 class="mb-0">
                                <%= users.filter(u=> u.tier === defaultPlanId).length %>
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card shadow-sm bg-warning text-white">
                        <div class="card-body">
                            <h5 class="card-title">Enterprise</h5>
                            <h2 class="mb-0">
                                <%= users.filter(u=> u.tier === 'enterprise').length %>
                            </h2>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Users Table -->
            <div class="card shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="mb-0">
                        <i class="fas fa-users me-2"></i>User Plans
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="usersTable">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Username</th>
                                    <th>Current Plan</th>
                                    <th>Expires At</th>
                                    <th>Registered</th>
                                    <th>Last Login</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <% users.forEach(u=> { %>
                                    <tr>
                                        <td>
                                            <%= u.id %>
                                        </td>
                                        <td><strong>
                                                <%= u.username %>
                                            </strong></td>
                                        <td>
                                            <% if (u.tier) { %>
                                                <% // Find the tier info to check if it's default const
                                                    tierInfo=tiers.find(t=> t.id === u.tier);
                                                    const isDefaultTier = tierInfo?.isDefault;
                                                    const badgeColor = isDefaultTier ? 'secondary' :
                                                    u.tier === 'starter' ? 'info' :
                                                    u.tier === 'professional' ? 'primary' :
                                                    u.tier === 'business' ? 'success' :
                                                    'warning';
                                                    %>
                                                    <span class="badge bg-<%= badgeColor %>">
                                                        <%= u.tier.toUpperCase() %>
                                                            <% if (isDefaultTier) { %>(Default)<% } %>
                                                    </span>
                                                    <% } else { %>
                                                        <span class="badge bg-secondary">NO PLAN</span>
                                                        <% } %>
                                        </td>
                                        <td>
                                            <% if (u.tier_expires_at) { %>
                                                <%= new Date(u.tier_expires_at).toLocaleDateString() %>
                                                    <% if (new Date(u.tier_expires_at) < new Date()) { %>
                                                        <span class="badge bg-danger ms-2">Expired</span>
                                                        <% } %>
                                                            <% } else { %>
                                                                <span class="text-muted">-</span>
                                                                <% } %>
                                        </td>
                                        <td>
                                            <%= new Date(u.created_at).toLocaleDateString() %>
                                        </td>
                                        <td>
                                            <% if (u.last_login) { %>
                                                <%= new Date(u.last_login).toLocaleDateString() %>
                                                    <% } else { %>
                                                        <span class="text-muted">Never</span>
                                                        <% } %>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" data-user-id="<%= u.id %>"
                                                data-user-tier="<%= u.tier %>" onclick="editPlan(this)">
                                                <i class="fas fa-edit"></i> Change Plan
                                            </button>
                                        </td>
                                    </tr>
                                    <% }) %>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Plan Modal -->
<div class="modal fade" id="editPlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Change User Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editPlanForm">
                <input type="hidden" id="editUserId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Select Plan</label>
                        <select class="form-select" id="editTier" required>
                            <% tiers.forEach(tier=> { %>
                                <option value="<%= tier.id %>" data-is-default="<%= tier.isDefault %>">
                                    <%= tier.name %>
                                        <% if (tier.isDefault) { %>
                                            (Default)
                                            <% } else if (tier.price !=='Custom' && tier.price !==0) { %>
                                                - $<%= tier.price.toLocaleString() %>/month
                                                    <% } else if (tier.price===0) { %>
                                                        - Free
                                                        <% } else { %>
                                                            - Custom Pricing
                                                            <% } %>
                                </option>
                                <% }) %>
                        </select>
                    </div>

                    <div class="mb-3" id="durationField">
                        <label class="form-label">Duration (days)</label>
                        <input type="number" class="form-control" id="editDuration" min="1" max="365" value="30">
                        <small class="text-muted">e.g., 30 days = 1 month, 365 days = 1 year</small>
                    </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> Update Plan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function editPlan(button) {
        const userId = button.getAttribute('data-user-id');
        const currentTier = button.getAttribute('data-user-tier');

        document.getElementById('editUserId').value = userId;
        document.getElementById('editTier').value = currentTier;

        // Show/hide duration field based on current tier
        const durationField = document.getElementById('durationField');
        if (currentTier === defaultPlanId) {
            durationField.style.display = 'none';
        } else {
            durationField.style.display = 'block';
        }

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

    // Show/hide duration field based on tier (hide for default/free plan)
    const defaultPlanId = '<%= defaultPlanId %>';
    document.getElementById('editTier').addEventListener('change', function () {
        const durationField = document.getElementById('durationField');
        const selectedTier = this.value;
        // Find if selected tier is the default plan
        const tierOption = this.options[this.selectedIndex];
        if (selectedTier === defaultPlanId) {
            durationField.style.display = 'none';
        } else {
            durationField.style.display = 'block';
        }
    });

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

        const userId = document.getElementById('editUserId').value;
        const tier = document.getElementById('editTier').value;
        const duration = document.getElementById('editDuration').value;

        try {
            const response = await fetch(`/webapi/admin/users/${userId}/plan`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'x-csrf-token': '<%= csrfToken %>'
                },
                body: JSON.stringify({ tier, duration })
            });

            const data = await response.json();

            if (data.success) {
                Toast.success('Plan updated successfully!');
                setTimeout(() => location.reload(), 1000);
            } else {
                Toast.error('Error: ' + data.error);
            }
        } catch (error) {
            console.error('Error:', error);
            Toast.error('Failed to update plan');
        }
    });
</script>