<?php
/**
 * Subscription Management Page for Existing Admin Panel
 */
require_once 'config.php';

// Check admin authentication
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();

// Get database connection
$pdo = getDBConnection();

// Get filter
$statusFilter = $_GET['status'] ?? 'all';

// Build query based on filter
$whereClause = "WHERE 1=1";
if ($statusFilter !== 'all') {
    $whereClause .= " AND s.status = " . $pdo->quote($statusFilter);
}

// Get subscriptions
$query = "
    SELECT 
        s.id as subscription_id,
        s.status,
        s.payment_method,
        s.amount_paid,
        s.start_date,
        s.end_date,
        s.created_at,
        DATEDIFF(s.end_date, NOW()) as days_remaining,
        u.id as user_id,
        u.email,
        u.user_name,
        COALESCE(u.full_name, u.user_name, u.email) as display_name,
        p.package_name,
        p.duration_months
    FROM user_subscriptions s
    JOIN users u ON s.user_id = u.id
    JOIN subscription_packages p ON s.package_id = p.id
    $whereClause
    ORDER BY s.created_at DESC
    LIMIT 100
";

$stmt = $pdo->query($query);
$subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$statsQuery = "
    SELECT 
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_count,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
        COUNT(CASE WHEN status = 'expired' THEN 1 END) as expired_count,
        SUM(CASE WHEN status = 'active' THEN amount_paid ELSE 0 END) as active_revenue,
        SUM(CASE WHEN status = 'pending' THEN amount_paid ELSE 0 END) as pending_revenue
    FROM user_subscriptions
";
$stats = $pdo->query($statsQuery)->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscriptions - Admin Panel</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h1>💳 Subscription Management</h1>
        </div>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">✅</div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['active_count']); ?></h3>
                    <p>Active Subscriptions</p>
                    <small style="color: #10b981;">Rs <?php echo number_format($stats['active_revenue'], 2); ?></small>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">⏳</div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['pending_count']); ?></h3>
                    <p>Pending</p>
                    <small style="color: #f59e0b;">Rs <?php echo number_format($stats['pending_revenue'], 2); ?></small>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">⏰</div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['expired_count']); ?></h3>
                    <p>Expired</p>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">💰</div>
                <div class="stat-content">
                    <h3>Rs <?php echo number_format($stats['active_revenue'] + $stats['pending_revenue'], 2); ?></h3>
                    <p>Total Revenue</p>
                </div>
            </div>
        </div>

        <!-- Filter -->
        <div class="filter-tabs" style="margin: 30px 0;">
            <a href="?status=all" class="filter-tab <?php echo $statusFilter === 'all' ? 'active' : ''; ?>">
                All
            </a>
            <a href="?status=active" class="filter-tab <?php echo $statusFilter === 'active' ? 'active' : ''; ?>">
                Active (<?php echo $stats['active_count']; ?>)
            </a>
            <a href="?status=pending" class="filter-tab <?php echo $statusFilter === 'pending' ? 'active' : ''; ?>">
                Pending (<?php echo $stats['pending_count']; ?>)
            </a>
            <a href="?status=expired" class="filter-tab <?php echo $statusFilter === 'expired' ? 'active' : ''; ?>">
                Expired (<?php echo $stats['expired_count']; ?>)
            </a>
        </div>

        <!-- Subscriptions Table -->
        <div class="content-card">
            <div class="card-header">
                <h2>📋 Subscriptions</h2>
            </div>
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Package</th>
                            <th>Amount</th>
                            <th>Payment</th>
                            <th>Status</th>
                            <th>Start Date</th>
                            <th>End Date</th>
                            <th>Days Left</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($subscriptions)): ?>
                            <tr>
                                <td colspan="10" style="text-align: center; padding: 40px;">No subscriptions found</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($subscriptions as $sub): ?>
                                <tr>
                                    <td><?php echo $sub['subscription_id']; ?></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($sub['display_name']); ?></strong><br>
                                        <small style="color: #666;"><?php echo htmlspecialchars($sub['email']); ?></small>
                                    </td>
                                    <td><?php echo htmlspecialchars($sub['package_name']); ?></td>
                                    <td>Rs <?php echo number_format($sub['amount_paid'], 2); ?></td>
                                    <td>
                                        <?php if ($sub['payment_method'] === 'bank_transfer'): ?>
                                            <span class="badge badge-info">Bank</span>
                                        <?php else: ?>
                                            <span class="badge badge-primary">Card</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $badgeClass = [
                                            'active' => 'badge-success',
                                            'pending' => 'badge-warning',
                                            'expired' => 'badge-secondary',
                                            'cancelled' => 'badge-danger'
                                        ][$sub['status']] ?? 'badge-secondary';
                                        ?>
                                        <span class="badge <?php echo $badgeClass; ?>">
                                            <?php echo ucfirst($sub['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo $sub['start_date'] ? date('Y-m-d', strtotime($sub['start_date'])) : '-'; ?></td>
                                    <td><?php echo $sub['end_date'] ? date('Y-m-d', strtotime($sub['end_date'])) : '-'; ?></td>
                                    <td>
                                        <?php if ($sub['status'] === 'active' && $sub['days_remaining'] !== null): ?>
                                            <?php if ($sub['days_remaining'] > 7): ?>
                                                <span style="color: #10b981;"><?php echo $sub['days_remaining']; ?> days</span>
                                            <?php elseif ($sub['days_remaining'] > 0): ?>
                                                <span style="color: #f59e0b;"><?php echo $sub['days_remaining']; ?> days</span>
                                            <?php else: ?>
                                                <span style="color: #ef4444;">Expired</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="users.php?id=<?php echo $sub['user_id']; ?>" class="action-btn" title="View User">
                                            👤
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
