<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

session_start();
include('../include/config.php');

// Check if user is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../login.php');
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['is_admin'] != 1) {
    header('Location: ../user/dashboard.php');
    exit();
}

// Handle User Update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_user'])) {
    $user_id = (int)$_POST['user_id'];
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $balance = (float)$_POST['balance'];
    $referral_balance = (float)$_POST['referral_balance'];
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;
    $has_active_subscription = isset($_POST['has_active_subscription']) ? 1 : 0;
    
    try {
        $stmt = $pdo->prepare("
            UPDATE users 
            SET username = ?, email = ?, full_name = ?, balance = ?, 
                referral_balance = ?, is_admin = ?, has_active_subscription = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$username, $email, $full_name, $balance, $referral_balance, $is_admin, $has_active_subscription, $user_id]);
        
        $_SESSION['success'] = "User updated successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error updating user: " . $e->getMessage();
    }
    
    header('Location: manage-users.php');
    exit();
}

// Handle User Deletion
if (isset($_GET['delete'])) {
    $user_id = (int)$_GET['delete'];
    
    // Prevent deleting own account
    if ($user_id == $_SESSION['user_id']) {
        $_SESSION['error'] = "You cannot delete your own account!";
        header('Location: manage-users.php');
        exit();
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND is_admin = 0");
        $stmt->execute([$user_id]);
        
        if ($stmt->rowCount() > 0) {
            $_SESSION['success'] = "User deleted successfully!";
        } else {
            $_SESSION['error'] = "Cannot delete admin users or user not found!";
        }
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error deleting user!";
    }
    
    header('Location: manage-users.php');
    exit();
}

// Pagination and filtering
$records_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Search filter
$search = isset($_GET['search']) && !empty($_GET['search']) ? trim($_GET['search']) : null;
$subscription_filter = isset($_GET['subscription']) && $_GET['subscription'] !== '' ? (int)$_GET['subscription'] : null;

// Build query
$where_conditions = [];
$params = [];

if ($search) {
    $where_conditions[] = "(username LIKE ? OR email LIKE ? OR full_name LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

if ($subscription_filter !== null) {
    $where_conditions[] = "has_active_subscription = ?";
    $params[] = $subscription_filter;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_query = "SELECT COUNT(*) FROM users $where_clause";
$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

// Fetch users
$query = "SELECT * FROM users $where_clause ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($query);

if (!empty($params)) {
    $param_index = 1;
    foreach ($params as $value) {
        $stmt->bindValue($param_index++, $value);
    }
}

$stmt->bindValue(':limit', (int)$records_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn(),
    'admins' => $pdo->query("SELECT COUNT(*) FROM users WHERE is_admin = 1")->fetchColumn(),
    'active_subscriptions' => $pdo->query("SELECT COUNT(*) FROM users WHERE has_active_subscription = 1")->fetchColumn(),
    'total_balance' => $pdo->query("SELECT COALESCE(SUM(balance), 0) FROM users")->fetchColumn(),
    'total_referral_balance' => $pdo->query("SELECT COALESCE(SUM(referral_balance), 0) FROM users")->fetchColumn(),
];

// Fetch user for editing
$edit_user = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_user = $stmt->fetch(PDO::FETCH_ASSOC);
}

$page_title = WEB_NAME . " | Manage Users";
?>
<!DOCTYPE html>
<html lang="en" class="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="shortcut icon" type="image/png" href="<?php echo $site_data['web_url']; ?>/public/favicons/favicon.png">
    <style>
        .stat-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen p-4 lg:p-8">

<div class="max-w-7xl mx-auto space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-3xl font-bold text-slate-900">Manage Users</h1>
            <p class="text-slate-600 mt-1">View and manage all registered users</p>
        </div>
        <a href="dashboard.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
            <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
    </div>

    <!-- Alert Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="p-4 bg-green-50 border border-green-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-green-600 mr-3"></i>
                <span class="text-green-800 font-medium"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="p-4 bg-red-50 border border-red-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-times-circle text-red-600 mr-3"></i>
                <span class="text-red-800 font-medium"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div class="stat-card bg-white rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-slate-900"><?php echo $stats['total']; ?></div>
            <div class="text-sm text-slate-600 mt-1">Total Users</div>
        </div>
        <div class="stat-card bg-purple-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-purple-700"><?php echo $stats['admins']; ?></div>
            <div class="text-sm text-purple-600 mt-1">Admins</div>
        </div>
        <div class="stat-card bg-green-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-green-700"><?php echo $stats['active_subscriptions']; ?></div>
            <div class="text-sm text-green-600 mt-1">Active Subs</div>
        </div>
        <div class="stat-card bg-blue-50 rounded-xl shadow p-4 text-center">
            <div class="text-xl font-bold text-blue-700">₦<?php echo number_format($stats['total_balance'], 2); ?></div>
            <div class="text-sm text-blue-600 mt-1">Total Balance</div>
        </div>
        <div class="stat-card bg-orange-50 rounded-xl shadow p-4 text-center">
            <div class="text-xl font-bold text-orange-700">₦<?php echo number_format($stats['total_referral_balance'], 2); ?></div>
            <div class="text-sm text-orange-600 mt-1">Referral Balance</div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-4">
        <form method="GET" class="flex flex-wrap gap-3">
            <input type="text" name="search" value="<?php echo htmlspecialchars($search ?? ''); ?>" 
                   placeholder="Search username, email, or name..."
                   class="flex-1 min-w-[200px] px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            
            <select name="subscription" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                <option value="">All Subscriptions</option>
                <option value="1" <?php echo $subscription_filter === 1 ? 'selected' : ''; ?>>Active Subscription</option>
                <option value="0" <?php echo $subscription_filter === 0 ? 'selected' : ''; ?>>No Subscription</option>
            </select>
            
            <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                <i class="fas fa-search mr-2"></i>Search
            </button>
            
            <?php if ($search || $subscription_filter !== null): ?>
            <a href="manage-users.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded-lg transition-colors">
                <i class="fas fa-times mr-2"></i>Clear
            </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Edit Form (shown when editing) -->
    <?php if ($edit_user): ?>
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-bold text-slate-900">
                <i class="fas fa-edit text-blue-600 mr-2"></i>Edit User
            </h2>
            <a href="manage-users.php" class="text-slate-600 hover:text-slate-900">
                <i class="fas fa-times"></i>
            </a>
        </div>

        <form method="POST" class="space-y-6">
            <input type="hidden" name="update_user" value="1">
            <input type="hidden" name="user_id" value="<?php echo $edit_user['id']; ?>">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Username *</label>
                    <input type="text" name="username" value="<?php echo htmlspecialchars($edit_user['username']); ?>" required
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Email *</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($edit_user['email']); ?>" required
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Full Name</label>
                    <input type="text" name="full_name" value="<?php echo htmlspecialchars($edit_user['full_name']); ?>"
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Referral Code</label>
                    <input type="text" value="<?php echo htmlspecialchars($edit_user['referral_code']); ?>" disabled
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg bg-slate-100">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Balance (₦)</label>
                    <input type="number" name="balance" value="<?php echo $edit_user['balance']; ?>" step="0.01" min="0"
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Referral Balance (₦)</label>
                    <input type="number" name="referral_balance" value="<?php echo $edit_user['referral_balance']; ?>" step="0.01" min="0"
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                    <input type="checkbox" name="is_admin" <?php echo $edit_user['is_admin'] ? 'checked' : ''; ?> class="mr-3">
                    <span class="text-sm text-slate-700">Admin User</span>
                </label>

                <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                    <input type="checkbox" name="has_active_subscription" <?php echo $edit_user['has_active_subscription'] ? 'checked' : ''; ?> class="mr-3">
                    <span class="text-sm text-slate-700">Has Active Subscription</span>
                </label>
            </div>

            <div class="flex gap-3">
                <button type="submit" class="px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold rounded-lg transition-all">
                    <i class="fas fa-save mr-2"></i>Update User
                </button>
                <a href="manage-users.php" class="px-6 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold rounded-lg transition-colors">
                    <i class="fas fa-times mr-2"></i>Cancel
                </a>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- Users List -->
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <h2 class="text-xl font-bold text-slate-900 mb-6">
            <i class="fas fa-users text-blue-600 mr-2"></i>All Users (<?php echo $total_records; ?>)
        </h2>

        <?php if (count($users) > 0): ?>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200">
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">User</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Email</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Balance</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Referral</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Status</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Joined</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $u): ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="p-3">
                                <div class="font-semibold text-slate-900"><?php echo htmlspecialchars($u['username']); ?></div>
                                <?php if ($u['is_admin']): ?>
                                    <span class="text-xs px-2 py-1 bg-purple-100 text-purple-700 rounded">Admin</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3 text-sm text-slate-600"><?php echo htmlspecialchars($u['email']); ?></td>
                            <td class="p-3 text-sm font-semibold text-green-600">₦<?php echo number_format($u['balance'], 2); ?></td>
                            <td class="p-3">
                                <div class="text-sm font-semibold text-orange-600">₦<?php echo number_format($u['referral_balance'], 2); ?></div>
                                <div class="text-xs text-slate-500"><?php echo $u['referral_code']; ?></div>
                            </td>
                            <td class="p-3">
                                <?php if ($u['has_active_subscription']): ?>
                                    <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-semibold">Active</span>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-slate-100 text-slate-700 rounded text-xs font-semibold">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3 text-sm text-slate-600"><?php echo date('M d, Y', strtotime($u['created_at'])); ?></td>
                            <td class="p-3">
                                <div class="flex gap-2">
                                    <a href="?edit=<?php echo $u['id']; ?>" class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if (!$u['is_admin'] && $u['id'] != $_SESSION['user_id']): ?>
                                    <a href="?delete=<?php echo $u['id']; ?>" onclick="return confirm('Delete this user? This action cannot be undone!')" 
                                       class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-xs">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="flex items-center justify-center gap-3 mt-6">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $subscription_filter !== null ? '&subscription=' . $subscription_filter : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>

            <span class="px-4 py-2 bg-slate-100 rounded-lg text-sm font-medium">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </span>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $subscription_filter !== null ? '&subscription=' . $subscription_filter : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <div class="text-center py-12">
            <i class="fas fa-users text-4xl text-slate-300 mb-4"></i>
            <p class="text-slate-600">No users found.</p>
        </div>
        <?php endif; ?>
    </div>

</div>

</body>
</html>