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

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

// Get users list with their roles
$sql = "SELECT u.*, ur.role_name, 
        CASE 
            WHEN u.verified = 1 AND u.failed_attempts < 3 THEN 'ACTIVE'
            WHEN u.verified = 2 THEN 'SUSPENDED'
            WHEN u.failed_attempts >= 3 THEN 'SUSPENDED'
        END as status
        FROM users u 
        LEFT JOIN user_role ur ON u.role_id = ur.role_id 
        ORDER BY u.full_name";
$result = $conn->query($sql);
$users = $result->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Users Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Users Management')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">System Users</h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_user.php" class="btn btn-success btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Add New User
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="users-table" class="table table-bordered nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Username</th>
                                                    <th>Email</th>
                                                    <th>Role</th>
                                                    <th>Status</th>
                                                    <th>Last Active</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($users as $user): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="avatar-xs me-2">
                                                                <div class="avatar-title bg-light rounded-circle text-primary">
                                                                    <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                                                                </div>
                                                            </div>
                                                            <?php echo htmlspecialchars($user['full_name']); ?>
                                                        </div>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($user['username']); ?></td>
                                                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                                                    <td><?php echo htmlspecialchars($user['role_name']); ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php 
                                                            echo $user['status'] === 'ACTIVE' ? 'success' : 
                                                                ($user['status'] === 'PENDING' ? 'warning' : 'danger'); 
                                                        ?>">
                                                            <?php echo $user['status']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php echo $user['last_active'] ? 
                                                            date('d M Y H:i', strtotime($user['last_active'])) : 
                                                            'Never'; ?>
                                                    </td>
                                                    <td>
                                                        <div class="dropdown d-inline-block">
                                                            <button class="btn btn-soft-secondary btn-sm dropdown" 
                                                                    type="button" data-bs-toggle="dropdown" 
                                                                    aria-expanded="false">
                                                                <i class="ri-more-fill align-middle"></i>
                                                            </button>
                                                            <ul class="dropdown-menu dropdown-menu-end">
                                                                <li>
                                                                    <a href="user_profile.php?id=<?php echo $user['user_id']; ?>" 
                                                                       class="dropdown-item">
                                                                        <i class="ri-eye-fill align-bottom me-2 text-muted"></i> View
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a href="user_profile.php?id=<?php echo $user['user_id']; ?>" 
                                                                       class="dropdown-item">
                                                                        <i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a href="javascript:void(0);" 
                                                                       class="dropdown-item" 
                                                                       onclick="resetPassword(<?php echo $user['user_id']; ?>)">
                                                                        <i class="ri-lock-password-line align-bottom me-2 text-muted"></i> 
                                                                        Reset Password
                                                                    </a>
                                                                </li>
                                                                <div class="dropdown-divider"></div>
                                                                <?php if ($user['status'] !== 'SUSPENDED'): ?>
                                                                <li>
                                                                    <a href="javascript:void(0);" 
                                                                       class="dropdown-item text-danger"
                                                                       onclick="suspendUser(<?php echo $user['user_id']; ?>)">
                                                                        <i class="ri-close-circle-line align-bottom me-2 text-danger"></i>
                                                                        Suspend
                                                                    </a>
                                                                </li>
                                                                <?php else: ?>
                                                                <li>
                                                                    <a href="javascript:void(0);" 
                                                                       class="dropdown-item text-success"
                                                                       onclick="activateUser(<?php echo $user['user_id']; ?>)">
                                                                        <i class="ri-check-double-line align-bottom me-2 text-success"></i>
                                                                        Activate
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#users-table').DataTable({
                responsive: true,
                lengthMenu: [10, 25, 50, 75, 100],
                language: {
                    search: "Search users:",
                    lengthMenu: "Show _MENU_ users"
                }
            });
        });

        function suspendUser(userId) {
            Swal.fire({
                title: 'Suspend User?',
                text: 'Are you sure you want to suspend this user?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Suspend',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('suspend_user.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({user_id: userId})
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success',
                                text: 'User has been suspended'
                            }).then(() => location.reload());
                        } else {
                            throw new Error(data.error);
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: error.message
                        });
                    });
                }
            });
        }

        function activateUser(userId) {
            Swal.fire({
                title: 'Activate User?',
                text: 'Are you sure you want to activate this user?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Activate',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('activate_user.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({user_id: userId})
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success',
                                text: 'User has been activated'
                            }).then(() => location.reload());
                        } else {
                            throw new Error(data.error);
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: error.message
                        });
                    });
                }
            });
        }

        function resetPassword(userId) {
            Swal.fire({
                title: 'Reset Password?',
                text: 'This will send password reset instructions to the user\'s email.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Reset',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('reset_password.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({user_id: userId})
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success',
                                text: 'Password reset instructions have been sent'
                            });
                        } else {
                            throw new Error(data.error);
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: error.message
                        });
                    });
                }
            });
        }
    </script>
</body>
</html>