<?php
/**
 * Admin Dashboard
 * LandSales Pro - Platform administration overview
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/subscription.php';
require_once '../includes/track.php';

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

// Get statistics
$totalSubscribers = db_fetch_one("SELECT COUNT(*) as count FROM users WHERE role = 'subscriber'")['count'] ?? 0;
$activeSubscriptions = db_fetch_one("SELECT COUNT(*) as count FROM subscriptions WHERE status = 'active'")['count'] ?? 0;
$trialSubscriptions = db_fetch_one("SELECT COUNT(*) as count FROM subscriptions WHERE status = 'trial'")['count'] ?? 0;
$expiredSubscriptions = db_fetch_one("SELECT COUNT(*) as count FROM subscriptions WHERE status = 'expired'")['count'] ?? 0;

// Revenue this month
$monthlyRevenue = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM subscription_payments WHERE status = 'confirmed' AND MONTH(payment_date) = MONTH(CURRENT_DATE()) AND YEAR(payment_date) = YEAR(CURRENT_DATE())")['total'] ?? 0;

// Revenue this year
$yearlyRevenue = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM subscription_payments WHERE status = 'confirmed' AND YEAR(payment_date) = YEAR(CURRENT_DATE())")['total'] ?? 0;

// Recent subscribers
$recentSubscribers = db_fetch_all("SELECT u.*, s.plan_id, s.status as sub_status, s.expires_at, p.name as plan_name
    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
    WHERE u.role = 'subscriber'
    ORDER BY u.created_at DESC
    LIMIT 5");

// Recent payments
$recentPayments = db_fetch_all("SELECT sp.*, u.full_name, u.email, p.name as plan_name
    FROM subscription_payments sp
    JOIN users u ON sp.user_id = u.id
    JOIN subscriptions s ON sp.subscription_id = s.id
    JOIN plans p ON s.plan_id = p.id
    ORDER BY sp.payment_date DESC
    LIMIT 5");

// Expiring soon (next 7 days)
$expiringSoon = db_fetch_all("SELECT s.*, u.full_name, u.email, p.name as plan_name
    FROM subscriptions s
    JOIN users u ON s.user_id = u.id
    JOIN plans p ON s.plan_id = p.id
    WHERE s.status IN ('active', 'trial')
    AND s.expires_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY)
    ORDER BY s.expires_at ASC
    LIMIT 5");

// Subscription by plan
$subscriptionsByPlan = db_fetch_all("SELECT p.name, p.slug, COUNT(s.id) as count
    FROM plans p
    LEFT JOIN subscriptions s ON p.id = s.plan_id AND s.status IN ('active', 'trial')
    WHERE p.is_active = 1
    GROUP BY p.id
    ORDER BY p.sort_order");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - <?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">Dashboard</h1>
            <div class="header-actions">
                <span class="text-muted"><?php echo date('F j, Y'); ?></span>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Stats Cards -->
            <div class="stats-grid">
                <div class="stat-card gradient-purple">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($totalSubscribers); ?></div>
                        <div class="stat-label">Total Subscribers</div>
                    </div>
                </div>

                <div class="stat-card gradient-green">
                    <div class="stat-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($activeSubscriptions); ?></div>
                        <div class="stat-label">Active Subscriptions</div>
                    </div>
                </div>

                <div class="stat-card gradient-blue">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($trialSubscriptions); ?></div>
                        <div class="stat-label">Trial Users</div>
                    </div>
                </div>

                <div class="stat-card gradient-orange">
                    <div class="stat-icon">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">TZS <?php echo number_format($monthlyRevenue); ?></div>
                        <div class="stat-label">Revenue This Month</div>
                    </div>
                </div>
            </div>

            <!-- Two Column Layout -->
            <div class="dashboard-grid">
                <!-- Recent Subscribers -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user-plus"></i> Recent Subscribers</h3>
                        <a href="subscribers/" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentSubscribers)): ?>
                        <div class="empty-state">
                            <i class="fas fa-users"></i>
                            <p>No subscribers yet</p>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($recentSubscribers as $subscriber): ?>
                            <div class="list-item">
                                <div class="list-avatar">
                                    <?php echo strtoupper(substr($subscriber['full_name'], 0, 1)); ?>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($subscriber['full_name']); ?></div>
                                    <div class="list-subtitle"><?php echo htmlspecialchars($subscriber['email']); ?></div>
                                </div>
                                <div class="list-meta">
                                    <?php if ($subscriber['sub_status']): ?>
                                    <span class="badge badge-<?php echo $subscriber['sub_status'] === 'active' ? 'success' : 'info'; ?>">
                                        <?php echo ucfirst($subscriber['sub_status']); ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="badge badge-secondary">No Plan</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Expiring Soon -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-exclamation-triangle"></i> Expiring Soon</h3>
                        <a href="subscriptions/" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($expiringSoon)): ?>
                        <div class="empty-state">
                            <i class="fas fa-calendar-check"></i>
                            <p>No subscriptions expiring soon</p>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($expiringSoon as $sub): ?>
                            <div class="list-item">
                                <div class="list-avatar warning">
                                    <?php echo strtoupper(substr($sub['full_name'], 0, 1)); ?>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($sub['full_name']); ?></div>
                                    <div class="list-subtitle"><?php echo $sub['plan_name']; ?></div>
                                </div>
                                <div class="list-meta">
                                    <?php
                                    $days = ceil((strtotime($sub['expires_at']) - time()) / 86400);
                                    ?>
                                    <span class="text-warning">
                                        <i class="fas fa-clock"></i> <?php echo $days; ?> days
                                    </span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Payments -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-money-bill-wave"></i> Recent Payments</h3>
                        <a href="subscriptions/payments.php" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentPayments)): ?>
                        <div class="empty-state">
                            <i class="fas fa-receipt"></i>
                            <p>No payments recorded yet</p>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($recentPayments as $payment): ?>
                            <div class="list-item">
                                <div class="list-avatar success">
                                    <i class="fas fa-check"></i>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($payment['full_name']); ?></div>
                                    <div class="list-subtitle"><?php echo $payment['plan_name']; ?> - <?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></div>
                                </div>
                                <div class="list-meta">
                                    <span class="text-success font-weight-bold">
                                        TZS <?php echo number_format($payment['amount']); ?>
                                    </span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Subscriptions by Plan -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-chart-pie"></i> Subscriptions by Plan</h3>
                    </div>
                    <div class="card-body">
                        <div class="plan-stats">
                            <?php foreach ($subscriptionsByPlan as $plan): ?>
                            <div class="plan-stat-item">
                                <div class="plan-info">
                                    <div class="plan-name"><?php echo $plan['name']; ?></div>
                                    <div class="plan-count"><?php echo number_format($plan['count']); ?> active</div>
                                </div>
                                <div class="plan-bar">
                                    <?php
                                    $total = array_sum(array_column($subscriptionsByPlan, 'count'));
                                    $percent = $total > 0 ? ($plan['count'] / $total) * 100 : 0;
                                    ?>
                                    <div class="bar-fill" style="width: <?php echo $percent; ?>%"></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="revenue-summary">
                            <div class="revenue-item">
                                <div class="revenue-label">This Month</div>
                                <div class="revenue-value">TZS <?php echo number_format($monthlyRevenue); ?></div>
                            </div>
                            <div class="revenue-item">
                                <div class="revenue-label">This Year</div>
                                <div class="revenue-value">TZS <?php echo number_format($yearlyRevenue); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="quick-actions">
                <h3>Quick Actions</h3>
                <div class="action-buttons">
                    <a href="subscribers/create.php" class="action-btn">
                        <i class="fas fa-user-plus"></i>
                        <span>Add Subscriber</span>
                    </a>
                    <a href="subscriptions/record-payment.php" class="action-btn">
                        <i class="fas fa-money-bill-wave"></i>
                        <span>Record Payment</span>
                    </a>
                    <a href="reports/revenue.php" class="action-btn">
                        <i class="fas fa-chart-line"></i>
                        <span>Revenue Report</span>
                    </a>
                    <a href="plans/" class="action-btn">
                        <i class="fas fa-tags"></i>
                        <span>Manage Plans</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

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

        .header-actions {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .text-muted {
            color: #64748b;
            font-size: 0.9rem;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            border-radius: 16px;
            padding: 1.5rem;
            color: white;
            display: flex;
            align-items: center;
            gap: 1rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

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

        .gradient-green {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        }

        .gradient-blue {
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        }

        .gradient-orange {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .stat-value {
            font-size: 1.75rem;
            font-weight: 700;
        }

        .stat-label {
            font-size: 0.875rem;
            opacity: 0.9;
        }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

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

        .card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-header h3 i {
            color: #667eea;
        }

        .card-body {
            padding: 1rem 1.5rem;
        }

        /* Buttons */
        .btn {
            padding: 0.5rem 1rem;
            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-sm {
            padding: 0.375rem 0.75rem;
            font-size: 0.8rem;
        }

        .btn-outline {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
        }

        .btn-outline:hover {
            border-color: #667eea;
            color: #667eea;
        }

        /* List Group */
        .list-group {
            display: flex;
            flex-direction: column;
        }

        .list-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .list-item:last-child {
            border-bottom: none;
        }

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

        .list-avatar.warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }

        .list-avatar.success {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        }

        .list-content {
            flex: 1;
            min-width: 0;
        }

        .list-title {
            font-weight: 500;
            color: #1e293b;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .list-subtitle {
            font-size: 0.8rem;
            color: #64748b;
        }

        .list-meta {
            text-align: right;
        }

        /* Badges */
        .badge {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .badge-success {
            background: #dcfce7;
            color: #16a34a;
        }

        .badge-info {
            background: #dbeafe;
            color: #2563eb;
        }

        .badge-warning {
            background: #fef3c7;
            color: #d97706;
        }

        .badge-secondary {
            background: #f1f5f9;
            color: #64748b;
        }

        .text-success {
            color: #16a34a;
        }

        .text-warning {
            color: #d97706;
        }

        .font-weight-bold {
            font-weight: 600;
        }

        /* Empty State */
        .empty-state {
            padding: 2rem;
            text-align: center;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
        }

        /* Plan Stats */
        .plan-stats {
            margin-bottom: 1.5rem;
        }

        .plan-stat-item {
            margin-bottom: 1rem;
        }

        .plan-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }

        .plan-name {
            font-weight: 500;
            color: #1e293b;
        }

        .plan-count {
            font-size: 0.85rem;
            color: #64748b;
        }

        .plan-bar {
            height: 8px;
            background: #f1f5f9;
            border-radius: 4px;
            overflow: hidden;
        }

        .bar-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 4px;
            transition: width 0.3s;
        }

        /* Revenue Summary */
        .revenue-summary {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #f1f5f9;
        }

        .revenue-item {
            text-align: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 10px;
        }

        .revenue-label {
            font-size: 0.8rem;
            color: #64748b;
            margin-bottom: 0.25rem;
        }

        .revenue-value {
            font-size: 1.1rem;
            font-weight: 700;
            color: #1e293b;
        }

        /* Quick Actions */
        .quick-actions h3 {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
        }

        .action-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 1rem 1.25rem;
            background: white;
            border-radius: 12px;
            text-decoration: none;
            color: #1e293b;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.2s;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .action-btn i {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 576px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }

            .content-wrapper {
                padding: 1rem;
            }

            .revenue-summary {
                grid-template-columns: 1fr;
            }
        }
    </style>
</body>
</html>
