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

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

// Handle status filter
$statusFilter = $_GET['status'] ?? 'all';
$searchQuery = $_GET['search'] ?? '';

// Build query
$whereClause = "WHERE u.role = 'subscriber'";
$params = [];
$types = '';

if ($statusFilter === 'active') {
    $whereClause .= " AND s.status = 'active'";
} elseif ($statusFilter === 'trial') {
    $whereClause .= " AND s.status = 'trial'";
} elseif ($statusFilter === 'expired') {
    $whereClause .= " AND (s.status = 'expired' OR s.id IS NULL)";
}

if (!empty($searchQuery)) {
    $whereClause .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
    $searchTerm = "%{$searchQuery}%";
    $params = [$searchTerm, $searchTerm, $searchTerm];
    $types = 'sss';
}

// Get subscribers with pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 15;
$offset = ($page - 1) * $perPage;

$countSql = "SELECT COUNT(DISTINCT u.id) as total
    FROM users u
    LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status IN ('active', 'trial')
    {$whereClause}";

$totalResult = empty($params) ? db_fetch_one($countSql) : db_fetch_one($countSql, $types, $params);
$total = $totalResult['total'] ?? 0;
$totalPages = ceil($total / $perPage);

$sql = "SELECT u.*, s.id as sub_id, s.plan_id, s.status as sub_status, s.expires_at, s.billing_cycle,
               p.name as plan_name, p.slug as plan_slug
        FROM users u
        LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status IN ('active', 'trial')
        LEFT JOIN plans p ON s.plan_id = p.id
        {$whereClause}
        ORDER BY u.created_at DESC
        LIMIT {$perPage} OFFSET {$offset}";

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

// Get counts for tabs
$allCount = db_fetch_one("SELECT COUNT(*) as count FROM users WHERE role = 'subscriber'")['count'];
$activeCount = db_fetch_one("SELECT COUNT(DISTINCT u.id) as count FROM users u JOIN subscriptions s ON u.id = s.user_id WHERE u.role = 'subscriber' AND s.status = 'active'")['count'];
$trialCount = db_fetch_one("SELECT COUNT(DISTINCT u.id) as count FROM users u JOIN subscriptions s ON u.id = s.user_id WHERE u.role = 'subscriber' AND s.status = 'trial'")['count'];
$expiredCount = $allCount - $activeCount - $trialCount;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscribers - <?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">Subscribers</h1>
            <div class="header-actions">
                <a href="create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Subscriber
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Filters -->
            <div class="filters-card">
                <div class="filter-tabs">
                    <a href="?status=all" class="filter-tab <?php echo $statusFilter === 'all' ? 'active' : ''; ?>">
                        All <span class="count"><?php echo $allCount; ?></span>
                    </a>
                    <a href="?status=active" class="filter-tab <?php echo $statusFilter === 'active' ? 'active' : ''; ?>">
                        Active <span class="count success"><?php echo $activeCount; ?></span>
                    </a>
                    <a href="?status=trial" class="filter-tab <?php echo $statusFilter === 'trial' ? 'active' : ''; ?>">
                        Trial <span class="count info"><?php echo $trialCount; ?></span>
                    </a>
                    <a href="?status=expired" class="filter-tab <?php echo $statusFilter === 'expired' ? 'active' : ''; ?>">
                        Expired <span class="count danger"><?php echo $expiredCount; ?></span>
                    </a>
                </div>
                <form class="search-form" method="GET">
                    <input type="hidden" name="status" value="<?php echo $statusFilter; ?>">
                    <div class="search-input">
                        <i class="fas fa-search"></i>
                        <input type="text" name="search" placeholder="Search by name, email or phone..." value="<?php echo htmlspecialchars($searchQuery); ?>">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
            </div>

            <!-- Subscribers Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Subscriber</th>
                                <th>Plan</th>
                                <th>Status</th>
                                <th>Expires</th>
                                <th>Joined</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($subscribers)): ?>
                            <tr>
                                <td colspan="6" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-users"></i>
                                        <p>No subscribers found</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($subscribers as $sub): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar">
                                            <?php echo strtoupper(substr($sub['full_name'], 0, 1)); ?>
                                        </div>
                                        <div class="user-info">
                                            <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>
                                    <?php if ($sub['plan_name']): ?>
                                    <span class="plan-badge plan-<?php echo $sub['plan_slug']; ?>">
                                        <?php echo $sub['plan_name']; ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="text-muted">No Plan</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($sub['sub_status']): ?>
                                    <span class="status-badge status-<?php echo $sub['sub_status']; ?>">
                                        <?php echo ucfirst($sub['sub_status']); ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="status-badge status-expired">Expired</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($sub['expires_at']): ?>
                                    <?php
                                    $expires = strtotime($sub['expires_at']);
                                    $daysLeft = ceil(($expires - time()) / 86400);
                                    $class = $daysLeft <= 7 ? 'text-danger' : ($daysLeft <= 30 ? 'text-warning' : '');
                                    ?>
                                    <span class="<?php echo $class; ?>">
                                        <?php echo date('M j, Y', $expires); ?>
                                        <?php if ($daysLeft > 0 && $daysLeft <= 30): ?>
                                        <br><small>(<?php echo $daysLeft; ?> days)</small>
                                        <?php endif; ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('M j, Y', strtotime($sub['created_at'])); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $sub['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="../subscriptions/record-payment.php?user_id=<?php echo $sub['id']; ?>" class="btn-icon" title="Record Payment">
                                            <i class="fas fa-money-bill-wave"></i>
                                        </a>
                                        <a href="edit.php?id=<?php echo $sub['id']; ?>" class="btn-icon" title="Edit">
                                            <i class="fas fa-edit"></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; ?>&search=<?php echo urlencode($searchQuery); ?>" 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; ?>&search=<?php echo urlencode($searchQuery); ?>"
                           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; ?>&search=<?php echo urlencode($searchQuery); ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                    <div class="pagination-info">
                        Showing <?php echo $offset + 1; ?> - <?php echo min($offset + $perPage, $total); ?> of <?php echo $total; ?>
                    </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;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        /* Filters Card */
        .filters-card {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .filter-tabs {
            display: flex;
            gap: 0.5rem;
        }

        .filter-tab {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            font-size: 0.875rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }

        .filter-tab:hover {
            background: #f1f5f9;
        }

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

        .filter-tab .count {
            background: rgba(0,0,0,0.1);
            padding: 0.125rem 0.5rem;
            border-radius: 10px;
            font-size: 0.75rem;
        }

        .filter-tab.active .count {
            background: rgba(255,255,255,0.2);
        }

        .count.success { color: #16a34a; }
        .count.info { color: #2563eb; }
        .count.danger { color: #dc2626; }
        .filter-tab.active .count.success,
        .filter-tab.active .count.info,
        .filter-tab.active .count.danger { color: white; }

        .search-form {
            display: flex;
            gap: 0.75rem;
        }

        .search-input {
            position: relative;
        }

        .search-input i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }

        .search-input input {
            padding: 0.625rem 1rem 0.625rem 2.5rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.875rem;
            width: 280px;
            transition: border-color 0.2s;
        }

        .search-input input:focus {
            outline: none;
            border-color: #667eea;
        }

        /* Table */
        .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: 40px;
            height: 40px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 10px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }

        .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; }
        .text-muted { color: #94a3b8; }

        .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 */
        .pagination-wrapper {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: 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;
        }

        .pagination-info {
            font-size: 0.875rem;
            color: #64748b;
        }

        @media (max-width: 768px) {
            .filters-card {
                flex-direction: column;
                align-items: stretch;
            }

            .filter-tabs {
                overflow-x: auto;
                padding-bottom: 0.5rem;
            }

            .search-form {
                flex-direction: column;
            }

            .search-input input {
                width: 100%;
            }

            .pagination-wrapper {
                flex-direction: column;
                gap: 0.75rem;
            }
        }
    </style>
</body>
</html>
