<?php include 'app/include/header.php'; ?>

<!-- Display Success/Error Messages -->
<?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bx bx-check-circle me-2"></i>
        <?= htmlspecialchars($_SESSION['success']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bx bx-error me-2"></i>
        <?= htmlspecialchars($_SESSION['error']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

<!-- Subscription Collection Dashboard -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between">
            <h4 class="mb-sm-0 font-size-18">Subscription Plans Management</h4>
            <div class="page-title-right">
                <button type="button" class="btn btn-primary" onclick="showAddPlanDialog()">
                    <i class="bx bx-plus me-1"></i> Add New Plan
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Dashboard Cards -->
<div class="row">
    <?php
    try {
        // Get subscription statistics
        $stats_query = "
            SELECT 
                COUNT(*) as total_accounts,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_accounts,
                SUM(CASE WHEN subscription_end < NOW() THEN 1 ELSE 0 END) as expired_accounts,
                SUM(CASE WHEN subscription_end > NOW() THEN 1 ELSE 0 END) as active_subscriptions
            FROM isp_accounts
        ";
        $stats_stmt = $conn->prepare($stats_query);
        $stats_stmt->execute();
        $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

        // Get revenue statistics
        $revenue_query = "
            SELECT 
                SUM(sp.price) as total_revenue,
                SUM(CASE WHEN ia.subscription_end > NOW() THEN sp.price ELSE 0 END) as active_revenue,
                COUNT(DISTINCT sp.id) as total_plans
            FROM isp_accounts ia
            LEFT JOIN subscription_plans sp ON ia.subscription_plan_id = sp.id
            WHERE ia.subscription_plan_id IS NOT NULL
        ";
        $revenue_stmt = $conn->prepare($revenue_query);
        $revenue_stmt->execute();
        $revenue = $revenue_stmt->fetch(PDO::FETCH_ASSOC);

        // Get monthly growth
        $monthly_query = "
            SELECT COUNT(*) as new_accounts
            FROM isp_accounts 
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
        ";
        $monthly_stmt = $conn->prepare($monthly_query);
        $monthly_stmt->execute();
        $monthly_stats = $monthly_stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Set default values if queries fail
        $stats = ['total_accounts' => 0, 'active_accounts' => 0, 'expired_accounts' => 0, 'active_subscriptions' => 0];
        $revenue = ['total_revenue' => 0, 'active_revenue' => 0, 'total_plans' => 0];
        $monthly_stats = ['new_accounts' => 0];
        error_log("Dashboard stats error: " . $e->getMessage());
    }
    ?>
    
    <div class="col-xl-3 col-md-6">
        <div class="card card-h-100">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-6">
                        <span class="text-muted mb-3 lh-1 d-block text-truncate">Total Accounts</span>
                        <h4 class="mb-3">
                            <span class="counter-value" data-target="<?= $stats['total_accounts'] ?? 0 ?>">
                                <?= number_format($stats['total_accounts'] ?? 0) ?>
                            </span>
                        </h4>
                    </div>
                    <div class="col-6">
                        <div class="text-end">
                            <div class="bg-primary bg-soft text-primary rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                                <i class="bx bx-user text-primary" style="font-size: 24px;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card card-h-100">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-6">
                        <span class="text-muted mb-3 lh-1 d-block text-truncate">Active Subscriptions</span>
                        <h4 class="mb-3">
                            <span class="counter-value" data-target="<?= $stats['active_subscriptions'] ?? 0 ?>">
                                <?= number_format($stats['active_subscriptions'] ?? 0) ?>
                            </span>
                        </h4>
                    </div>
                    <div class="col-6">
                        <div class="text-end">
                            <div class="bg-success bg-soft text-success rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                                <i class="bx bx-check-circle text-success" style="font-size: 24px;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card card-h-100">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-6">
                        <span class="text-muted mb-3 lh-1 d-block text-truncate">Total Revenue</span>
                        <h4 class="mb-3">
                            <span class="counter-value">
                                <?= htmlspecialchars($currentSettings['currency_symbol']).' '.number_format($revenue['total_revenue'] ?? 0, 2) ?>
                            </span>
                        </h4>
                    </div>
                    <div class="col-6">
                        <div class="text-end">
                            <div class="bg-warning bg-soft text-warning rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                                <i class="bx bx-dollar text-warning" style="font-size: 24px;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card card-h-100">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-6">
                        <span class="text-muted mb-3 lh-1 d-block text-truncate">Monthly Growth</span>
                        <h4 class="mb-3">
                            <span class="counter-value" data-target="<?= $monthly_stats['new_accounts'] ?? 0 ?>">
                                <?= number_format($monthly_stats['new_accounts'] ?? 0) ?>
                            </span>
                        </h4>
                    </div>
                    <div class="col-6">
                        <div class="text-end">
                            <div class="bg-info bg-soft text-info rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                                <i class="bx bx-trending-up text-info" style="font-size: 24px;"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Subscription Plans Table -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Available Subscription Plans</h4>
            </div>
            <div class="card-body">
                <?php
                try {
                    // Fetch all subscription plans
                    $query = "SELECT * FROM subscription_plans ORDER BY created_at DESC";
                    $stmt = $conn->prepare($query);
                    $stmt->execute();
                    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e) {
                    $plans = [];
                    error_log("Subscription plans query error: " . $e->getMessage());
                    echo '<div class="alert alert-warning">Error loading subscription plans. Please check your database connection.</div>';
                }
                ?>

                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Plan Name</th>
                                <th>Price</th>
                                <th>Duration</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($plans)): ?>
                                <?php foreach ($plans as $plan): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($plan['name']) ?></strong>
                                            <?php if (!empty($plan['description'])): ?>
                                                <br><small class="text-muted"><?= htmlspecialchars($plan['description']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= htmlspecialchars($currentSettings['currency_symbol']).' '.number_format($plan['price'], 2) ?></td>
                                        <td><?= $plan['duration_days'] ?> days</td>
                                        <td>
                                            <span class="badge <?= $plan['status'] === 'active' ? 'bg-success' : 'bg-warning' ?>">
                                                <?= ucfirst($plan['status']) ?>
                                            </span>
                                        </td>
                                        <td><?= date('M d, Y', strtotime($plan['created_at'])) ?></td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-outline-primary"
                                                    onclick="showEditPlanDialog(<?= htmlspecialchars(json_encode($plan)) ?>)">
                                                    <i class="bx bx-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-danger"
                                                    onclick="deletePlan(<?= $plan['id'] ?>, '<?= htmlspecialchars($plan['name']) ?>')">
                                                    <i class="bx bx-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center">No subscription plans found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ISP Users Assignment -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">ISP Users & Plan Assignments</h4>
            </div>
            <div class="card-body">
                <?php
                try {
                    // Fixed query for ISP accounts with proper table structure
                    $query = "SELECT 
                        ia.id, 
                        ia.username, 
                        ia.email, 
                        ia.company_name, 
                        ia.phone,
                        ia.status as account_status,
                        ia.subscription_start, 
                        ia.subscription_end,
                        ia.subscription_plan_id,
                        ia.created_at,
                        sp.name AS current_plan_name,
                        sp.price AS plan_price,
                        sp.duration_days
                    FROM isp_accounts ia
                    LEFT JOIN subscription_plans sp ON ia.subscription_plan_id = sp.id
                    ORDER BY ia.created_at DESC";
                    
                    $stmt = $conn->prepare($query);
                    $stmt->execute();
                    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e) {
                    $users = [];
                    error_log("ISP accounts query error: " . $e->getMessage());
                    echo '<div class="alert alert-warning">Error loading ISP accounts. Please check your database connection.</div>';
                }
                ?>

                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ISP Account</th>
                                <th>Company</th>
                                <th>Phone</th>
                                <th>Current Plan</th>
                                <th>Subscription Period</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($users)): ?>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($user['username']) ?></strong>
                                            <br><small class="text-muted"><?= htmlspecialchars($user['email']) ?></small>
                                        </td>
                                        <td><?= htmlspecialchars($user['company_name'] ?? 'N/A') ?></td>
                                        <td><?= htmlspecialchars($user['phone'] ?? 'N/A') ?></td>
                                        <td>
                                            <?php if ($user['current_plan_name']): ?>
                                                <span class="badge bg-info"><?= htmlspecialchars($user['current_plan_name']) ?></span>
                                                <br><small class="text-muted">$<?= number_format($user['plan_price'] ?? 0, 2) ?></small>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">No Plan</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($user['subscription_start'] && $user['subscription_end']): ?>
                                                <strong><?= date('M d, Y', strtotime($user['subscription_start'])) ?></strong><br>
                                                <small class="text-muted">to <?= date('M d, Y', strtotime($user['subscription_end'])) ?></small>
                                            <?php else: ?>
                                                <span class="text-muted">Not set</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            $status = 'active';
                                            $status_class = 'bg-success';
                                            
                                            if ($user['account_status'] !== 'active') {
                                                $status = $user['account_status'];
                                                $status_class = 'bg-warning';
                                            } elseif ($user['subscription_end'] && strtotime($user['subscription_end']) < time()) {
                                                $status = 'expired';
                                                $status_class = 'bg-danger';
                                            }
                                            ?>
                                            <span class="badge <?= $status_class ?>">
                                                <?= ucfirst($status) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-primary"
                                                    onclick="assignPlan(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')">
                                                    <i class="bx bx-user-check me-1"></i> Assign Plan
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-info"
                                                    onclick="viewAccount(<?= $user['id'] ?>)">
                                                    <i class="bx bx-show"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center">No ISP accounts found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- Assign Plan Modal -->
<div class="modal fade" id="assignPlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assign Subscription Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="?app_route=subscription_plans_assign" method="POST">
                <input type="hidden" name="user_id" id="assign_user_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">ISP Account</label>
                        <input type="text" class="form-control" id="assign_username" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Select Plan *</label>
                        <select class="form-select" name="plan_id" required>
                            <option value="">Choose a plan...</option>
                            <?php foreach ($plans as $plan): ?>
                                <option value="<?= $plan['id'] ?>" data-price="<?= $plan['price'] ?>" data-duration="<?= $plan['duration_days'] ?>">
                                    <?= htmlspecialchars($plan['name']) ?> - $<?= number_format($plan['price'], 2) ?>
                                    (<?= $plan['duration_days'] ?> days)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Start Date</label>
                        <input type="date" class="form-control" name="start_date" value="<?= date('Y-m-d') ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">End Date</label>
                        <input type="date" class="form-control" name="end_date" id="assign_end_date" readonly>
                        <small class="text-muted">Automatically calculated based on plan duration</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">Assign Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    function showAddPlanDialog() {
        Swal.fire({
            title: 'Add New Subscription Plan',
            html: `
                <form id="addPlanForm" class="text-start">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Plan Name *</label>
                                <input type="text" class="form-control" name="plan_name" id="swal_plan_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Price (<?= htmlspecialchars($currentSettings['currency_symbol']) ?>)</label>
                                <input type="number" class="form-control" name="price" id="swal_price" step="0.01" value="0">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Duration (Days)</label>
                                <input type="number" class="form-control" name="duration_days" id="swal_duration" value="30">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Subscription Model</label>
                                <select class="form-select" name="subscription_model" id="swal_model">
                                    <option value="monthly">Monthly</option>
                                    <option value="yearly">Yearly</option>
                                    <option value="one-time">One-time</option>
                                    <option value="custom">Custom</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="swal_status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="swal_description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Features *</label>
                        <textarea class="form-control" name="features" id="swal_features" rows="3" placeholder="List key features, one per line" required></textarea>
                    </div>
                </form>
            `,
            width: '800px',
            showCancelButton: true,
            confirmButtonText: '<i class="bx bx-plus me-1"></i> Create Plan',
            cancelButtonText: '<i class="bx bx-x me-1"></i> Cancel',
            focusConfirm: false,
            preConfirm: () => {
                const planName = document.getElementById('swal_plan_name').value;
                const features = document.getElementById('swal_features').value;
                
                if (!planName.trim()) {
                    Swal.showValidationMessage('Plan name is required');
                    return false;
                }
                
                if (!features.trim()) {
                    Swal.showValidationMessage('Features are required');
                    return false;
                }
                
                return {
                    plan_name: planName,
                    price: document.getElementById('swal_price').value,
                    duration_days: document.getElementById('swal_duration').value,
                    subscription_model: document.getElementById('swal_model').value,
                    status: document.getElementById('swal_status').value,
                    description: document.getElementById('swal_description').value,
                    features: features
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Creating Plan...',
                    text: 'Please wait while we create the subscription plan.',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Create and submit form
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '?app_route=subscription_plans_create';
                
                Object.keys(result.value).forEach(key => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = result.value[key];
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
            }
        });
    }

    function showEditPlanDialog(plan) {
        Swal.fire({
            title: 'Edit Subscription Plan',
            html: `
                <form id="editPlanForm" class="text-start">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Plan Name *</label>
                                <input type="text" class="form-control" name="plan_name" id="edit_plan_name" value="${plan.name}" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Price (<?= htmlspecialchars($currentSettings['currency_symbol']) ?>)</label>
                                <input type="number" class="form-control" name="price" id="edit_price" step="0.01" value="${plan.price}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Duration (Days)</label>
                                <input type="number" class="form-control" name="duration_days" id="edit_duration" value="${plan.duration_days}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Subscription Model</label>
                                <select class="form-select" name="subscription_model" id="edit_model">
                                    <option value="monthly" ${plan.subscription_model === 'monthly' ? 'selected' : ''}>Monthly</option>
                                    <option value="yearly" ${plan.subscription_model === 'yearly' ? 'selected' : ''}>Yearly</option>
                                    <option value="one-time" ${plan.subscription_model === 'one-time' ? 'selected' : ''}>One-time</option>
                                    <option value="custom" ${plan.subscription_model === 'custom' ? 'selected' : ''}>Custom</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="edit_status">
                            <option value="active" ${plan.status === 'active' ? 'selected' : ''}>Active</option>
                            <option value="inactive" ${plan.status === 'inactive' ? 'selected' : ''}>Inactive</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="edit_description" rows="3">${plan.description || ''}</textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Features *</label>
                        <textarea class="form-control" name="features" id="edit_features" rows="3" required>${plan.features || ''}</textarea>
                    </div>
                </form>
            `,
            width: '800px',
            showCancelButton: true,
            confirmButtonText: '<i class="bx bx-check me-1"></i> Update Plan',
            cancelButtonText: '<i class="bx bx-x me-1"></i> Cancel',
            focusConfirm: false,
            preConfirm: () => {
                const planName = document.getElementById('edit_plan_name').value;
                const features = document.getElementById('edit_features').value;
                
                if (!planName.trim()) {
                    Swal.showValidationMessage('Plan name is required');
                    return false;
                }
                
                if (!features.trim()) {
                    Swal.showValidationMessage('Features are required');
                    return false;
                }
                
                return {
                    plan_id: plan.id,
                    plan_name: planName,
                    price: document.getElementById('edit_price').value,
                    duration_days: document.getElementById('edit_duration').value,
                    subscription_model: document.getElementById('edit_model').value,
                    status: document.getElementById('edit_status').value,
                    description: document.getElementById('edit_description').value,
                    features: features
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Updating Plan...',
                    text: 'Please wait while we update the subscription plan.',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Create and submit form
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '?app_route=subscription_plans_update';
                
                Object.keys(result.value).forEach(key => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = result.value[key];
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
            }
        });
    }

    function deletePlan(planId, planName) {
        Swal.fire({
            title: 'Delete Subscription Plan',
            html: `Are you sure you want to delete the plan <strong>"${planName}"</strong>?<br><br>This action cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bx bx-trash me-1"></i> Yes, Delete Plan',
            cancelButtonText: '<i class="bx bx-x me-1"></i> Cancel',
            focusCancel: true
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Deleting...',
                    text: 'Please wait while we delete the subscription plan.',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Redirect to delete
                window.location.href = `?app_route=subscription_plans_delete&id=${planId}`;
            }
        });
    }
    
    function editPlan(plan) {
        // Legacy function for backward compatibility - redirect to new SweetAlert function
        showEditPlanDialog(plan);
    }

    function assignPlan(userId, username) {
        document.getElementById('assign_user_id').value = userId;
        document.getElementById('assign_username').value = username;

        // Add event listener for plan selection
        const planSelect = document.querySelector('select[name="plan_id"]');
        const startDateInput = document.querySelector('input[name="start_date"]');
        const endDateInput = document.getElementById('assign_end_date');

        function updateEndDate() {
            const selectedOption = planSelect.options[planSelect.selectedIndex];
            const duration = selectedOption.getAttribute('data-duration');
            const startDate = new Date(startDateInput.value);
            
            if (duration && startDate) {
                const endDate = new Date(startDate);
                endDate.setDate(endDate.getDate() + parseInt(duration));
                endDateInput.value = endDate.toISOString().split('T')[0];
            }
        }

        planSelect.addEventListener('change', updateEndDate);
        startDateInput.addEventListener('change', updateEndDate);

        // Initialize end date
        updateEndDate();

        new bootstrap.Modal(document.getElementById('assignPlanModal')).show();
    }

    function viewAccount(accountId) {
        // Redirect to account details page or show modal with account details
        window.location.href = '?app_route=accounts&action=view&id=' + accountId;
    }

    // Initialize counter animations
    document.addEventListener('DOMContentLoaded', function() {
        const counters = document.querySelectorAll('.counter-value');
        counters.forEach(counter => {
            const target = parseInt(counter.getAttribute('data-target') || counter.textContent.replace(/[^\d]/g, ''));
            const duration = 2000; // 2 seconds
            const increment = target / (duration / 16); // 60fps
            let current = 0;

            const updateCounter = () => {
                if (current < target) {
                    current += increment;
                    if (current > target) current = target;
                    
                    // Format the number properly
                    const formatted = Math.floor(current).toLocaleString();
                    if (counter.textContent.includes('$')) {
                        counter.textContent = '$' + formatted + (target >= 100 ? '.00' : '');
                    } else {
                        counter.textContent = formatted;
                    }
                    
                    requestAnimationFrame(updateCounter);
                }
            };

            // Start animation when element is visible
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        updateCounter();
                        observer.unobserve(entry.target);
                    }
                });
            });

            observer.observe(counter);
        });
    });
</script>

<style>
    .card-h-100 {
        height: 100%;
    }
    
    .counter-value {
        font-weight: 600;
        color: #495057;
    }
    
    .bg-soft {
        background-color: rgba(var(--bs-primary-rgb), 0.1) !important;
    }
    
    .bg-success.bg-soft {
        background-color: rgba(var(--bs-success-rgb), 0.1) !important;
    }
    
    .bg-warning.bg-soft {
        background-color: rgba(var(--bs-warning-rgb), 0.1) !important;
    }
    
    .bg-info.bg-soft {
        background-color: rgba(var(--bs-info-rgb), 0.1) !important;
    }
    
    .table th {
        background-color: #f8f9fa;
        border-top: none;
        font-weight: 600;
    }
    
    .badge {
        font-size: 0.75rem;
    }
    
    .btn-group .btn {
        border-radius: 0.375rem;
        margin-right: 0.25rem;
    }
    
    .btn-group .btn:last-child {
        margin-right: 0;
    }
    
    .modal-header {
        border-bottom: 1px solid #dee2e6;
        padding: 1rem 1.5rem;
    }
    
    .modal-footer {
        border-top: 1px solid #dee2e6;
        padding: 1rem 1.5rem;
    }
    
    .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .text-muted {
        color: #6c757d !important;
    }
    
    .card-title {
        font-size: 1.125rem;
        font-weight: 600;
        margin-bottom: 1rem;
    }
    
    .dashboard-stats {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 0.5rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .dashboard-stats h2 {
        margin: 0;
        font-size: 2rem;
        font-weight: 700;
    }
    
    .dashboard-stats p {
        margin: 0.5rem 0 0 0;
        opacity: 0.9;
    }
</style>

<?php include 'app/include/footer.php'; ?>