<?php
define('APP_RUNNING', true);
session_start();
require_once '../db_connect.php';

// Allow both admin and user_admin roles
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'user_admin'])) {
    header('Location: ../login');
    exit;
}

$current_role = $_SESSION['role'];

$admin_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Handle actions (only full admin can do these, except password change)
if(isset($_POST['action'])) {
    $user_id = intval($_POST['user_id']);
    $action = $_POST['action'];

    // Only full admin can perform these actions
    if($current_role == 'admin') {
        if($action == 'approve') {
            mysqli_query($conn, "UPDATE users SET status = 'approved', approved_by = $admin_id, approved_at = NOW() WHERE id = $user_id");
            $message = 'User approved successfully';
        } elseif($action == 'reject') {
            $reason = mysqli_real_escape_string($conn, $_POST['reason'] ?? '');
            mysqli_query($conn, "UPDATE users SET status = 'rejected', rejection_reason = '$reason' WHERE id = $user_id");
            $message = 'User rejected';
        } elseif($action == 'suspend') {
            mysqli_query($conn, "UPDATE users SET status = 'suspended' WHERE id = $user_id");
            $message = 'User suspended';
        } elseif($action == 'activate') {
            mysqli_query($conn, "UPDATE users SET status = 'approved' WHERE id = $user_id");
            $message = 'User activated';
        } elseif($action == 'delete') {
            mysqli_query($conn, "DELETE FROM users WHERE id = $user_id AND role != 'admin'");
            $message = 'User deleted';
        } elseif($action == 'change_role') {
            $new_role = mysqli_real_escape_string($conn, $_POST['new_role']);
            if(in_array($new_role, ['user', 'broker'])) {
                mysqli_query($conn, "UPDATE users SET role = '$new_role' WHERE id = $user_id AND role != 'admin'");
                $message = 'User role updated';
            }
        }
    }
}

// Filter
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$where = "u.role != 'admin'";
if($filter == 'pending') $where .= " AND u.status = 'pending'";
elseif($filter == 'approved') $where .= " AND u.status = 'approved'";
elseif($filter == 'rejected') $where .= " AND u.status = 'rejected'";
elseif($filter == 'suspended') $where .= " AND u.status = 'suspended'";
elseif($filter == 'brokers') $where .= " AND u.role = 'broker'";
elseif($filter == 'users') $where .= " AND u.role = 'user'";

$users = mysqli_query($conn, "SELECT u.*, a.username as approved_by_name,
    (SELECT COUNT(*) FROM lands WHERE user_id = u.id) as land_count
    FROM users u
    LEFT JOIN users a ON u.approved_by = a.id
    WHERE $where
    ORDER BY u.created_at DESC");

$pending_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM users WHERE status = 'pending' AND role != 'admin'"))['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/DataTables/datatables.min.css" rel="stylesheet">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-users"></i> User Management</h1>
                    <p>Manage user accounts, approvals, and roles</p>
                </div>
            </div>
        </div>

        <?php if($message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i><?php echo $message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <!-- Filter Tabs -->
        <div class="filter-tabs">
            <a href="users" class="filter-tab <?php echo $filter == 'all' ? 'active' : ''; ?>">
                <i class="fas fa-users"></i> All Users
            </a>
            <a href="users?filter=pending" class="filter-tab <?php echo $filter == 'pending' ? 'active' : ''; ?>">
                <i class="fas fa-clock"></i> Pending
                <?php if($pending_count > 0): ?><span class="badge"><?php echo $pending_count; ?></span><?php endif; ?>
            </a>
            <a href="users?filter=approved" class="filter-tab <?php echo $filter == 'approved' ? 'active' : ''; ?>">
                <i class="fas fa-check"></i> Approved
            </a>
            <a href="users?filter=rejected" class="filter-tab <?php echo $filter == 'rejected' ? 'active' : ''; ?>">
                <i class="fas fa-times"></i> Rejected
            </a>
            <a href="users?filter=suspended" class="filter-tab <?php echo $filter == 'suspended' ? 'active' : ''; ?>">
                <i class="fas fa-ban"></i> Suspended
            </a>
            <a href="users?filter=brokers" class="filter-tab <?php echo $filter == 'brokers' ? 'active' : ''; ?>">
                <i class="fas fa-user-tie"></i> Brokers
            </a>
            <a href="users?filter=users" class="filter-tab <?php echo $filter == 'users' ? 'active' : ''; ?>">
                <i class="fas fa-user"></i> Land Owners
            </a>
        </div>

        <div class="content-card">
            <div class="card-header-custom">
                <h3><i class="fas fa-list"></i> Users List</h3>
                <span class="result-count"><?php echo mysqli_num_rows($users); ?> users found</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover modern-table" id="usersTable">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Contact</th>
                                <th>Role</th>
                                <th>Lands</th>
                                <th>Status</th>
                                <th>Registered</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($user = mysqli_fetch_assoc($users)): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar-table">
                                            <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                                        </div>
                                        <div class="user-info-table">
                                            <strong><?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?></strong>
                                            <span>@<?php echo $user['username']; ?></span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="contact-cell">
                                        <span class="email"><?php echo $user['email']; ?></span>
                                        <?php if($user['phone']): ?>
                                        <span class="phone"><?php echo $user['phone']; ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <span class="role-badge role-<?php echo $user['role']; ?>">
                                        <?php echo ucfirst($user['role']); ?>
                                    </span>
                                </td>
                                <td><span class="land-count"><?php echo $user['land_count']; ?></span></td>
                                <td>
                                    <span class="status-badge status-<?php echo $user['status']; ?>">
                                        <?php echo ucfirst($user['status']); ?>
                                    </span>
                                    <?php if($user['status'] == 'approved' && $user['approved_by_name']): ?>
                                    <small class="approved-by">by <?php echo $user['approved_by_name']; ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn-action" data-toggle="dropdown">
                                            <i class="fas fa-ellipsis-v"></i>
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right">
                                            <?php if($current_role == 'admin'): ?>
                                            <?php if($user['status'] == 'pending'): ?>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <input type="hidden" name="action" value="approve">
                                                <button type="submit" class="dropdown-item text-success">
                                                    <i class="fas fa-check mr-2"></i>Approve
                                                </button>
                                            </form>
                                            <a href="#" class="dropdown-item text-danger" data-toggle="modal"
                                               data-target="#rejectModal" data-userid="<?php echo $user['id']; ?>">
                                                <i class="fas fa-times mr-2"></i>Reject
                                            </a>
                                            <?php endif; ?>

                                            <?php if($user['status'] == 'approved'): ?>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <input type="hidden" name="action" value="suspend">
                                                <button type="submit" class="dropdown-item text-warning">
                                                    <i class="fas fa-ban mr-2"></i>Suspend
                                                </button>
                                            </form>
                                            <?php endif; ?>

                                            <?php if($user['status'] == 'suspended' || $user['status'] == 'rejected'): ?>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <input type="hidden" name="action" value="activate">
                                                <button type="submit" class="dropdown-item text-success">
                                                    <i class="fas fa-check mr-2"></i>Activate
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                            <?php endif; ?>

                                            <?php if($current_role == 'admin'): ?>
                                            <a href="edit_user?id=<?php echo $user['id']; ?>" class="dropdown-item">
                                                <i class="fas fa-edit mr-2"></i>Edit Details
                                            </a>
                                            <?php endif; ?>

                                            <!-- Change Password - Available to both admin and user_admin -->
                                            <a href="change_password?id=<?php echo $user['id']; ?>" class="dropdown-item">
                                                <i class="fas fa-key mr-2"></i>Change Password
                                            </a>

                                            <?php if($current_role == 'admin'): ?>
                                            <a href="#" class="dropdown-item" data-toggle="modal"
                                               data-target="#roleModal" data-userid="<?php echo $user['id']; ?>"
                                               data-role="<?php echo $user['role']; ?>">
                                                <i class="fas fa-user-tag mr-2"></i>Change Role
                                            </a>
                                            <?php endif; ?>

                                            <?php if($current_role == 'admin'): ?>
                                            <div class="dropdown-divider"></div>
                                            <form method="POST" style="display:inline;"
                                                  onsubmit="return confirm('Are you sure you want to delete this user?');">
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <input type="hidden" name="action" value="delete">
                                                <button type="submit" class="dropdown-item text-danger">
                                                    <i class="fas fa-trash mr-2"></i>Delete
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-times-circle mr-2"></i>Reject User</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="user_id" id="rejectUserId">
                        <input type="hidden" name="action" value="reject">
                        <div class="form-group">
                            <label>Reason for rejection (optional)</label>
                            <textarea name="reason" class="form-control" rows="3" placeholder="Enter reason..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Reject User</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Role Modal -->
    <div class="modal fade" id="roleModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-user-tag mr-2"></i>Change User Role</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="user_id" id="roleUserId">
                        <input type="hidden" name="action" value="change_role">
                        <div class="form-group">
                            <label>Select New Role</label>
                            <select name="new_role" class="form-control" id="newRoleSelect">
                                <option value="user">Land Owner (User)</option>
                                <option value="broker">Broker/Agent</option>
                                <optgroup label="CBC Village Roles">
                                    <option value="village_chairman">Village Chairman (Mwenyekiti)</option>
                                    <option value="land_officer">Land Officer (Afisa Ardhi)</option>
                                    <option value="surveyor">Surveyor (Mpima Ardhi)</option>
                                    <option value="district_officer">District Officer (Afisa Wilaya)</option>
                                </optgroup>
                                <optgroup label="Admin Roles">
                                    <option value="user_admin">Payment Admin</option>
                                </optgroup>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Role</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
    /* Page-specific styles */
    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
        font-size: 15px;
    }

    .filter-tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 25px;
        flex-wrap: wrap;
    }

    .filter-tab {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 18px;
        background: white;
        border-radius: 12px;
        text-decoration: none;
        color: #64748b;
        font-weight: 500;
        font-size: 14px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    }

    .filter-tab:hover {
        background: #f8fafc;
        color: #667eea;
        text-decoration: none;
        transform: translateY(-2px);
    }

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

    .filter-tab .badge {
        background: rgba(255,255,255,0.2);
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 11px;
    }

    .filter-tab.active .badge {
        background: rgba(255,255,255,0.3);
    }

    .content-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
    }

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

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

    .result-count {
        background: #f1f5f9;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 13px;
        color: #64748b;
        font-weight: 500;
    }

    .card-body {
        padding: 0;
    }

    .modern-table {
        margin: 0;
    }

    .modern-table thead th {
        background: #f8fafc;
        border: none;
        padding: 16px 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
    }

    .modern-table tbody td {
        padding: 16px 20px;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
    }

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

    .user-cell {
        display: flex;
        align-items: center;
        gap: 12px;
    }

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

    .user-info-table {
        display: flex;
        flex-direction: column;
    }

    .user-info-table strong {
        font-size: 14px;
        color: #1e293b;
    }

    .user-info-table span {
        font-size: 12px;
        color: #94a3b8;
    }

    .contact-cell {
        display: flex;
        flex-direction: column;
    }

    .contact-cell .email {
        font-size: 13px;
        color: #475569;
    }

    .contact-cell .phone {
        font-size: 12px;
        color: #94a3b8;
    }

    .role-badge {
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .role-broker {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        color: white;
    }

    .role-user {
        background: #e2e8f0;
        color: #475569;
    }

    .status-badge {
        display: inline-block;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .status-pending {
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        color: white;
    }

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

    .status-rejected {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: white;
    }

    .status-suspended {
        background: #94a3b8;
        color: white;
    }

    .approved-by {
        display: block;
        font-size: 11px;
        color: #94a3b8;
        margin-top: 4px;
    }

    .land-count {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        background: #f1f5f9;
        border-radius: 8px;
        font-weight: 600;
        color: #475569;
    }

    .btn-action {
        width: 36px;
        height: 36px;
        border-radius: 10px;
        border: none;
        background: #f1f5f9;
        color: #64748b;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-action:hover {
        background: #e2e8f0;
        color: #1e293b;
    }

    .dropdown-menu {
        border: none;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.12);
        padding: 8px;
    }

    .dropdown-item {
        border-radius: 8px;
        padding: 10px 16px;
        font-size: 14px;
        transition: all 0.2s ease;
    }

    .dropdown-item:hover {
        background: #f8fafc;
    }

    .modal-content {
        border: none;
        border-radius: 20px;
    }

    .modal-header {
        border-bottom: 1px solid #f1f5f9;
        padding: 20px 24px;
    }

    .modal-body {
        padding: 24px;
    }

    .modal-footer {
        border-top: 1px solid #f1f5f9;
        padding: 16px 24px;
    }

    .form-control {
        border-radius: 12px;
        border: 2px solid #e2e8f0;
        padding: 12px 16px;
        transition: all 0.3s ease;
    }

    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
    }

    .btn {
        border-radius: 10px;
        padding: 10px 20px;
        font-weight: 600;
        transition: all 0.3s ease;
    }

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

    .btn-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        border: none;
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
    }

    .alert-success {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        color: #166534;
        border-left: 4px solid #22c55e;
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .filter-tabs {
            gap: 8px;
        }

        .filter-tab {
            padding: 8px 14px;
            font-size: 13px;
        }

        .card-header-custom {
            padding: 16px 20px;
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;
        }

        .modern-table thead th,
        .modern-table tbody td {
            padding: 12px 14px;
        }
    }
    </style>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/DataTables/datatables.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#usersTable').DataTable({
                order: [[5, 'desc']],
                pageLength: 25,
                language: {
                    search: "",
                    searchPlaceholder: "Search users..."
                }
            });
        });

        $('#rejectModal').on('show.bs.modal', function(e) {
            var userId = $(e.relatedTarget).data('userid');
            $('#rejectUserId').val(userId);
        });

        $('#roleModal').on('show.bs.modal', function(e) {
            var userId = $(e.relatedTarget).data('userid');
            var role = $(e.relatedTarget).data('role');
            $('#roleUserId').val(userId);
            $('#newRoleSelect').val(role);
        });
    </script>
</body>
</html>
