<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

$page_title = 'Users Management';
$msg = '';

// Approve user
if (isset($_POST['approve_user'])) {
    $uid = (int)$_POST['user_id'];
    $user = $conn->query("SELECT name, email FROM users WHERE id=$uid")->fetch_assoc();
    $conn->query("UPDATE users SET account_status='active' WHERE id=$uid");
    logActivity($conn, 'approve_user', 'user', $uid, 'Approved user: ' . $user['name']);
    createNotification($conn, $uid, 'Your account has been approved! You can now log in and use RELINK.', 'general');
    $sent = sendAccountApprovedEmail($conn, $user['email'], $user['name']);
    $email_note = $sent ? ' Email notification sent.' : ' (Email not sent — check SMTP settings.)';
    $msg = '<div class="alert alert-success">User approved and activated.' . $email_note . '</div>';
}

// Reject user
if (isset($_POST['reject_user'])) {
    $uid = (int)$_POST['user_id'];
    $user = $conn->query("SELECT name FROM users WHERE id=$uid")->fetch_assoc();
    $conn->query("UPDATE users SET account_status='rejected' WHERE id=$uid");
    logActivity($conn, 'reject_user', 'user', $uid, 'Rejected user: ' . $user['name']);
    $msg = '<div class="alert alert-warning">User account rejected.</div>';
}

// Delete user
if (isset($_POST['delete_user'])) {
    $uid = (int)$_POST['user_id'];
    if ($uid !== $_SESSION['user_id']) {
        $user = $conn->query("SELECT name FROM users WHERE id=$uid")->fetch_assoc();
        $conn->query("DELETE FROM users WHERE id=$uid");
        logActivity($conn, 'delete_user', 'user', $uid, 'Deleted user: ' . $user['name']);
        $msg = '<div class="alert alert-success">User deleted.</div>';
    }
}

// Update role
if (isset($_POST['update_role'])) {
    $uid = (int)$_POST['user_id'];
    $role = sanitize($conn, $_POST['role']);
    $user = $conn->query("SELECT name FROM users WHERE id=$uid")->fetch_assoc();
    $conn->query("UPDATE users SET role='$role' WHERE id=$uid");
    logActivity($conn, 'update_role', 'user', $uid, 'Updated role to: ' . $role . ' for ' . $user['name']);
    $msg = '<div class="alert alert-success">User role updated.</div>';
}

$tab = $_GET['tab'] ?? 'all';
$search = sanitize($conn, $_GET['search'] ?? '');

$where = "WHERE role='user'";
if ($search) $where .= " AND (name LIKE '%$search%' OR email LIKE '%$search%')";
if ($tab === 'pending')  $where .= " AND account_status='pending'";
if ($tab === 'active')   $where .= " AND account_status='active'";
if ($tab === 'rejected') $where .= " AND account_status='rejected'";

$users = $conn->query("SELECT * FROM users $where ORDER BY created_at DESC");
$pending_count = $conn->query("SELECT COUNT(*) c FROM users WHERE role='user' AND account_status='pending'")->fetch_assoc()['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <?= $msg ?>

            <?php if($pending_count > 0): ?>
            <div class="alert alert-warning" style="display:flex;align-items:center;gap:10px">
                <span style="font-size:20px">⏳</span>
                <span><strong><?= $pending_count ?> user(s)</strong> are waiting for account approval.</span>
                <a href="?tab=pending" class="btn btn-sm btn-warning" style="margin-left:auto">Review Now</a>
            </div>
            <?php endif; ?>

            <div class="card">
                <div class="card-header">
                    <h3>👥 Users Management</h3>
                </div>
                <div class="card-body">
                    <!-- Tabs -->
                    <div style="display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap">
                        <a href="?tab=all" class="btn btn-sm <?= $tab==='all'?'btn-primary':'btn-outline' ?>">All Users</a>
                        <a href="?tab=pending" class="btn btn-sm <?= $tab==='pending'?'btn-warning':'btn-outline' ?>">
                            ⏳ Pending <?php if($pending_count > 0): ?><span class="notif-badge" style="position:relative;top:0;right:0;margin-left:4px"><?= $pending_count ?></span><?php endif; ?>
                        </a>
                        <a href="?tab=active" class="btn btn-sm <?= $tab==='active'?'btn-success':'btn-outline' ?>">✅ Active</a>
                        <a href="?tab=rejected" class="btn btn-sm <?= $tab==='rejected'?'btn-danger':'btn-outline' ?>">❌ Rejected</a>
                    </div>

                    <!-- Search -->
                    <form method="GET" class="search-bar">
                        <input type="hidden" name="tab" value="<?= $tab ?>">
                        <input type="text" name="search" class="form-control" placeholder="Search by name or email..." value="<?= htmlspecialchars($search) ?>">
                        <button type="submit" class="btn btn-primary">Search</button>
                        <?php if($search): ?><a href="?tab=<?= $tab ?>" class="btn btn-secondary">Clear</a><?php endif; ?>
                    </form>

                    <div class="table-wrapper">
                        <table>
                            <thead>
                                <tr><th>#</th><th>Name</th><th>Email</th><th>Gender</th><th>Phone</th><th>Role</th><th>Status</th><th>Joined</th><th>Actions</th></tr>
                            </thead>
                            <tbody>
                            <?php if($users->num_rows === 0): ?>
                            <tr><td colspan="9" class="text-center text-muted" style="padding:32px">No users found.</td></tr>
                            <?php endif; ?>
                            <?php while($u = $users->fetch_assoc()): ?>
                            <tr>
                                <td><?= $u['id'] ?></td>
                                <td>
                                    <div style="display:flex;align-items:center;gap:8px">
                                        <?php if(!empty($u['avatar'])): ?>
                                        <img src="<?= BASE_URL ?>/<?= htmlspecialchars($u['avatar']) ?>" style="width:36px;height:36px;border-radius:50%;object-fit:cover;flex-shrink:0;border:2px solid var(--border);">
                                        <?php else: ?>
                                        <div style="width:36px;height:36px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px;flex-shrink:0">
                                            <?= strtoupper(substr($u['name'],0,1)) ?>
                                        </div>
                                        <?php endif; ?>
                                        <?= htmlspecialchars($u['name']) ?>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($u['email']) ?></td>
                                <td><?= ucfirst($u['gender']) ?></td>
                                <td><?= htmlspecialchars($u['phone'] ?? '-') ?></td>
                                <td><span class="badge badge-<?= $u['role'] ?>"><?= $u['role'] ?></span></td>
                                <td>
                                    <?php
                                    $st = $u['account_status'] ?? 'pending';
                                    $badge = match($st) {
                                        'active'    => 'badge-returned',
                                        'rejected'  => 'badge-rejected',
                                        'suspended' => 'badge-pending',
                                        'banned'    => 'badge-rejected',
                                        default     => 'badge-pending'
                                    };
                                    $icon = match($st) {
                                        'active'    => '✅',
                                        'rejected'  => '❌',
                                        'suspended' => '⏸',
                                        'banned'    => '🚫',
                                        default     => '⏳'
                                    };
                                    ?>
                                    <span class="badge <?= $badge ?>"><?= $icon ?> <?= ucfirst($st) ?></span>
                                </td>
                                <td><?= date('M d, Y', strtotime($u['created_at'])) ?></td>
                                <td>
                                    <div style="display:flex;gap:4px;flex-wrap:wrap">
                                        <?php if(($u['account_status'] ?? 'pending') === 'pending'): ?>
                                        <form method="POST" style="display:inline">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button name="approve_user" class="btn btn-sm btn-success" title="Approve">✅ Approve</button>
                                        </form>
                                        <form method="POST" style="display:inline">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button name="reject_user" class="btn btn-sm btn-danger" title="Reject">❌ Reject</button>
                                        </form>
                                        <?php elseif(($u['account_status'] ?? 'pending') === 'rejected'): ?>
                                        <form method="POST" style="display:inline">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button name="approve_user" class="btn btn-sm btn-success" title="Activate">✅ Activate</button>
                                        </form>
                                        <?php elseif(($u['account_status'] ?? 'pending') === 'active'): ?>
                                        <form method="POST" style="display:inline">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button name="reject_user" class="btn btn-sm btn-warning" title="Deactivate">🚫 Deactivate</button>
                                        </form>
                                        <?php endif; ?>
                                        <button onclick="openModal('roleModal<?= $u['id'] ?>')" class="btn btn-sm btn-secondary">Role</button>
                                        <?php if($u['id'] !== $_SESSION['user_id']): ?>
                                        <form method="POST" style="display:inline" onsubmit="return confirmDelete(this)" data-item="<?= htmlspecialchars($u['name']) ?>">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button type="submit" name="delete_user" class="btn btn-sm btn-danger">Delete</button>
                                        </form>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Role Modal -->
                                    <div class="modal-overlay" id="roleModal<?= $u['id'] ?>">
                                        <div class="modal">
                                            <div class="modal-header">
                                                <h3>Change Role — <?= htmlspecialchars($u['name']) ?></h3>
                                                <button class="modal-close" onclick="closeModal('roleModal<?= $u['id'] ?>')">✕</button>
                                            </div>
                                            <form method="POST">
                                                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                                <div class="form-group">
                                                    <label>Role</label>
                                                    <select name="role" class="form-control">
                                                        <option value="user" <?= $u['role']==='user'?'selected':'' ?>>User</option>
                                                        <option value="admin" <?= $u['role']==='admin'?'selected':'' ?>>Admin</option>
                                                    </select>
                                                </div>
                                                <button type="submit" name="update_role" class="btn btn-primary btn-block">Update Role</button>
                                            </form>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
</body>
</html>
