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

header('Content-Type: application/json');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$action = trim($_REQUEST['action'] ?? 'get_customers');
$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];

// ACTION: LẤY CHI TIẾT ĐƠN HÀNG
if ($action == 'get_order_details') {
    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    if ($order_id > 0) {
        $stmt = $conn->prepare("SELECT detail_order FROM cms_orders WHERE ID = ?");
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        $order = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($order && !empty($order['detail_order'])) {
            $products_in_order = json_decode($order['detail_order'], true);
            $product_ids = array_column($products_in_order, 'id');
            if (!empty($product_ids)) {
                $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
                $types = str_repeat('i', count($product_ids));
                $sql_products = "SELECT ID, prd_code, prd_name FROM cms_products WHERE ID IN ($ids_placeholder)";
                $stmt_products = $conn->prepare($sql_products);
                $stmt_products->bind_param($types, ...$product_ids);
                $stmt_products->execute();
                $products_info_result = $stmt_products->get_result();
                $products_info = [];
                while($row = $products_info_result->fetch_assoc()) { $products_info[$row['ID']] = $row; }
                $stmt_products->close();
                foreach($products_in_order as &$item) {
                    if (isset($products_info[$item['id']])) {
                        $item['prd_name'] = $products_info[$item['id']]['prd_name'];
                        $item['prd_code'] = $products_info[$item['id']]['prd_code'];
                    }
                }
            }
            echo json_encode(['status' => 'success', 'data' => $products_in_order]);
        } else { echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy chi tiết đơn hàng.']); }
    } else { echo json_encode(['status' => 'error', 'message' => 'ID đơn hàng không hợp lệ.']); }
    exit();
}

// ACTION: LƯU KHÁCH HÀNG (THÊM MỚI & CẬP NHẬT)
if ($action == 'save_customer') {
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $customer_name = trim($_POST['customer_name'] ?? '');
    if (empty($customer_name)) {
        echo json_encode(['status' => 'error', 'message' => 'Tên khách hàng là bắt buộc.']);
        exit();
    }
    
    // **YÊU CẦU**: Lấy dữ liệu Mã số thuế (notes) và Nhóm KH (customer_group) từ form
    $customer_code = trim($_POST['customer_code'] ?? '');
    $customer_group = intval($_POST['customer_group'] ?? 1); // Dữ liệu Nhóm KH
    $customer_phone = trim($_POST['customer_phone'] ?? '');
    $customer_email = trim($_POST['customer_email'] ?? '');
    $customer_addr = trim($_POST['customer_addr'] ?? '');
    $notes = trim($_POST['notes'] ?? ''); // Dữ liệu Mã số thuế
    $user_id = $_SESSION['user_id'] ?? 0;
    
    if ($customer_id > 0) {
        // Cập nhật khách hàng, bao gồm cả nhóm và mã số thuế
        $sql = "UPDATE cms_customers SET customer_code=?, customer_name=?, customer_group=?, customer_phone=?, customer_email=?, customer_addr=?, notes=? WHERE ID=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssissssi', $customer_code, $customer_name, $customer_group, $customer_phone, $customer_email, $customer_addr, $notes, $customer_id);
    } else {
        // Tự động sinh mã KH nếu để trống
        if (empty($customer_code)) {
            $last_id_result = $conn->query("SELECT ID FROM cms_customers ORDER BY ID DESC LIMIT 1");
            $last_id = $last_id_result && $last_id_result->num_rows > 0 ? $last_id_result->fetch_row()[0] : 0;
            $customer_code = 'KH' . str_pad($last_id + 1, 5, '0', STR_PAD_LEFT);
        }
        // Thêm khách hàng mới, bao gồm cả nhóm và mã số thuế
        $sql = "INSERT INTO cms_customers (customer_code, customer_name, customer_group, customer_phone, customer_email, customer_addr, notes, user_init) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssissssi', $customer_code, $customer_name, $customer_group, $customer_phone, $customer_email, $customer_addr, $notes, $user_id);
    }

    if ($stmt && $stmt->execute()) {
        $response = ['status' => 'success', 'message' => $customer_id > 0 ? 'Cập nhật thành công!' : 'Thêm mới thành công!'];
    } else {
        $response['message'] = 'Lỗi khi lưu: ' . ($stmt ? $stmt->error : $conn->error);
    }
    if($stmt) $stmt->close();
    echo json_encode($response);
    exit();
}

// ACTION: LẤY CHI TIẾT MỘT KHÁCH HÀNG ĐỂ SỬA
if ($action == 'get_customer_details') {
    $customer_id = intval($_GET['id'] ?? 0);
    if ($customer_id > 0) {
        // **YÊU CẦU**: Lấy tất cả thông tin KH, bao gồm `notes` và `customer_group` để điền vào form sửa
        $stmt = $conn->prepare("SELECT * FROM cms_customers WHERE ID = ?");
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $customer = $stmt->get_result()->fetch_assoc();
        if ($customer) { $response = ['status' => 'success', 'data' => $customer]; }
        else { $response['message'] = 'Không tìm thấy khách hàng.'; }
        $stmt->close();
    } else { $response['message'] = 'ID khách hàng không hợp lệ.'; }
    echo json_encode($response);
    exit();
}

// ACTION: XÓA KHÁCH HÀNG
if ($action == 'delete_customer') {
    $customer_id = intval($_POST['id'] ?? 0);
    if ($customer_id > 0) {
        $stmt = $conn->prepare("DELETE FROM cms_customers WHERE ID = ?");
        $stmt->bind_param("i", $customer_id);
        if ($stmt->execute()) { $response = ['status' => 'success', 'message' => 'Xóa khách hàng thành công!']; }
        else { $response = ['status' => 'error', 'message' => 'Lỗi khi xóa khách hàng.']; }
        $stmt->close();
    } else { $response['message'] = 'ID khách hàng không hợp lệ.'; }
    echo json_encode($response);
    exit();
}
// ACTION: THU NỢ KHÁCH HÀNG
if ($action == 'collect_debt') {
    $order_id = intval($_POST['order_id'] ?? 0);
    $amount = intval($_POST['amount'] ?? 0);
    $receipt_date = $_POST['receipt_date'] ?? date('Y-m-d H:i:s');
    $notes = trim($_POST['notes'] ?? '');
    $payment_method = intval($_POST['payment_method'] ?? 1);
    $user_id = $_SESSION['user_id'] ?? 0;
    if ($order_id <= 0 || $amount <= 0) { echo json_encode(['status' => 'error', 'message' => 'Dữ liệu không hợp lệ.']); exit(); }
    $conn->begin_transaction();
    try {
        $order_stmt = $conn->prepare("SELECT lack FROM cms_orders WHERE ID = ?");
        $order_stmt->bind_param("i", $order_id);
        $order_stmt->execute();
        $order_data = $order_stmt->get_result()->fetch_assoc();
        if (!$order_data || $amount > $order_data['lack']) { throw new Exception("Số tiền thu không thể lớn hơn số tiền còn nợ."); }
        $order_stmt->close();
        $last_id_result = $conn->query("SELECT ID FROM cms_receipt ORDER BY ID DESC LIMIT 1");
        $last_id = $last_id_result && $last_id_result->num_rows > 0 ? $last_id_result->fetch_row()[0] : 0;
        $receipt_code = 'PT' . str_pad($last_id + 1, 6, '0', STR_PAD_LEFT);
        $receipt_sql = "INSERT INTO cms_receipt (order_id, receipt_code, type_id, store_id, receipt_date, notes, receipt_method, total_money, user_init) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $receipt_stmt = $conn->prepare($receipt_sql);
        $type_id = 1; $store_id = 1;
        $receipt_stmt->bind_param("isissidii", $order_id, $receipt_code, $type_id, $store_id, $receipt_date, $notes, $payment_method, $amount, $user_id);
        $receipt_stmt->execute();
        $receipt_stmt->close();
        $update_order_sql = "UPDATE cms_orders SET lack = lack - ?, customer_pay = customer_pay + ? WHERE ID = ?";
        $update_stmt = $conn->prepare($update_order_sql);
        $update_stmt->bind_param("iii", $amount, $amount, $order_id);
        $update_stmt->execute();
        $update_stmt->close();
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Thu nợ thành công!']);
    } catch (Exception $e) { $conn->rollback(); echo json_encode(['status' => 'error', 'message' => 'Lỗi khi thu nợ: ' . $e->getMessage()]); }
    exit();
}

// ACTION CHÍNH: LẤY DỮ LIỆU DANH SÁCH KHÁCH HÀNG
if ($action == 'get_customers') {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);

    function json_error($message, $draw_request) {
        echo json_encode([
            "draw" => $draw_request,
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => [],
            "error" => $message
        ]);
        exit;
    }

    $summary = [];
    $summary['total_customers'] = $conn->query("SELECT COUNT(ID) FROM cms_customers")->fetch_row()[0] ?? 0;
    $debt_revenue_query = $conn->query("SELECT COUNT(DISTINCT customer_id) as buying_customers, SUM(total_money) as total_revenue FROM cms_orders WHERE deleted = 0")->fetch_assoc();
    $summary['buying_customers'] = $debt_revenue_query['buying_customers'] ?? 0;
    $summary['total_revenue'] = $debt_revenue_query['total_revenue'] ?? 0;
    $debt_query = $conn->query("SELECT COUNT(DISTINCT customer_id) as debt_customers, SUM(lack) as total_debt FROM cms_orders WHERE lack > 0 AND deleted = 0")->fetch_assoc();
    $summary['debt_customers'] = $debt_query['debt_customers'] ?? 0;
    $summary['total_debt'] = $debt_query['total_debt'] ?? 0;

    $baseQuery = "FROM cms_customers c";
    $whereClauses = [];
    $params = [];
    $types = '';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(c.customer_name LIKE ? OR c.customer_code LIKE ? OR c.customer_phone LIKE ?)";
        $searchTermWildcard = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTermWildcard, $searchTermWildcard, $searchTermWildcard);
        $types .= 'sss';
    }
    if (isset($_POST['group_id']) && $_POST['group_id'] !== '') {
        $whereClauses[] = "c.customer_group = ?";
        $params[] = $_POST['group_id'];
        $types .= 'i';
    }
    $whereSql = !empty($whereClauses) ? " WHERE " . implode(" AND ", $whereClauses) : "";

    $group_name_case_sql = "CASE c.customer_group WHEN 1 THEN 'Khách lẻ' WHEN 0 THEN 'Khách sỉ' ELSE '' END";

    $subqueries = "(SELECT MAX(o.sell_date) FROM cms_orders o WHERE o.customer_id = c.ID AND o.deleted = 0) as last_purchase_date,
                   (SELECT SUM(o.total_money) FROM cms_orders o WHERE o.customer_id = c.ID AND o.deleted = 0) as total_revenue,
                   (SELECT SUM(o.lack) FROM cms_orders o WHERE o.customer_id = c.ID AND o.deleted = 0) as total_debt";

    $fullQueryInner = "SELECT c.ID, c.notes, ({$group_name_case_sql}) AS group_name, c.customer_code, c.customer_name, c.customer_phone, c.customer_addr, c.customer_group, $subqueries " . $baseQuery . $whereSql;

    $outerWhereClause = '';
    if (isset($_POST['debt_status']) && $_POST['debt_status'] === 'debt') {
        $outerWhereClause = " WHERE total_debt > 0";
    } elseif (isset($_POST['debt_status']) && $_POST['debt_status'] === 'no_debt') {
        $outerWhereClause = " WHERE (total_debt <= 0 OR total_debt IS NULL)";
    }

    $countQuery = "SELECT COUNT(*) as total FROM ({$fullQueryInner}) AS sub_query" . $outerWhereClause;

    $stmtFiltered = $conn->prepare($countQuery);
    if ($stmtFiltered === false) { json_error("Lỗi SQL (countQuery): " . $conn->error, $draw); }
    if (!empty($types)) { $stmtFiltered->bind_param($types, ...$params); }
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_assoc()['total'];
    $stmtFiltered->close();

    $dataQuery = "SELECT * FROM ({$fullQueryInner}) AS sub_query" . $outerWhereClause . " ORDER BY ID DESC LIMIT ?, ?";

    $data_types = $types . 'ii';
    $data_params = array_merge($params, [$start, $length]);

    $stmt_data = $conn->prepare($dataQuery);
    if ($stmt_data === false) { json_error("Lỗi SQL (dataQuery): " . $conn->error, $draw); }
    $stmt_data->bind_param($data_types, ...$data_params);
    $stmt_data->execute();
    $data = $stmt_data->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_data->close();

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($summary['total_customers']),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "summary" => $summary
    ]);
    exit;
}

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