let currentSubscriptions = [];
let currentPlans = [];

function showSubscriptionTab(tabName) {
    document.querySelectorAll('#subscriptions .management-content').forEach(content => {
        content.classList.remove('active');
    });
    document.querySelectorAll('#subscriptions .management-tabs .tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    document.getElementById(tabName).classList.add('active');
    event.target.closest('.tab-btn').classList.add('active');
    
    if (tabName === 'subscriptions-list') {
        loadSubscriptions();
    } else if (tabName === 'subscription-plans') {
        loadPlans();
    } else if (tabName === 'subscription-stats') {
        loadRecentActivity();
    }
}

function loadSubscriptions() {
    const tbody = document.getElementById('subscriptionsTableBody');
    tbody.innerHTML = '<tr><td colspan="9" class="loading-state">Loading subscriptions...</td></tr>';
    
    fetch('subscriptions.php?action=get_subscriptions')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentSubscriptions = data.subscriptions;
                displaySubscriptions(data.subscriptions);
            } else {
                tbody.innerHTML = '<tr><td colspan="9" class="error-state">Failed to load subscriptions</td></tr>';
            }
        })
        .catch(error => {
            tbody.innerHTML = '<tr><td colspan="9" class="error-state">Error loading subscriptions</td></tr>';
            console.error('Error:', error);
        });
}

function displaySubscriptions(subscriptions) {
    const tbody = document.getElementById('subscriptionsTableBody');
    
    if (subscriptions.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" class="no-data">No subscriptions found</td></tr>';
        return;
    }
    
    tbody.innerHTML = subscriptions.map(sub => {
        const statusClass = sub.status === 'active' ? 'status-active' : 
                          sub.status === 'expired' ? 'status-expired' : 'status-cancelled';
        
        const daysLeft = Math.ceil((new Date(sub.end_date) - new Date()) / (1000 * 60 * 60 * 24));
        const daysLeftText = daysLeft > 0 ? `${daysLeft} days left` : 'Expired';
        const daysLeftColor = daysLeft <= 3 ? 'red' : daysLeft <= 7 ? 'orange' : 'green';
        
        return `
            <tr data-status="${sub.status}">
                <td>#${sub.id}</td>
                <td>${sub.customer_name || 'N/A'}</td>
                <td>${sub.plan_name}</td>
                <td>SAR ${parseFloat(sub.price).toFixed(2)}</td>
                <td>${formatDate(sub.start_date)}</td>
                <td>
                    ${formatDate(sub.end_date)}
                    ${sub.status === 'active' ? `<br><small style="color: ${daysLeftColor};">(${daysLeftText})</small>` : ''}
                </td>
                <td>${sub.usage_count || 0} / ${sub.max_usage}</td>
                <td>
                    <span class="status-badge ${statusClass}">
                        ${sub.status.charAt(0).toUpperCase() + sub.status.slice(1)}
                    </span>
                </td>
                <td>
                    <div class="staff-actions-small">
                        <button class="btn-small btn-edit" onclick="editSubscription(${sub.id})" title="Edit">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${sub.status === 'active' ? `
                        <button class="btn-small btn-warning" onclick="cancelSubscription(${sub.id})" title="Cancel">
                            <i class="fas fa-ban"></i>
                        </button>
                        ` : ''}
                        <button class="btn-small btn-delete" onclick="deleteSubscription(${sub.id}, '${sub.plan_name}')" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

function filterSubscriptions() {
    const status = document.getElementById('subscriptionStatusFilter').value;
    
    if (!status) {
        displaySubscriptions(currentSubscriptions);
        return;
    }
    
    const filtered = currentSubscriptions.filter(sub => sub.status === status);
    displaySubscriptions(filtered);
}

function openSubscriptionForm(id = null) {
    const modal = document.getElementById('subscriptionModal');
    const form = document.getElementById('subscriptionForm');
    const title = document.getElementById('subscriptionModalTitle');
    
    form.reset();
    loadCustomersForSelect();
    
    if (id) {
        title.textContent = 'Edit Subscription';
        fetch(`subscriptions.php?action=get_subscription&id=${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const sub = data.subscription;
                    document.getElementById('subscription_id').value = sub.id;
                    document.getElementById('subscription_user_id').value = sub.user_id;
                    document.getElementById('subscription_plan_name').value = sub.plan_name;
                    document.getElementById('subscription_price').value = sub.price;
                    document.getElementById('subscription_max_usage').value = sub.max_usage;
                    document.getElementById('subscription_start_date').value = sub.start_date;
                    document.getElementById('subscription_end_date').value = sub.end_date;
                    document.getElementById('subscription_status').value = sub.status;
                }
            });
    } else {
        title.textContent = 'Add New Subscription';
        document.getElementById('subscription_id').value = '';
        const today = new Date().toISOString().split('T')[0];
        const nextMonth = new Date();
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        document.getElementById('subscription_start_date').value = today;
        document.getElementById('subscription_end_date').value = nextMonth.toISOString().split('T')[0];
    }
    
    modal.style.display = 'flex';
}

function editSubscription(id) {
    openSubscriptionForm(id);
}

function cancelSubscription(id) {
    if (!confirm('Are you sure you want to cancel this subscription?')) return;
    
    const formData = new FormData();
    formData.append('action', 'cancel_subscription');
    formData.append('id', id);
    
    fetch('subscriptions.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadSubscriptions();
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('Failed to cancel subscription', 'error');
        console.error('Error:', error);
    });
}

function deleteSubscription(id, planName) {
    if (!confirm(`Are you sure you want to delete the subscription "${planName}"?`)) return;
    
    const formData = new FormData();
    formData.append('action', 'delete_subscription');
    formData.append('id', id);
    
    fetch('subscriptions.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadSubscriptions();
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('Failed to delete subscription', 'error');
        console.error('Error:', error);
    });
}

function closeSubscriptionModal() {
    document.getElementById('subscriptionModal').style.display = 'none';
}

document.addEventListener('DOMContentLoaded', function() {
    const subForm = document.getElementById('subscriptionForm');
    if (subForm) {
        subForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('subscriptions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    closeSubscriptionModal();
                    loadSubscriptions();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('Failed to save subscription', 'error');
                console.error('Error:', error);
            });
        });
    }
});

function loadPlans() {
    const grid = document.getElementById('plansGrid');
    grid.innerHTML = '<div class="loading-state">Loading plans...</div>';
    
    fetch('subscriptions.php?action=get_plans')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentPlans = data.plans;
                displayPlans(data.plans);
            } else {
                grid.innerHTML = '<div class="error-state">Failed to load plans</div>';
            }
        })
        .catch(error => {
            grid.innerHTML = '<div class="error-state">Error loading plans</div>';
            console.error('Error:', error);
        });
}

function displayPlans(plans) {
    const grid = document.getElementById('plansGrid');
    
    if (plans.length === 0) {
        grid.innerHTML = '<div class="no-data"><i class="fas fa-box-open"></i><p>No plans found</p></div>';
        return;
    }
    
    grid.innerHTML = plans.map(plan => {
        const features = plan.features ? plan.features.split('\n').filter(f => f.trim()) : [];
        
        return `
            <div class="plan-card plan-template">
                <div class="plan-header">
                    <h4>${plan.plan_name}</h4>
                    <span class="plan-badge">${plan.plan_type}</span>
                </div>
                <div class="plan-price">
                    <span class="price-amount">SAR ${parseFloat(plan.price).toFixed(2)}</span>
                    <span class="price-duration">/ ${plan.duration_days} days</span>
                </div>
                <div class="plan-details">
                    <p>${plan.description || 'No description'}</p>
                    <div class="plan-info">
                        <div><i class="fas fa-check-circle"></i> ${plan.max_usage} uses</div>
                        <div><i class="fas fa-calendar"></i> ${plan.duration_days} days</div>
                    </div>
                    ${features.length > 0 ? `
                    <div class="plan-features">
                        <h5>Features:</h5>
                        <ul>
                            ${features.map(f => `<li><i class="fas fa-check"></i> ${f}</li>`).join('')}
                        </ul>
                    </div>
                    ` : ''}
                </div>
                <div class="plan-actions">
                    <button class="btn btn-primary" onclick="editPlan(${plan.id})">
                        <i class="fas fa-edit"></i> Edit Plan
                    </button>
                </div>
            </div>
        `;
    }).join('');
}

function editPlan(id) {
    const modal = document.getElementById('planModal');
    const form = document.getElementById('planForm');
    const title = document.getElementById('planModalTitle');
    
    form.reset();
    title.textContent = 'Edit Subscription Plan';
    
    fetch(`subscriptions.php?action=get_plan&id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const plan = data.plan;
                document.getElementById('plan_id').value = plan.id;
                document.getElementById('plan_name').value = plan.plan_name;
                document.getElementById('plan_price_modifier').value = plan.price_modifier;
                document.getElementById('plan_base_price').value = plan.base_price;
                document.getElementById('plan_type_display').value = plan.plan_type;
                document.getElementById('plan_total_price').textContent = parseFloat(plan.price).toFixed(2);
            }
        });
    
    modal.style.display = 'flex';
}

function openPlanForm() {
    showNotification('Cannot add new plans. Only edit existing ones.', 'info');
}

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

function updatePlanTotalPrice() {
    const basePrice = parseFloat(document.getElementById('plan_base_price').value) || 0;
    const priceModifier = parseFloat(document.getElementById('plan_price_modifier').value) || 0;
    const totalPrice = basePrice + priceModifier;
    document.getElementById('plan_total_price').textContent = totalPrice.toFixed(2);
}

document.addEventListener('DOMContentLoaded', function() {
    const planForm = document.getElementById('planForm');
    if (planForm) {
        planForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('subscriptions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    closePlanModal();
                    loadPlans();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('Failed to save plan', 'error');
                console.error('Error:', error);
            });
        });
        
        const priceModifierInput = document.getElementById('plan_price_modifier');
        if (priceModifierInput) {
            priceModifierInput.addEventListener('input', updatePlanTotalPrice);
        }
    }
});

function loadRecentActivity() {
    const container = document.getElementById('recentActivity');
    container.innerHTML = '<div class="loading-state">Loading activity...</div>';
    
    fetch('subscriptions.php?action=get_activity')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayActivity(data.activity);
            } else {
                container.innerHTML = '<div class="error-state">Failed to load activity</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="error-state">Error loading activity</div>';
            console.error('Error:', error);
        });
}

function displayActivity(activity) {
    const container = document.getElementById('recentActivity');
    
    if (activity.length === 0) {
        container.innerHTML = '<div class="no-data">No recent activity</div>';
        return;
    }
    
    container.innerHTML = `
        <table class="activity-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Customer</th>
                    <th>Plan</th>
                    <th>Action</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                ${activity.map(act => `
                    <tr>
                        <td>${formatDate(act.created_at)}</td>
                        <td>${act.customer_name || 'N/A'}</td>
                        <td>${act.plan_name}</td>
                        <td>${act.action}</td>
                        <td><span class="status-badge status-${act.status}">${act.status}</span></td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

function loadCustomersForSelect() {
    fetch('subscriptions.php?action=get_customers')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('subscription_user_id');
                select.innerHTML = '<option value="">Select Customer</option>' +
                    data.customers.map(c => `<option value="${c.id}">${c.name} (${c.email})</option>`).join('');
            }
        });
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB');
}

document.addEventListener('DOMContentLoaded', function() {
    const subscriptionsNav = document.querySelector('[data-section="subscriptions"]');
    if (subscriptionsNav) {
        subscriptionsNav.addEventListener('click', function() {
            setTimeout(() => {
                loadSubscriptions();
            }, 100);
        });
    }
});
