<?php
/**
 * Subscriptions List
 * LandSales Pro - View all subscriptions
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';

initSecureSession();
requireRole(['super_admin', 'admin']);

// Filters
$statusFilter = $_GET['status'] ?? 'all';
$planFilter = $_GET['plan'] ?? 'all';

// Build query
$whereClause = "WHERE 1=1";
$params = [];
$types = '';

if ($statusFilter !== 'all') {
    $whereClause .= " AND s.status = ?";
    $params[] = $statusFilter;
    $types .= 's';
}

if ($planFilter !== 'all') {
    $whereClause .= " AND s.plan_id = ?";
    $params[] = intval($planFilter);
    $types .= 'i';
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$countSql = "SELECT COUNT(*) as total FROM subscriptions s {$whereClause}";
$total = empty($params) ? db_fetch_one($countSql)['total'] : db_fetch_one($countSql, $types, $params)['total'];
$totalPages = ceil($total / $perPage);

$sql = "SELECT s.*, u.full_name, u.email, u.phone, p.name as plan_name, p.slug as plan_slug
        FROM subscriptions s
        JOIN users u ON s.user_id = u.id
        JOIN plans p ON s.plan_id = p.id
        {$whereClause}
        ORDER BY s.created_at DESC
        LIMIT {$perPage} OFFSET {$offset}";

$subscriptions = empty($params) ? db_fetch_all($sql) : db_fetch_all($sql, $types, $params);

// Get plans for filter
$plans = db_fetch_all("SELECT * FROM plans WHERE is_active = 1 ORDER BY sort_order");

// Stats
$activeCount = db_fetch_one("SELECT COUNT(*) as c FROM subscriptions WHERE status = 'active'")['c'];
$trialCount = db_fetch_one("SELECT COUNT(*) as c FROM subscriptions WHERE status = 'trial'")['c'];
$expiredCount = db_fetch_one("SELECT COUNT(*) as c FROM subscriptions WHERE status = 'expired'")['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscriptions - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Subscriptions</h1>
            <div class="header-actions">
                <a href="record-payment.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Record Payment
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Stats -->
            <div class="stats-row">
                <div class="stat-mini gradient-green">
                    <i class="fas fa-check-circle"></i>
                    <div>
                        <div class="stat-value"><?php echo $activeCount; ?></div>
                        <div class="stat-label">Active</div>
                    </div>
                </div>
                <div class="stat-mini gradient-blue">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value"><?php echo $trialCount; ?></div>
                        <div class="stat-label">Trial</div>
                    </div>
                </div>
                <div class="stat-mini gradient-red">
                    <i class="fas fa-times-circle"></i>
                    <div>
                        <div class="stat-value"><?php echo $expiredCount; ?></div>
                        <div class="stat-label">Expired</div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form class="filters-form" method="GET">
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" class="form-control" onchange="this.form.submit()">
                            <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="trial" <?php echo $statusFilter === 'trial' ? 'selected' : ''; ?>>Trial</option>
                            <option value="expired" <?php echo $statusFilter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                            <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Plan</label>
                        <select name="plan" class="form-control" onchange="this.form.submit()">
                            <option value="all">All Plans</option>
                            <?php foreach ($plans as $plan): ?>
                            <option value="<?php echo $plan['id']; ?>" <?php echo $planFilter == $plan['id'] ? 'selected' : ''; ?>>
                                <?php echo $plan['name']; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Subscriber</th>
                                <th>Plan</th>
                                <th>Billing</th>
                                <th>Status</th>
                                <th>Expires</th>
                                <th>Amount</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($subscriptions)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-credit-card"></i>
                                        <p>No subscriptions found</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($subscriptions as $sub): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar">
                                            <?php echo strtoupper(substr($sub['full_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="user-name"><?php echo htmlspecialchars($sub['full_name']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($sub['email']); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="plan-badge plan-<?php echo $sub['plan_slug']; ?>">
                                        <?php echo $sub['plan_name']; ?>
                                    </span>
                                </td>
                                <td><?php echo ucfirst(str_replace('_', ' ', $sub['billing_cycle'])); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $sub['status']; ?>">
                                        <?php echo ucfirst($sub['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                    $expires = strtotime($sub['expires_at']);
                                    $daysLeft = ceil(($expires - time()) / 86400);
                                    $class = $sub['status'] === 'expired' ? 'text-danger' : ($daysLeft <= 7 ? 'text-warning' : '');
                                    ?>
                                    <span class="<?php echo $class; ?>">
                                        <?php echo date('M j, Y', $expires); ?>
                                    </span>
                                </td>
                                <td>TZS <?php echo number_format($sub['amount']); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="record-payment.php?user_id=<?php echo $sub['user_id']; ?>" class="btn-icon" title="Record Payment">
                                            <i class="fas fa-money-bill-wave"></i>
                                        </a>
                                        <a href="../subscribers/view.php?id=<?php echo $sub['user_id']; ?>" class="btn-icon" title="View Subscriber">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $statusFilter; ?>&plan=<?php echo $planFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&status=<?php echo $statusFilter; ?>&plan=<?php echo $planFilter; ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $statusFilter; ?>&plan=<?php echo $planFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions { display: flex; gap: 0.75rem; }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .stats-row {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-mini {
            flex: 1;
            padding: 1rem 1.25rem;
            border-radius: 12px;
            color: white;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .stat-mini i { font-size: 1.5rem; opacity: 0.9; }
        .stat-mini .stat-value { font-size: 1.5rem; font-weight: 700; }
        .stat-mini .stat-label { font-size: 0.8rem; opacity: 0.9; }

        .gradient-green { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
        .gradient-blue { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); }
        .gradient-red { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }

        .filters-card {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .filters-form {
            display: flex;
            gap: 1rem;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .filter-group label {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
        }

        .form-control {
            padding: 0.5rem 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 0.875rem;
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .table-responsive { overflow-x: auto; }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th, .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #f1f5f9;
        }

        .data-table th {
            background: #f8fafc;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #64748b;
        }

        .data-table tbody tr:hover { background: #f8fafc; }

        .user-cell {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.8rem;
        }

        .user-name { font-weight: 500; color: #1e293b; }
        .user-email { font-size: 0.8rem; color: #64748b; }

        .plan-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .plan-starter { background: #dbeafe; color: #2563eb; }
        .plan-professional { background: #f3e8ff; color: #7c3aed; }
        .plan-enterprise { background: #fef3c7; color: #d97706; }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-active { background: #dcfce7; color: #16a34a; }
        .status-trial { background: #dbeafe; color: #2563eb; }
        .status-expired { background: #fee2e2; color: #dc2626; }
        .status-cancelled { background: #f1f5f9; color: #64748b; }

        .text-danger { color: #dc2626; }
        .text-warning { color: #d97706; }

        .action-buttons { display: flex; gap: 0.5rem; }

        .btn-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #64748b;
            background: #f1f5f9;
            text-decoration: none;
            transition: all 0.2s;
        }

        .btn-icon:hover { background: #667eea; color: white; }

        .empty-row td { padding: 3rem; }

        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2.5rem; margin-bottom: 0.75rem; }

        .pagination-wrapper {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: center;
        }

        .pagination { display: flex; gap: 0.25rem; }

        .page-link {
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
    </style>
</body>
</html>
