<?php
// File: /quanlybanhang/ajax/users_ajax.php

require_once __DIR__ . '/../core/init.php';

header('Content-Type: application/json; charset=utf-8');
$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];
$conn->begin_transaction(); 

// Hàm hỗ trợ upload ảnh
function uploadImage($file) {
    if (!isset($file['name']) || $file['error'] != 0) return null;
    $target_dir = __DIR__ . "/../../uploads/cccd/"; 
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $new_name = 'cccd_' . time() . '_' . rand(100, 999) . '.' . $ext;
    $target_file = $target_dir . $new_name;
    
    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        return "uploads/cccd/" . $new_name; 
    }
    return null;
}

try {
    if (isset($_POST['action']) && $_POST['action'] == 'add_user') {
        if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['display_name'])) {
            $response['message'] = 'Vui lòng điền thông tin bắt buộc (*).';
        } else {
            // Nhận dữ liệu
            $username = trim($_POST['username']);
            $email = trim($_POST['email']);
            $password = $_POST['password'];
            $display_name = trim($_POST['display_name']);
            $group_id = intval($_POST['group_id']);
            $store_id = intval($_POST['store_id']);
            $commission = floatval($_POST['commission'] ?? 0);
            
            // Dữ liệu bổ sung
            $phone = trim($_POST['phone'] ?? '');
            $address = trim($_POST['address'] ?? '');
            $cccd = trim($_POST['cccd'] ?? '');
            $job_title = trim($_POST['job_title'] ?? '');
            $bank_account = trim($_POST['bank_account'] ?? '');
            $allowance = isset($_POST['allowance']) ? str_replace(',', '', $_POST['allowance']) : 0;

            // Check trùng
            $stmt_check = $conn->prepare("SELECT id FROM cms_users WHERE username = ? OR (email != '' AND email = ?)");
            $stmt_check->bind_param("ss", $username, $email);
            $stmt_check->execute();
            if ($stmt_check->get_result()->fetch_assoc()) {
                $response['message'] = 'Mã nhân viên (username) hoặc Email đã tồn tại.';
            } else {
                // Upload ảnh
                $cccd_image = isset($_FILES['cccd_image']) ? uploadImage($_FILES['cccd_image']) : null;
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // INSERT dữ liệu (Chưa có user_code)
                $sql = "INSERT INTO cms_users (username, password, email, display_name, phone, address, cccd, cccd_image, bank_account, job_title, allowance, user_status, group_id, commission, store_id, created, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, NOW(), NOW())";
                
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ssssssssssdidi", $username, $hashed_password, $email, $display_name, $phone, $address, $cccd, $cccd_image, $bank_account, $job_title, $allowance, $group_id, $commission, $store_id);
                
                if ($stmt->execute()) {
                    // --- ĐOẠN MỚI: TỰ ĐỘNG SINH MÃ USER_CODE (NV...) ---
                    $new_user_id = $stmt->insert_id;
                    $auto_code = 'NV' . str_pad($new_user_id, 3, '0', STR_PAD_LEFT); // Ví dụ: ID 38 -> NV038
                    $conn->query("UPDATE cms_users SET user_code = '$auto_code' WHERE id = $new_user_id");
                    // ----------------------------------------------------

                    $response = ['status' => 'success', 'message' => 'Thêm nhân viên thành công! Mã hệ thống: ' . $auto_code];
                } else {
                    $response['message'] = 'Lỗi CSDL: ' . $stmt->error;
                }
                $stmt->close();
            }
            $stmt_check->close();
        }
    }
    
    // GET DETAILS
    else if (isset($_GET['action']) && $_GET['action'] == 'get_user_details') {
        $user_id = intval($_GET['user_id'] ?? 0);
        $sql = "SELECT id, username, display_name, email, phone, address, cccd, cccd_image, bank_account, job_title, allowance, group_id, store_id, commission FROM cms_users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $user_id); 
        $stmt->execute(); 
        $data = $stmt->get_result()->fetch_assoc();
        if ($data) { $response = ['status' => 'success', 'data' => $data]; } 
        else { $response['message'] = 'Không tìm thấy nhân viên.'; }
        $stmt->close();
    }
    
    // EDIT USER
    else if (isset($_POST['action']) && $_POST['action'] == 'edit_user') {
        $user_id = intval($_POST['user_id'] ?? 0);
        
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $display_name = trim($_POST['display_name']);
        $group_id = intval($_POST['group_id']);
        $store_id = intval($_POST['store_id']);
        $commission = floatval($_POST['commission'] ?? 0);
        $password = $_POST['password'];
        
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $cccd = trim($_POST['cccd'] ?? '');
        $job_title = trim($_POST['job_title'] ?? '');
        $bank_account = trim($_POST['bank_account'] ?? '');
        $allowance = isset($_POST['allowance']) ? str_replace(',', '', $_POST['allowance']) : 0;

        if (empty($user_id) || empty($username) || empty($display_name)) {
            $response['message'] = 'Thiếu thông tin bắt buộc.';
        } else {
            $stmt_check = $conn->prepare("SELECT id FROM cms_users WHERE (username = ? OR (email != '' AND email = ?)) AND id != ?");
            $stmt_check->bind_param("ssi", $username, $email, $user_id);
            $stmt_check->execute();
            if ($stmt_check->get_result()->fetch_assoc()) {
                 $response['message'] = 'Thông tin đăng nhập đã trùng với người khác.';
            } else {
                $new_image = isset($_FILES['cccd_image']) ? uploadImage($_FILES['cccd_image']) : null;
                
                $sql = "UPDATE cms_users SET username=?, email=?, display_name=?, phone=?, address=?, cccd=?, bank_account=?, job_title=?, allowance=?, group_id=?, store_id=?, commission=?";
                $types = "ssssssssdidi";
                $params = [$username, $email, $display_name, $phone, $address, $cccd, $bank_account, $job_title, $allowance, $group_id, $store_id, $commission];

                if (!empty($password)) {
                    $sql .= ", password=?";
                    $types .= "s";
                    $params[] = password_hash($password, PASSWORD_DEFAULT);
                }
                if ($new_image) {
                    $sql .= ", cccd_image=?";
                    $types .= "s";
                    $params[] = $new_image;
                }
                
                $sql .= " WHERE id=?";
                $types .= "i";
                $params[] = $user_id;

                $stmt = $conn->prepare($sql);
                $stmt->bind_param($types, ...$params); 
                
                if ($stmt->execute()) { 
                    // Cập nhật lại user_code nếu bị thiếu (Fix lỗi user cũ)
                    $check_code = $conn->query("SELECT user_code FROM cms_users WHERE id = $user_id")->fetch_assoc();
                    if(empty($check_code['user_code'])) {
                        $fix_code = 'NV' . str_pad($user_id, 3, '0', STR_PAD_LEFT);
                        $conn->query("UPDATE cms_users SET user_code = '$fix_code' WHERE id = $user_id");
                    }
                    $response = ['status' => 'success', 'message' => 'Cập nhật thành công!']; 
                } 
                else { $response['message'] = 'Lỗi cập nhật: ' . $stmt->error; }
                $stmt->close();
            }
            $stmt_check->close();
        }
    }
    
    // DELETE USER
    else if (isset($_POST['action']) && $_POST['action'] == 'delete_user') {
        $user_id = intval($_POST['user_id'] ?? 0);
        if ($user_id == 1) { $response['message'] = 'Không thể xóa Admin!'; } 
        else if ($user_id > 0) {
            $conn->query("DELETE FROM cms_users WHERE id = $user_id");
            $response = ['status' => 'success', 'message' => 'Xóa thành công!'];
        }
    }
    
    $conn->commit();
} catch (Exception $e) {
    $conn->rollback();
    $response['message'] = 'Lỗi hệ thống: ' . $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>