<?php
require_once __DIR__ . '/../../templates/header.php';

// LẤY DỮ LIỆU TỪ DATABASE
$sql_users = "SELECT u.id, u.username AS ma_nhan_vien, u.display_name AS ten_nhan_vien, u.email, u.commission AS he_so_thuong, u.user_status, g.group_name FROM cms_users AS u LEFT JOIN cms_users_group AS g ON u.group_id = g.id ORDER BY u.id ASC";
$staff_list = $conn->query($sql_users)->fetch_all(MYSQLI_ASSOC);

$sql_groups = "SELECT id, group_name FROM cms_users_group ORDER BY group_name ASC";
$user_groups_list = $conn->query($sql_groups)->fetch_all(MYSQLI_ASSOC);

$sql_stores = "SELECT ID, store_name FROM cms_stores ORDER BY store_name ASC";
$stores_list = $conn->query($sql_stores)->fetch_all(MYSQLI_ASSOC);
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<style>
    .nav-tabs .nav-link.active { font-weight: bold; color: #4e73df; }
    #dataTableNhanVien thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #dataTableNhanVien tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #dataTableNhanVien tbody tr:hover { background-color: #eaecf4; }
    .modal-header { background-color: #f8f9fc; border-bottom: 1px solid #e3e6f0; }
    .modal-title { font-weight: 600; color: #3a3b45; }
    .form-label { font-weight: 500; color: #6c757d; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý người dùng</h1>

    <ul class="nav nav-tabs mb-4">
        <li class="nav-item"><a class="nav-link active" href="/quanlybanhang/modules/users/list.php"><i class="fas fa-user fa-sm me-2"></i>Nhân viên</a></li>
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/users/permissions.php"><i class="fas fa-user-shield fa-sm me-2"></i>Phân quyền</a></li>
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/settings/print_config.php"><i class="fas fa-print fa-sm me-2"></i>Cài đặt trang in</a></li>
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/stores/list.php"><i class="fas fa-warehouse fa-sm me-2"></i>Quản lý kho</a></li>
    </ul>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách nhân viên</h6>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#userModal" id="btnOpenAddModal">
                <i class="fas fa-plus fa-sm"></i> Tạo nhân viên
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="dataTableNhanVien" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>#</th><th>Mã nhân viên</th><th>Tên nhân viên</th><th>Email</th><th>Hệ số thưởng</th><th>Nhóm</th><th>Trạng thái</th><th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($staff_list)): foreach ($staff_list as $index => $staff): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($staff['ma_nhan_vien']); ?></td>
                                <td><?php echo htmlspecialchars($staff['ten_nhan_vien']); ?></td>
                                <td><?php echo htmlspecialchars($staff['email']); ?></td>
                                <td><?php echo htmlspecialchars($staff['he_so_thuong']); ?></td>
                                <td><?php echo htmlspecialchars($staff['group_name'] ?? 'Chưa phân nhóm'); ?></td>
                                <td><?php echo ($staff['user_status'] == 1) ? '<span class="badge bg-success">Hoạt động</span>' : '<span class="badge bg-secondary">Tạm khóa</span>'; ?></td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm">
                                        <a href="#" class="btn btn-warning btn-edit" data-id="<?php echo $staff['id']; ?>" title="Sửa"><i class="fas fa-edit"></i></a>
                                        <a href="#" class="btn btn-danger btn-delete" data-id="<?php echo $staff['id']; ?>" title="Xóa"><i class="fas fa-trash"></i></a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="8" class="text-center">Không tìm thấy nhân viên nào.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="userForm">
                <input type="hidden" id="user_id" name="user_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">Tạo nhân viên</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label for="display_name" class="form-label">Tên nhân viên <span class="text-danger">*</span></label><input type="text" class="form-control" id="display_name" name="display_name" required></div>
                        <div class="col-md-6 mb-3"><label for="username" class="form-label">Mã nhân viên (đăng nhập) <span class="text-danger">*</span></label><input type="text" class="form-control" id="username" name="username" required></div>
                        <div class="col-md-6 mb-3"><label for="email" class="form-label">Email <span class="text-danger">*</span></label><input type="email" class="form-control" id="email" name="email" required></div>
                        <div class="col-md-6 mb-3"><label for="commission" class="form-label">Hệ số thưởng</label><input type="number" step="0.1" class="form-control" id="commission" name="commission" value="0"></div>
                        <div class="col-md-12 mb-3"><label for="password" class="form-label">Mật khẩu</label><input type="password" class="form-control" id="password" name="password" placeholder="Để trống nếu không muốn đổi"></div>
                        <div class="col-md-6 mb-3"><label for="group_id" class="form-label">Nhóm người dùng <span class="text-danger">*</span></label><select class="form-select" id="group_id" name="group_id" required><?php foreach ($user_groups_list as $group): ?><option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['group_name']); ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-6 mb-3"><label for="store_id" class="form-label">Kho làm việc <span class="text-danger">*</span></label><select class="form-select" id="store_id" name="store_id" required><?php foreach ($stores_list as $store): ?><option value="<?php echo $store['ID']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Bỏ qua</button>
                    <button type="submit" class="btn btn-primary">Lưu</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.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() {
    $('#dataTableNhanVien').DataTable({ "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" } });
    
    $('#group_id, #store_id').select2({ theme: "bootstrap-5", dropdownParent: $('#userModal') });

    $('#btnOpenAddModal').on('click', function() {
        $('#userForm')[0].reset();
        $('#user_id').val('');
        $('#userModalLabel').text('Tạo nhân viên mới');
        $('#password').prop('required', true).attr('placeholder', 'Nhập mật khẩu');
    });

    $('#userForm').on('submit', function(e) {
        e.preventDefault();
        var action = $('#user_id').val() ? 'edit_user' : 'add_user';
        var formData = $(this).serialize() + '&action=' + action;
        
        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', type: 'POST', dataType: 'json', data: formData,
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') location.reload();
            },
            error: function() { alert('Lỗi kết nối đến máy chủ.'); }
        });
    });

    $('#dataTableNhanVien tbody').on('click', 'a.btn-delete', function(e) {
        e.preventDefault();
        var userId = $(this).data('id');
        if (confirm('Bạn có chắc chắn muốn xóa nhân viên này không?')) {
            $.ajax({
                url: '/quanlybanhang/ajax/users_ajax.php', type: 'POST', dataType: 'json', data: { action: 'delete_user', user_id: userId },
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') location.reload();
                }
            });
        }
    });

    $('#dataTableNhanVien tbody').on('click', 'a.btn-edit', function(e) {
        e.preventDefault();
        var userId = $(this).data('id');
        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', type: 'GET', dataType: 'json', data: { action: 'get_user_details', user_id: userId },
            success: function(response) {
                if (response.status === 'success') {
                    var user = response.data;
                    $('#user_id').val(user.id);
                    $('#username').val(user.username);
                    $('#display_name').val(user.display_name);
                    $('#email').val(user.email);
                    $('#group_id').val(user.group_id).trigger('change');
                    $('#store_id').val(user.store_id).trigger('change');
                    $('#commission').val(user.commission);
                    $('#password').prop('required', false).attr('placeholder', 'Để trống nếu không muốn đổi');
                    $('#userModalLabel').text('Chỉnh sửa nhân viên');
                    
                    var userModal = new bootstrap.Modal(document.getElementById('userModal'));
                    userModal.show();
                } else {
                    alert(response.message);
                }
            }
        });
    });
});
</script>