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

// LẤY DỮ LIỆU TỪ DATABASE (Đã cập nhật câu Query lấy thêm thông tin)
$sql_users = "SELECT u.*, 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; white-space: nowrap; }
    #dataTableNhanVien tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #dataTableNhanVien tbody tr:hover { background-color: #eaecf4; }
    .img-cccd-thumb { width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd; cursor: pointer; }
    .modal-header { background-color: #f8f9fc; border-bottom: 1px solid #e3e6f0; }
    .form-label { font-weight: 500; color: #6c757d; font-size: 0.9rem; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý nhân viên</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 table-bordered" id="dataTableNhanVien" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Ảnh</th>
                            <th>Mã NV</th>
                            <th>Họ tên & Chức danh</th>
                            <th>Liên hệ</th>
                            <th>Lương & Thưởng</th>
                            <th>Nhóm & Kho</th>
                            <th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($staff_list)): foreach ($staff_list as $staff): 
                            $img_src = !empty($staff['cccd_image']) ? '/quanlybanhang/' . $staff['cccd_image'] : '/quanlybanhang/assets/img/no-image.png';
                        ?>
                            <tr>
                                <td class="text-center">
                                    <img src="<?php echo $img_src; ?>" class="img-cccd-thumb" alt="CCCD" onclick="window.open(this.src)">
                                </td>
                                <td><?php echo htmlspecialchars($staff['username']); ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($staff['display_name']); ?></strong><br>
                                    <small class="text-primary"><?php echo htmlspecialchars($staff['job_title'] ?? 'N/A'); ?></small><br>
                                    <small class="text-muted">CCCD: <?php echo htmlspecialchars($staff['cccd']); ?></small>
                                </td>
                                <td>
                                    <i class="fas fa-phone fa-xs text-muted"></i> <?php echo htmlspecialchars($staff['phone']); ?><br>
                                    <i class="fas fa-envelope fa-xs text-muted"></i> <?php echo htmlspecialchars($staff['email']); ?><br>
                                    <i class="fas fa-map-marker-alt fa-xs text-muted"></i> <?php echo htmlspecialchars($staff['address']); ?>
                                </td>
                                <td>
                                    HH: <span class="text-danger fw-bold"><?php echo htmlspecialchars($staff['commission']); ?>%</span><br>
                                    P.Cấp: <?php echo number_format($staff['allowance']); ?>đ<br>
                                    <small class="text-muted"><?php echo htmlspecialchars($staff['bank_account']); ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-info"><?php echo htmlspecialchars($staff['group_name'] ?? 'Chưa phân nhóm'); ?></span><br>
                                    <?php if ($staff['user_status'] == 1): ?>
                                        <span class="badge bg-success mt-1">Hoạt động</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary mt-1">Tạm khóa</span>
                                    <?php endif; ?>
                                </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="7" 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" enctype="multipart/form-data"> <input type="hidden" id="user_id" name="user_id">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">Thông tin nhân viên</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <h6 class="text-primary border-bottom pb-1 mb-3">1. Thông tin tài khoản & Công việc</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Mã NV (Đă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-4 mb-3">
                            <label class="form-label">Họ và tê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-4 mb-3">
                            <label class="form-label">Chức danh</label>
                            <input type="text" class="form-control" id="job_title" name="job_title" placeholder="VD: Quản lý, Thu ngân...">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label 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 đổi">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Nhóm quyền <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-4 mb-3">
                            <label 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>

                    <h6 class="text-primary border-bottom pb-1 mb-3 mt-2">2. Lương thưởng & Thanh toán</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Hệ số hoa hồng (%)</label>
                            <input type="number" step="0.1" class="form-control" id="commission" name="commission" value="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Phụ cấp (VNĐ)</label>
                            <input type="text" class="form-control" id="allowance" name="allowance" value="0" onkeyup="this.value=Number(this.value.replace(/\D/g,'')).toLocaleString('en-US')">
                        </div>
                         <div class="col-md-4 mb-3">
                            <label class="form-label">Tài khoản ngân hàng</label>
                            <input type="text" class="form-control" id="bank_account" name="bank_account" placeholder="Tên NH - Số TK">
                        </div>
                    </div>

                    <h6 class="text-primary border-bottom pb-1 mb-3 mt-2">3. Thông tin cá nhân</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label 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-4 mb-3">
                            <label class="form-label">Số điện thoại</label>
                            <input type="text" class="form-control" id="phone" name="phone">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Số CCCD</label>
                            <input type="text" class="form-control" id="cccd" name="cccd">
                        </div>
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Địa chỉ</label>
                            <input type="text" class="form-control" id="address" name="address">
                        </div>
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Ảnh CCCD (Mặt trước)</label>
                            <input type="file" class="form-control" id="cccd_image" name="cccd_image" accept="image/*">
                            <div id="preview_image" class="mt-2"></div>
                        </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" id="btnSaveUser">Lưu thông tin</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<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('');
        $('#preview_image').html('');
        $('#userModalLabel').text('Tạo nhân viên mới');
        $('#password').prop('required', true).attr('placeholder', 'Nhập mật khẩu');
    });

    // SỬ DỤNG AJAX VỚI FORMDATA ĐỂ GỬI ĐƯỢC FILE
    $('#userForm').on('submit', function(e) {
        e.preventDefault();
        var btn = $('#btnSaveUser');
        btn.prop('disabled', true).text('Đang lưu...');

        var action = $('#user_id').val() ? 'edit_user' : 'add_user';
        var formData = new FormData(this); // Tạo FormData từ form
        formData.append('action', action); // Thêm action thủ công

        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', 
            type: 'POST', 
            dataType: 'json', 
            data: formData,
            processData: false, // Bắt buộc khi dùng FormData
            contentType: false, // Bắt buộc khi dùng 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ủ.'); },
            complete: function() { btn.prop('disabled', false).text('Lưu thông tin'); }
        });
    });

    // Lấy thông tin chi tiết
    $('#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 đổi');
                    
                    // Điền dữ liệu mới
                    $('#phone').val(user.phone);
                    $('#cccd').val(user.cccd);
                    $('#job_title').val(user.job_title);
                    $('#address').val(user.address);
                    $('#bank_account').val(user.bank_account);
                    // Format lại số tiền phụ cấp hiển thị
                    $('#allowance').val(Number(user.allowance).toLocaleString('en-US'));

                    if(user.cccd_image){
                        $('#preview_image').html('<img src="/quanlybanhang/'+user.cccd_image+'" style="height:100px; border-radius:4px;">');
                    } else {
                        $('#preview_image').html('');
                    }

                    $('#userModalLabel').text('Chỉnh sửa nhân viên');
                    new bootstrap.Modal(document.getElementById('userModal')).show();
                } else {
                    alert(response.message);
                }
            }
        });
    });

    // Xóa (Giữ nguyên)
    $('#dataTableNhanVien tbody').on('click', 'a.btn-delete', function(e) {
        e.preventDefault();
        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: $(this).data('id') },
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') location.reload();
                }
            });
        }
    });
});
</script>