@extends('admin.layouts.app')

@section('title', 'User Plans Management')

@section('content')
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">User Plans Management</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Manage subscription plans and premium features</div>
        </div>
        
        <div style="padding: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <div style="display: flex; gap: 12px; align-items: center;">
                    <div style="position: relative;">
                        <input type="text" id="searchPlans" placeholder="Search plans..." style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; width: 300px;">
                        <span style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: var(--text-secondary);">🔍</span>
                    </div>
                    <button onclick="openAddPlanModal()" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; display: flex; align-items: center; gap: 8px;">
                        <span>➕</span> Add Plan
                    </button>
                </div>
                
                <div style="display: flex; gap: 8px;">
                    <button onclick="exportPlans()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Export Plans</button>
                    <button onclick="openRevenueReport()" style="padding: 8px 16px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer;">Revenue Report</button>
                </div>
            </div>
            
            <!-- Statistics Cards -->
            <div class="dashboard-grid" style="margin-bottom: 24px;">
                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Total Plans</div>
                            <div class="card-value" id="totalPlans">{{ $stats['total_plans'] }}</div>
                        </div>
                        <div class="stat-icon">📋</div>
                    </div>
                    <div class="card-change">Active and inactive plans</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Active Plans</div>
                            <div class="card-value" id="activePlans">{{ $stats['active_plans'] }}</div>
                        </div>
                        <div class="stat-icon">✅</div>
                    </div>
                    <div class="card-change">Currently available</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Monthly Revenue</div>
                            <div class="card-value">₹{{ number_format($stats['total_revenue'], 2) }}</div>
                        </div>
                        <div class="stat-icon">💰</div>
                    </div>
                    <div class="card-change">Estimated monthly income</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Premium Users</div>
                            <div class="card-value">{{ $stats['premium_users'] }}</div>
                        </div>
                        <div class="stat-icon">💎</div>
                    </div>
                    <div class="card-change">Users with premium plans</div>
                </div>
            </div>

            <!-- Plans Table -->
            <div class="table-card" style="border: none; padding: 0;">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 50px;">
                                <input type="checkbox" id="selectAllPlans" style="width: 16px; height: 16px;">
                            </th>
                            <th>Plan</th>
                            <th>Price</th>
                            <th>Duration</th>
                            <th>Features</th>
                            <th>Users</th>
                            <th>Default</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="plansTableBody">
                        @foreach($plans as $plan)
                        <tr data-plan-id="{{ $plan->id }}">
                            <td><input type="checkbox" class="plan-checkbox" data-plan-id="{{ $plan->id }}" style="width: 16px; height: 16px;"></td>
                            <td>
                                <div>
                                    <div style="font-weight: 600; color: {{ $plan->theme_color ?? '#7c3aed' }}; display: flex; align-items: center; gap: 8px;">
                                        {{ $plan->plan_name }}
                                        @if($plan->is_default ?? false)
                                            <span style="background: #10b981; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.65rem; font-weight: 600;">DEFAULT</span>
                                        @endif
                                    </div>
                                    <div style="font-size: 0.875rem; color: var(--text-secondary);">{{ $plan->analytics_tier }} tier</div>
                                </div>
                            </td>
                            <td style="font-weight: 600; color: var(--primary-color);">
                                @php
                                    $finalPrice = $plan->price;
                                    if ($plan->discount_percentage > 0) {
                                        $finalPrice = $plan->price * (1 - $plan->discount_percentage / 100);
                                    } elseif ($plan->discount_fixed_amount > 0) {
                                        $finalPrice = max(0, $plan->price - $plan->discount_fixed_amount);
                                    }
                                @endphp

                                @if($finalPrice < $plan->price)
                                    <div>
                                        <span style="text-decoration: line-through; color: #94a3b8; font-size: 0.8rem;">₹{{ number_format($plan->price, 2) }}</span>
                                        <span style="color: #ef4444;">₹{{ number_format($finalPrice, 2) }}</span>
                                    </div>
                                @else
                                    ₹{{ number_format($plan->price, 2) }}
                                @endif

                                @if($plan->duration_days > 30)
                                    <span style="font-size: 0.75rem; color: var(--text-secondary);">/month</span>
                                @endif
                            </td>
                            <td style="color: var(--text-secondary);">{{ $plan->duration_days }} days</td>
                            <td>
                                <div style="display: flex; gap: 4px; flex-wrap: wrap;">
                                    @if($plan->ad_free)
                                        <span style="background: #f3e8ff; color: #7c3aed; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;">Ad Free</span>
                                    @endif
                                    @if($plan->has_analytics)
                                        <span style="background: #dcfce7; color: #10b981; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;">Analytics</span>
                                    @endif
                                    @if($plan->verified_badge)
                                        <span style="background: #fef3c7; color: #f59e0b; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;">Verified</span>
                                    @endif
                                    @if($plan->post_limit)
                                        <span style="background: #e0f2fe; color: #0ea5e9; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;">{{ $plan->post_limit }} Posts</span>
                                    @endif
                                </div>
                            </td>
                            <td style="font-weight: 600;">{{ $plan->users()->count() }}</td>
                            <td>
                                @if($plan->is_default)
                                    <span style="background: #10b981; color: white; padding: 6px 12px; border-radius: 6px; font-size: 0.75rem; font-weight: 600; display: inline-block;">
                                        ✓ DEFAULT
                                    </span>
                                @else
                                    <span style="color: #94a3b8; font-size: 0.75rem;">
                                        —
                                    </span>
                                @endif
                            </td>
                            <td>
                                <label class="switch">
                                    <input type="checkbox" onchange="togglePlanStatus({{ $plan->id }}, this)" {{ $plan->status === 'Active' ? 'checked' : '' }}>
                                    <span class="slider round"></span>
                                </label>
                                <span id="status-text-{{ $plan->id }}" style="font-size: 0.75rem; color: var(--text-secondary); margin-left: 8px;">
                                    {{ $plan->status }}
                                </span>
                            </td>
                            <td>
                                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                    @if(!$plan->is_default)
                                        <form action="{{ route('admin.plans.setDefault', $plan->id) }}" method="POST" style="display: inline;">
                                            @csrf
                                            <button type="submit" class="btn-enhanced" style="background: #10b981; color: white; padding: 6px 12px; border-radius: 6px; border: none; cursor: pointer; font-size: 13px;" title="Set as default plan for new users">
                                                <span style="font-size: 14px;">⭐</span> Set Default
                                            </button>
                                        </form>
                                    @else
                                        <span style="background: #10b981; color: white; padding: 6px 12px; border-radius: 6px; font-size: 13px; font-weight: 600;">
                                            ⭐ DEFAULT
                                        </span>
                                    @endif
                                    <button class="btn-enhanced btn-analytics" onclick="viewPlanAnalytics({{ $plan->id }})">
                                        <span style="font-size: 14px;">📊</span> Analytics
                                    </button>
                                    <button class="btn-enhanced btn-edit" onclick="editPlan({{ $plan->id }})">
                                        <span style="font-size: 14px;">✏️</span> Edit
                                    </button>
                                    <button class="btn-enhanced btn-delete" onclick="deletePlan({{ $plan->id }})">
                                        <span style="font-size: 14px;">🗑️</span> Delete
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            
            <!-- Bulk Actions -->
            <div style="display: flex; gap: 12px; align-items: center; margin-top: 20px; padding: 16px; background: #f8fafc; border-radius: 8px; border: 1px solid var(--border-color);">
                <label style="font-weight: 600; color: var(--text-primary);">Bulk Actions:</label>
                <select id="bulkAction" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                    <option value="">Select Action</option>
                    <option value="activate">Activate Selected</option>
                    <option value="deactivate">Deactivate Selected</option>
                    <option value="delete">Delete Selected</option>
                </select>
                <button onclick="applyBulkAction()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Apply to Selected</button>
                <button onclick="selectAllPlans()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">Select All</button>
                <button onclick="clearSelection()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Clear Selection</button>
            </div>
        </div>
    </div>

    <!-- Add/Edit Plan Modal -->
    <div id="planModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="modalTitle">Add New Plan</h3>
                <button onclick="closePlanModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div id="planModalContent" style="padding: 20px;">
                <!-- Form will be loaded here -->
            </div>
        </div>
    </div>

    <!-- Analytics Modal -->
    <div id="analyticsModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 900px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="analyticsTitle">Plan Analytics</h3>
                <button onclick="closeAnalyticsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div id="analyticsContent" style="padding: 20px;">
                <!-- Analytics will be loaded here -->
            </div>
        </div>
    </div>



    <script>
        // State management
        let selectedPlans = new Set();

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            setupEventListeners();
        });

        // Event Listeners
        function setupEventListeners() {
            document.getElementById('selectAllPlans').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.plan-checkbox');
                checkboxes.forEach(cb => {
                    cb.checked = this.checked;
                    if (this.checked) {
                        selectedPlans.add(parseInt(cb.dataset.planId));
                    } else {
                        selectedPlans.clear();
                    }
                });
            });

            document.getElementById('bulkAction').addEventListener('change', function() {
                // Handle bulk action selection
            });

            document.getElementById('searchPlans').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('#plansTableBody tr');
                
                rows.forEach(row => {
                    const planName = row.querySelector('td:nth-child(2) div:first-child').textContent.toLowerCase();
                    const planDescription = row.querySelector('td:nth-child(2) div:last-child').textContent.toLowerCase();
                    
                    if (planName.includes(searchTerm) || planDescription.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
        }

        // Plan Management Functions
        function openAddPlanModal() {
            document.getElementById('modalTitle').textContent = 'Add New Plan';
            document.getElementById('planModalContent').innerHTML = `
                <form id="planForm">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Plan Name</label>
                            <input type="text" name="plan_name" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Price (₹)</label>
                            <input type="number" name="price" step="0.01" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Duration (Days)</label>
                            <input type="number" name="duration_days" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Validity (Days)</label>
                            <input type="number" name="validity_days" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                    </div>

                    <div style="margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: 8px; border: 1px solid var(--border-color);">
                        <h4 style="margin: 0 0 12px 0; font-size: 1rem; color: var(--text-primary);">Features</h4>
                        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="ad_free" value="1"> Ad Free
                            </label>
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="has_analytics" value="1"> Analytics
                            </label>
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="verified_badge" value="1"> Verified Badge
                            </label>
                            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="vip_badge" value="1"> VIP Badge
                            </label>
                        </div>
                    </div>

                    <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Post Limit</label>
                            <input type="number" name="post_limit" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Lead Limit</label>
                            <input type="number" name="lead_limit" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Contact Limit (VIP Bypass)</label>
                            <input type="number" name="contact_limit" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Unlimited">
                            <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 4px;">Outgoing contacts allowed when seller limit is reached.</div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Halo Effect (CSS)</label>
                            <input type="text" name="halo_effect" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="e.g., 0 0 15px rgba(255, 215, 0, 0.5)">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Ad Border (CSS)</label>
                            <input type="text" name="ad_border" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="e.g., 2px solid #FFD700">
                        </div>
                    </div>

                    <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Analytics Tier</label>
                            <select name="analytics_tier" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                <option value="basic">Basic</option>
                                <option value="advanced">Advanced</option>
                                <option value="premium">Premium</option>
                            </select>
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Status</label>
                            <select name="status" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                <option value="Active">Active</option>
                                <option value="Inactive">Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" onclick="closePlanModal()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Cancel</button>
                        <button type="submit" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Save Plan</button>
                    </div>
                </form>
            `;
            
            document.getElementById('planModal').style.display = 'flex';
            
            // Form submission
            document.getElementById('planForm').addEventListener('submit', function(e) {
                e.preventDefault();
                savePlan(new FormData(this));
            });
        }

        function editPlan(planId) {
            loadPlanData(planId);
        }

        function loadPlanData(planId) {
            // Add loading indicator
            const editBtn = document.querySelector(`tr[data-plan-id="${planId}"] button[onclick^="editPlan"]`);
            if (editBtn) editBtn.textContent = '⏳ Loading...';

            fetch(`/admin/plans/${planId}`) // Note: Matches wildcard route moved to bottom, so it should be apiShow
                .then(response => {
                    if (!response.ok) throw new Error('Network response was not ok');
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        if (editBtn) editBtn.innerHTML = '<span style="margin-right: 6px;">✏️</span> Edit';
                        const plan = data.plan;
                        
                        document.getElementById('modalTitle').textContent = 'Edit Plan';
                        // Generate Edit Form
                        document.getElementById('planModalContent').innerHTML = `
                             <form id="planForm">
                                <input type="hidden" name="plan_id" value="${plan.id}">
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Plan Name</label>
                                        <input type="text" name="plan_name" value="${plan.plan_name}" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Price (₹)</label>
                                        <input type="number" name="price" step="0.01" value="${plan.price}" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Duration (Days)</label>
                                        <input type="number" name="duration_days" value="${plan.duration_days}" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Validity (Days)</label>
                                        <input type="number" name="validity_days" value="${plan.validity_days}" required style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                </div>

                                <div style="margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <h4 style="margin: 0 0 12px 0; font-size: 1rem; color: var(--text-primary);">Features</h4>
                                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
                                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                            <input type="checkbox" name="ad_free" value="1" ${plan.ad_free ? 'checked' : ''}> Ad Free
                                        </label>
                                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                            <input type="checkbox" name="has_analytics" value="1" ${plan.has_analytics ? 'checked' : ''}> Analytics
                                        </label>
                                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                            <input type="checkbox" name="verified_badge" value="1" ${plan.verified_badge ? 'checked' : ''}> Verified Badge
                                        </label>
                                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                            <input type="checkbox" name="vip_badge" value="1" ${plan.vip_badge ? 'checked' : ''}> VIP Badge
                                        </label>
                                    </div>
                                </div>

                                <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Post Limit</label>
                                        <input type="number" name="post_limit" value="${plan.post_limit || ''}" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Lead Limit</label>
                                        <input type="number" name="lead_limit" value="${plan.lead_limit || ''}" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Contact Limit (VIP Bypass)</label>
                                        <input type="number" name="contact_limit" value="${plan.contact_limit || ''}" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Unlimited">
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 4px;">Outgoing contacts allowed when seller limit is reached.</div>
                                    </div>
                                </div>
                                
                                <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Halo Effect (CSS)</label>
                                        <input type="text" name="halo_effect" value="${plan.halo_effect || ''}" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="e.g., 0 0 15px rgba(255, 215, 0, 0.5)">
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Ad Border (CSS)</label>
                                        <input type="text" name="ad_border" value="${plan.ad_border || ''}" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="e.g., 2px solid #FFD700">
                                    </div>
                                </div>

                                <div style="margin-top: 16px; padding: 16px; background: #fffbeb; border-radius: 8px; border: 1px solid #fcd34d;">
                                    <h4 style="margin: 0 0 12px 0; font-size: 1rem; color: #92400e;">Discount / Offer</h4>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                        <div>
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #92400e;">Discount Percentage (%)</label>
                                            <input type="number" name="discount_percentage" step="0.01" value="${plan.discount_percentage || ''}" placeholder="0" style="width: 100%; padding: 8px 12px; border: 1px solid #fcd34d; border-radius: 6px;">
                                        </div>
                                        <div>
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #92400e;">Fixed Discount (₹)</label>
                                            <input type="number" name="discount_fixed_amount" step="0.01" value="${plan.discount_fixed_amount || ''}" placeholder="0" style="width: 100%; padding: 8px 12px; border: 1px solid #fcd34d; border-radius: 6px;">
                                        </div>
                                        <div>
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #92400e;">Start Date</label>
                                            <input type="datetime-local" name="discount_start_date" value="${plan.discount_start_date ? plan.discount_start_date.substring(0, 16) : ''}" style="width: 100%; padding: 8px 12px; border: 1px solid #fcd34d; border-radius: 6px;">
                                        </div>
                                        <div>
                                            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #92400e;">End Date</label>
                                            <input type="datetime-local" name="discount_end_date" value="${plan.discount_end_date ? plan.discount_end_date.substring(0, 16) : ''}" style="width: 100%; padding: 8px 12px; border: 1px solid #fcd34d; border-radius: 6px;">
                                        </div>
                                    </div>
                                    <div style="margin-top: 8px; font-size: 0.75rem; color: #92400e;">
                                        * Enter either Percentage OR Fixed Amount. Percentage takes priority if both are set.
                                    </div>
                                </div>

                                <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Analytics Tier</label>
                                        <select name="analytics_tier" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                            <option value="basic" ${plan.analytics_tier === 'basic' ? 'selected' : ''}>Basic</option>
                                            <option value="advanced" ${plan.analytics_tier === 'advanced' ? 'selected' : ''}>Advanced</option>
                                            <option value="premium" ${plan.analytics_tier === 'premium' ? 'selected' : ''}>Premium</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Status</label>
                                        <select name="status" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                            <option value="Active" ${plan.status === 'Active' ? 'selected' : ''}>Active</option>
                                            <option value="Inactive" ${plan.status === 'Inactive' ? 'selected' : ''}>Inactive</option>
                                        </select>
                                    </div>
                                </div>

                                <div style="margin-top: 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Badge Style</label>
                                        <select name="badge_style" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                            <option value="vip_buyer" ${plan.badge_style === 'vip_buyer' ? 'selected' : ''}>VIP Buyer (Blue)</option>
                                            <option value="vip_pro" ${plan.badge_style === 'vip_pro' ? 'selected' : ''}>VIP Pro (Purple)</option>
                                            <option value="gold" ${plan.badge_style === 'gold' ? 'selected' : ''}>Gold</option>
                                            <option value="silver" ${plan.badge_style === 'silver' ? 'selected' : ''}>Silver</option>
                                            <option value="bronze" ${plan.badge_style === 'bronze' ? 'selected' : ''}>Bronze</option>
                                            <option value="platinum" ${plan.badge_style === 'platinum' ? 'selected' : ''}>Platinum</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Theme</label>
                                        <select name="theme" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                            <option value="standard" ${plan.theme === 'standard' ? 'selected' : ''}>Standard (Blue)</option>
                                            <option value="purple" ${plan.theme === 'purple' ? 'selected' : ''}>Purple (VIP Pro)</option>
                                            <option value="orange" ${plan.theme === 'orange' ? 'selected' : ''}>Orange</option>
                                            <option value="gold" ${plan.theme === 'gold' ? 'selected' : ''}>Gold</option>
                                            <option value="dark" ${plan.theme === 'dark' ? 'selected' : ''}>Dark Mode</option>
                                        </select>
                                    </div>
                                </div>

                                <div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
                                    <button type="button" onclick="closePlanModal()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Cancel</button>
                                    <button type="submit" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">Update Plan</button>
                                </div>
                            </form>
                        `;

                        document.getElementById('planModal').style.display = 'flex';
                        
                        document.getElementById('planForm').addEventListener('submit', function(e) {
                            e.preventDefault();
                            updatePlan(plan.id, new FormData(this));
                        });
                    } else {
                        if (editBtn) editBtn.innerHTML = '<span style="margin-right: 6px;">✏️</span> Edit';
                        alert('Failed to load plan data. Server returned success=false.');
                    }
                })
                .catch(error => {
                    if (editBtn) editBtn.innerHTML = '<span style="margin-right: 6px;">✏️</span> Edit';
                    console.error('Error loading plan data:', error);
                    alert('Failed to load plan data. Please try again.');
                });
        }

        function savePlan(formData) {
            // Convert FormData to JSON for API consistency
            const data = Object.fromEntries(formData.entries());
            // Checkboxes needing explicit boolean handling
            data.ad_free = formData.has('ad_free') ? 1 : 0;
            data.has_analytics = formData.has('has_analytics') ? 1 : 0;
            data.verified_badge = formData.has('verified_badge') ? 1 : 0;
            data.vip_badge = formData.has('vip_badge') ? 1 : 0;

            const btn = document.querySelector('#planForm button[type="submit"]');
            const originalText = btn.innerHTML;
            btn.textContent = 'Saving...';
            btn.disabled = true;

            fetch('/admin/plans/api-store', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Plan saved successfully!');
                    closePlanModal();
                    location.reload(); 
                } else {
                    alert('Failed to save plan: ' + data.message);
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error saving plan');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }

        function updatePlan(planId, formData) {
             // Convert FormData to JSON
            const data = Object.fromEntries(formData.entries());
             data.ad_free = formData.has('ad_free') ? 1 : 0;
            data.has_analytics = formData.has('has_analytics') ? 1 : 0;
            data.verified_badge = formData.has('verified_badge') ? 1 : 0;
            data.vip_badge =formData.has('vip_badge') ? 1 : 0;

            const btn = document.querySelector('#planForm button[type="submit"]');
            const originalText = btn.innerHTML;
            btn.textContent = 'Updating...';
            btn.disabled = true;

            fetch(`/admin/plans/api-update/${planId}`, {
                method: 'POST', // Using POST for update to avoid PUT payload issues sometimes with FormData/JSON parsing if not standard
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Plan updated successfully!');
                    closePlanModal();
                    location.reload();
                } else {
                    alert('Failed to update plan: ' + data.message);
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error updating plan:', error);
                alert('Failed to update plan.');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }

        function viewPlanAnalytics(planId) {
            fetch(`/admin/plans/${planId}/analytics`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const analytics = data.analytics;
                        document.getElementById('analyticsTitle').textContent = `Analytics: ${analytics.plan_name}`;
                        
                        // Determine growth color (green for positive, red for negative)
                        const growthColor = analytics.growth_rate.includes('+') ? '#10b981' : (analytics.growth_rate === '0%' ? '#64748b' : '#ef4444');

                        document.getElementById('analyticsContent').innerHTML = `
                            <div class="dashboard-grid">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 style="margin: 0;">Users & Growth</h4>
                                    </div>
                                    <div style="padding: 16px; text-align: center;">
                                        <div style="font-size: 2rem; font-weight: 700; color: var(--primary-color);">${analytics.total_users}</div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Total Users</div>
                                        <div style="margin-top: 8px; font-size: 0.8rem; color: ${growthColor}; font-weight: 600;">
                                            ${analytics.growth_rate} MoM
                                        </div>
                                    </div>
                                </div>
                                <div class="card">
                                    <div class="card-header">
                                        <h4 style="margin: 0;">Revenue</h4>
                                    </div>
                                    <div style="padding: 16px; text-align: center;">
                                        <div style="font-size: 2rem; font-weight: 700; color: #10b981;">₹${analytics.monthly_revenue}</div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Monthly Revenue</div>
                                    </div>
                                </div>
                                <div class="card">
                                    <div class="card-header">
                                        <h4 style="margin: 0;">Retention</h4>
                                    </div>
                                    <div style="padding: 16px; text-align: center;">
                                        <div style="font-size: 2rem; font-weight: 700; color: #3b82f6;">${analytics.retention_rate}</div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Retention Rate</div>
                                    </div>
                                </div>
                                <div class="card">
                                    <div class="card-header">
                                        <h4 style="margin: 0;">Churn Rate</h4>
                                    </div>
                                    <div style="padding: 16px; text-align: center;">
                                        <div style="font-size: 2rem; font-weight: 700; color: #ef4444;">${analytics.churn_rate}</div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Churn Rate</div>
                                    </div>
                                </div>
                            </div>
                        `;
                        document.getElementById('analyticsModal').style.display = 'flex';
                    }
                })
                .catch(error => console.error('Error loading analytics:', error));
        }

        function togglePlanStatus(planId, checkbox) {
            const originalState = !checkbox.checked; // State before click
            const statusText = document.getElementById(`status-text-${planId}`);
            
            // Disable to prevent multiple clicks
            checkbox.disabled = true;

            const action = checkbox.checked ? 'activate' : 'deactivate';
            const actionLabel = checkbox.checked ? 'Active' : 'Inactive';

            fetch(`/admin/plans/${planId}/toggle-status`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                checkbox.disabled = false;
                if (data.success) {
                    // Update Status Text
                    statusText.textContent = data.status;
                    statusText.style.color = data.status === 'Active' ? '#059669' : '#64748b';
                } else {
                    // Revert state
                    checkbox.checked = originalState;
                    alert('Failed to update plan status: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                checkbox.disabled = false;
                checkbox.checked = originalState;
                alert('Error updating status.');
            });
        }

        function deletePlan(planId) {
            console.log('deletePlan called for ID:', planId);
            if (confirm('Are you sure you want to delete this plan? This action cannot be undone.')) {
                
                const row = document.querySelector(`tr[data-plan-id="${planId}"]`);
                if (!row) {
                    console.error('Row not found for ID:', planId);
                    alert('Error: Could not find plan row in UI.');
                    return;
                }

                const btn = row.querySelector('button[onclick^="deletePlan"]');
                if (!btn) {
                    console.error('Delete button not found in row');
                    // Continue anyway, just can't show loading state on button
                } else {
                    var originalContent = btn.innerHTML;
                    btn.textContent = 'Wait...'; // Simplified loading text
                    btn.disabled = true;
                }

                console.log('Sending DELETE request to:', `/admin/plans/${planId}`);

                fetch(`/admin/plans/${planId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    console.log('Delete response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Delete response data:', data);
                    if (data.success) {
                        // Animate removal
                        row.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                        row.style.opacity = '0';
                        row.style.transform = 'translateX(20px)';
                        setTimeout(() => {
                            row.remove();
                        }, 500);
                    } else {
                        if (btn) {
                            btn.innerHTML = originalContent;
                            btn.disabled = false;
                        }
                        alert('Failed to delete plan: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Delete error:', error);
                    if (btn) {
                        btn.innerHTML = originalContent;
                        btn.disabled = false;
                    }
                    alert('Network or Server Error while deleting.');
                });
            }
        }

        function applyBulkAction() {
            const action = document.getElementById('bulkAction').value;
            const selected = Array.from(selectedPlans);
            
            if (selected.length === 0) {
                alert('Please select at least one plan.');
                return;
            }

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (confirm(`Are you sure you want to apply '${action}' to ${selected.length} plans?`)) {
                fetch('/admin/plans/bulk-action', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        action: action,
                        plan_ids: selected
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert('Failed to perform bulk action.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error performing bulk action.');
                });
            }
        }

        // Utility Functions
        function selectAllPlans() {
            const checkboxes = document.querySelectorAll('.plan-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = true;
                selectedPlans.add(parseInt(cb.dataset.planId));
            });
            document.getElementById('selectAllPlans').checked = true;
        }

        function clearSelection() {
            const checkboxes = document.querySelectorAll('.plan-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            selectedPlans.clear();
            document.getElementById('selectAllPlans').checked = false;
        }

        function exportPlans() {
             window.location.href = '/admin/plans/export';
        }

        function openRevenueReport() {
            // Check if analytics modal exists and reuse it or just show an alert if not implemented
            // Since we have `viewPlanAnalytics` which is per plan, this should normally be global analytics.
            // For now, let's redirect to the analytics page which exists in routes
            window.location.href = '/admin/analytics';
        }

        function openDiscountManager() {
            document.getElementById('discountModal').style.display = 'flex';
        }

        function applyDiscount() {
            // Mock implementation as discussed
            const type = document.getElementById('discountType').value;
            const selectedPlans = Array.from(document.querySelectorAll('input[name="plan_ids[]"]:checked')).map(cb => cb.value);
            
            alert(`Discount feature is currently in beta. Your selection (${type}) has been noted but not applied to the billing system yet.`);
            closeDiscountModal();
        }

        function toggleDefaultPlan(planId, button) {
            const originalText = button.innerHTML;
            button.textContent = '⏳ Loading...';
            button.disabled = true;

            fetch(`/admin/plans/${planId}/toggle-default`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Reload page to update all plan indicators
                    location.reload();
                } else {
                    button.innerHTML = originalText;
                    button.disabled = false;
                    alert('Failed to set default plan: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                button.innerHTML = originalText;
                button.disabled = false;
                alert('Error setting default plan.');
            });
        }

        // Modal Functions
        function closePlanModal() {
            document.getElementById('planModal').style.display = 'none';
        }

        function closeAnalyticsModal() {
            document.getElementById('analyticsModal').style.display = 'none';
        }


    </script>

    <style>
        /* Modal styles */
        .modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(2px);
        }

        .modal-content {
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border-color);
            max-width: 90vw;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideIn 0.3s ease-out;
            position: relative;
            margin: 0 auto;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* Status badges */
        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border: 1px solid transparent;
            transition: all 0.2s ease;
        }

        .status-active {
            background: linear-gradient(135deg, #dcfce7, #bbf7d0);
            color: #059669;
            border-color: #bbf7d0;
            box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2);
        }

        .status-inactive {
            background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
            color: #475569;
            border-color: #e2e8f0;
            box-shadow: 0 2px 4px rgba(71, 85, 105, 0.2);
        }

        /* Enhanced button styles */
        .btn-enhanced {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn-enhanced:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        .btn-enhanced:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .btn-analytics {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }

        .btn-analytics:hover {
            background: linear-gradient(135deg, #059669, #047857);
        }

        .btn-edit {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
        }

        .btn-edit:hover {
            background: linear-gradient(135deg, #2563eb, #1d4ed8);
        }

        .btn-toggle {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }

        .btn-toggle.active {
            background: linear-gradient(135deg, #10b981, #059669);
        }

        .btn-toggle:hover {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
        }

        .btn-toggle.active:hover {
            background: linear-gradient(135deg, #059669, #047857);
        }

        .btn-delete {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }

        .btn-delete:hover {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
        }

        /* Table row hover effects */
        tbody tr:hover {
            background-color: rgba(59, 130, 246, 0.05);
            transform: scale(1.001);
            transition: all 0.2s ease;
        }

        /* Feature tags styling */
        .feature-tag {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            color: #475569;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
            transition: all 0.2s ease;
        }

        .feature-tag:hover {
            background: #e2e8f0;
            border-color: #cbd5e1;
        }

        /* Toggle Switch Styles */
        .switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
            vertical-align: middle;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #cbd5e1;
            transition: .4s;
            border-radius: 20px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #10b981;
        }

        input:checked + .slider:before {
            transform: translateX(20px);
        }
    </style>
@endsection
