<?php
session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Get current user's role and permissions
$current_user_id = $_SESSION['user_id'];
$current_user_role_sql = "SELECT ur.role_name, ur.role_id 
                          FROM users u 
                          JOIN user_roles ur ON u.role_id = ur.role_id 
                          WHERE u.user_id = ?";
$stmt = $conn->prepare($current_user_role_sql);
$stmt->bind_param("i", $current_user_id);
$stmt->execute();
$current_role_result = $stmt->get_result();
$current_user_role = $current_role_result->fetch_assoc();

// Check if user has permission to manage users
$can_manage_users = false;
$can_view_users = false;

if ($current_user_role) {
    // Check permissions from role_permissions table
    $perm_sql = "SELECT can_create, can_edit, can_delete, can_view 
                 FROM role_permissions 
                 WHERE role_id = ? AND menu_id = (SELECT menu_id FROM menu_items WHERE menu_url = 'users.php' LIMIT 1)";
    $perm_stmt = $conn->prepare($perm_sql);
    $perm_stmt->bind_param("i", $current_user_role['role_id']);
    $perm_stmt->execute();
    $perm_result = $perm_stmt->get_result();
    $permissions = $perm_result->fetch_assoc();
    
    if ($permissions) {
        $can_view_users = $permissions['can_view'] == 1;
        $can_manage_users = ($permissions['can_edit'] == 1 || $permissions['can_delete'] == 1 || $permissions['can_create'] == 1);
    }
    
    // Super Admin always has full access
    if ($current_user_role['role_name'] === 'Super Admin' || $current_user_role['role_name'] === 'Administrator') {
        $can_manage_users = true;
        $can_view_users = true;
    }
}

// If user doesn't have view permission, redirect
//if (!$can_view_users) {
//    header("Location: index.php");
//    exit();
//}

// Rest of your existing code for fetching users...
$users_sql = "SELECT 
    u.user_id, 
    u.username, 
    u.email, 
    u.full_name, 
    u.phone_primary, 
    u.staff_number,
    u.user_type,
    u.status,
    u.hire_date,
    u.last_login,
    ur.role_name,
    hb.branch_name,
    CASE 
        WHEN u.user_type = 'STAFF' AND d.doctor_id IS NOT NULL THEN 'Doctor'
        WHEN u.user_type = 'STAFF' AND n.nurse_id IS NOT NULL THEN 'Nurse'
        WHEN u.user_type = 'STAFF' AND lt.tech_id IS NOT NULL THEN 'Lab Technician'
        ELSE ur.role_name
    END as user_role_display
FROM users u
LEFT JOIN user_roles ur ON u.role_id = ur.role_id
LEFT JOIN hospital_branches hb ON u.branch_id = hb.branch_id
LEFT JOIN doctors d ON u.user_id = d.user_id
LEFT JOIN nurses n ON u.user_id = n.user_id
LEFT JOIN lab_technicians lt ON u.user_id = lt.user_id
WHERE u.user_type = 'STAFF'
ORDER BY u.created_at DESC";

$users_result = $conn->query($users_sql);

// Get user statistics
$stats_sql = "SELECT 
    COUNT(*) as total_users,
    SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_users,
    SUM(CASE WHEN status = 'INACTIVE' THEN 1 ELSE 0 END) as inactive_users,
    SUM(CASE WHEN status = 'PENDING' THEN 1 ELSE 0 END) as pending_users,
    SUM(CASE WHEN last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as recent_logins
FROM users WHERE user_type = 'STAFF'";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Get roles for filter
$roles_sql = "SELECT role_id, role_name FROM user_roles WHERE is_active = 1 ORDER BY role_name";
$roles_result = $conn->query($roles_sql);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Users Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--vz-primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-suspended { background: #fecaca; color: #b91c1c; }
        
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stats-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .action-buttons .btn {
            padding: 0.375rem 0.75rem;
            margin: 0.125rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Users Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="#">User Management</a></li>
                                        <li class="breadcrumb-item active">Users</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-primary"><?php echo number_format($stats['total_users']); ?></div>
                                <div class="stats-label">Total Users</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-success"><?php echo number_format($stats['active_users']); ?></div>
                                <div class="stats-label">Active Users</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-warning"><?php echo number_format($stats['pending_users']); ?></div>
                                <div class="stats-label">Pending Approval</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-info"><?php echo number_format($stats['recent_logins']); ?></div>
                                <div class="stats-label">Recent Logins</div>
                            </div>
                        </div>
                    </div>

                    <!-- Users Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-line align-middle me-2"></i>System Users
                                    </h5>
                                    <div class="d-flex gap-2">
                                        <!-- Filter Dropdown -->
                                        <select class="form-select" id="statusFilter" style="width: auto;">
                                            <option value="">All Status</option>
                                            <option value="ACTIVE">Active</option>
                                            <option value="INACTIVE">Inactive</option>
                                            <option value="PENDING">Pending</option>
                                            <option value="SUSPENDED">Suspended</option>
                                        </select>
                                        
                                        <select class="form-select" id="roleFilter" style="width: auto;">
                                            <option value="">All Roles</option>
                                            <?php 
                                            $roles_result->data_seek(0); // Reset pointer
                                            while($role = $roles_result->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $role['role_name']; ?>"><?php echo $role['role_name']; ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                        
                                        <?php if ($can_manage_users): ?>
                                        <a href="add_user.php" class="btn btn-primary">
                                            <i class="ri-user-add-line align-middle me-1"></i> Add User
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="usersTable" class="table table-striped table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>User</th>
                                                    <th>Contact</th>
                                                    <th>Role</th>
                                                    <th>Branch</th>
                                                    <th>Status</th>
                                                    <th>Hire Date</th>
                                                    <th>Last Login</th>
                                                    <?php if ($can_manage_users): ?>
                                                    <th>Actions</th>
                                                    <?php endif; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($user = $users_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="user-avatar me-3">
                                                                <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                                                <div class="text-muted small">
                                                                    <?php echo htmlspecialchars($user['username'] ?: $user['email']); ?>
                                                                </div>
                                                                <div class="text-muted small">
                                                                    ID: <?php echo $user['staff_number'] ?: 'N/A'; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <i class="ri-mail-line me-1"></i>
                                                            <?php echo htmlspecialchars($user['email']); ?>
                                                        </div>
                                                        <div class="text-muted small">
                                                            <i class="ri-phone-line me-1"></i>
                                                            <?php echo htmlspecialchars($user['phone_primary']); ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary-subtle text-primary">
                                                            <?php echo htmlspecialchars($user['user_role_display']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php echo htmlspecialchars($user['branch_name'] ?: 'Not Assigned'); ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $status_class = match($user['status']) {
                                                            'ACTIVE' => 'status-active',
                                                            'INACTIVE' => 'status-inactive',
                                                            'PENDING' => 'status-pending',
                                                            'SUSPENDED' => 'status-suspended',
                                                            default => 'status-inactive'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $status_class; ?>">
                                                            <?php echo ucfirst(strtolower($user['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php echo $user['hire_date'] ? date('M j, Y', strtotime($user['hire_date'])) : 'N/A'; ?>
                                                    </td>
                                                    <td>
                                                        <?php if($user['last_login']): ?>
                                                            <span class="text-success small">
                                                                <?php echo date('M j, g:i A', strtotime($user['last_login'])); ?>
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="text-muted small">Never</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <?php if ($can_manage_users): ?>
                                                    <td>
                                                        <div class="action-buttons">
                                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                    onclick="viewUser(<?php echo $user['user_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                                    onclick="editUser(<?php echo $user['user_id']; ?>)"
                                                                    title="Edit User">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <?php if($user['status'] === 'ACTIVE'): ?>
                                                            <button type="button" class="btn btn-sm btn-outline-warning" 
                                                                    onclick="toggleUserStatus(<?php echo $user['user_id']; ?>, 'INACTIVE')"
                                                                    title="Deactivate User">
                                                                <i class="ri-user-forbid-line"></i>
                                                            </button>
                                                            <?php else: ?>
                                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                                    onclick="toggleUserStatus(<?php echo $user['user_id']; ?>, 'ACTIVE')"
                                                                    title="Activate User">
                                                                <i class="ri-user-line"></i>
                                                            </button>
                                                            <?php endif; ?>
                                                            <button type="button" class="btn btn-sm btn-outline-info" 
                                                                    onclick="resetPassword(<?php echo $user['user_id']; ?>)"
                                                                    title="Reset Password">
                                                                <i class="ri-lock-password-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                    <?php endif; ?>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- User Details Modal -->
    <?php if ($can_manage_users): ?>
    <div class="modal fade" id="userDetailsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">User Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userDetailsContent">
                    <!-- Content will be loaded via AJAX -->
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- DataTables JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        let usersTable;
        const canManageUsers = <?php echo $can_manage_users ? 'true' : 'false'; ?>;
        
        $(document).ready(function() {
            // Initialize DataTable
            const tableConfig = {
                responsive: true,
                pageLength: 25,
                order: [[0, 'asc']]
            };
            
            // Only make actions column non-orderable if user can manage users
            if (canManageUsers) {
                tableConfig.columnDefs = [
                    { orderable: false, targets: [7] }
                ];
            }
            
            usersTable = $('#usersTable').DataTable(tableConfig);

            // Status filter
            $('#statusFilter').on('change', function() {
                usersTable.column(4).search(this.value).draw();
            });

            // Role filter
            $('#roleFilter').on('change', function() {
                usersTable.column(2).search(this.value).draw();
            });
        });

        <?php if ($can_manage_users): ?>
        function viewUser(userId) {
            // Show loading
            $('#userDetailsContent').html('<div class="text-center p-4"><div class="spinner-border text-primary"></div></div>');
            $('#userDetailsModal').modal('show');
            
            // Load user details via AJAX
            $.ajax({
                url: 'ajax/get_user_details.php',
                type: 'POST',
                data: { user_id: userId },
                success: function(response) {
                    $('#userDetailsContent').html(response);
                },
                error: function() {
                    $('#userDetailsContent').html('<div class="alert alert-danger">Error loading user details</div>');
                }
            });
        }

        function editUser(userId) {
            window.location.href = 'edit_user.php?id=' + userId;
        }

        function toggleUserStatus(userId, newStatus) {
            const action = newStatus === 'ACTIVE' ? 'activate' : 'deactivate';
            const title = newStatus === 'ACTIVE' ? 'Activate User' : 'Deactivate User';
            const text = `Are you sure you want to ${action} this user?`;
            
            Swal.fire({
                title: title,
                text: text,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: `Yes, ${action}!`
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/toggle_user_status.php',
                        type: 'POST',
                        data: {
                            user_id: userId,
                            status: newStatus
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success!',
                                    text: response.message
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error!',
                                    text: response.message
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: 'An error occurred while updating user status'
                            });
                        }
                    });
                }
            });
        }

        function resetPassword(userId) {
            Swal.fire({
                title: 'Reset Password',
                text: 'This will generate a new temporary password for the user.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, reset password!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/reset_user_password.php',
                        type: 'POST',
                        data: { user_id: userId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Password Reset!',
                                    html: `New temporary password: <strong>${response.new_password}</strong><br><small class="text-muted">User will be required to change this on next login</small>`
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error!',
                                    text: response.message
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: 'An error occurred while resetting password'
                            });
                        }
                    });
                }
            });
        }
        <?php endif; ?>
    </script>
</body>
</html>