<?php
// Tắt hiển thị lỗi ra màn hình để tránh làm hỏng cấu trúc JSON trả về cho DataTables
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'get_products_list':
        handle_get_products_list($conn);
        break;
    case 'search_products_for_barcode':
        handle_search_products_for_barcode($conn);
        break;
    case 'get_product_details':
        handle_get_product_details($conn);
        break;
    case 'edit_product':
        handle_edit_product($conn);
        break;
    case 'delete_product':
        handle_delete_product($conn);
        break;
    case 'toggle_product_status':
        handle_toggle_product_status($conn);
        break;
    // --- CHỨC NĂNG SỬA GIÁ (GIỮ NGUYÊN) ---
    case 'update_product_prices':
        handle_update_product_prices($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

// --- HÀM SỬA GIÁ NHANH (GIỮ NGUYÊN) ---
function handle_update_product_prices($conn) {
    $product_id = intval($_POST['product_id'] ?? 0);
    $sell_price = floatval($_POST['sell_price'] ?? 0);
    $sell_price2 = floatval($_POST['sell_price2'] ?? 0);

    if ($product_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID sản phẩm không hợp lệ.']);
        return;
    }

    $stmt = $conn->prepare("UPDATE cms_products SET prd_sell_price = ?, prd_sell_price2 = ?, updated = NOW() WHERE ID = ?");
    $stmt->bind_param("ddi", $sell_price, $sell_price2, $product_id);

    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Đã cập nhật giá bán thành công!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi DB: ' . $stmt->error]);
    }
    $stmt->close();
}

function handle_toggle_product_status($conn) {
    $product_id = intval($_POST['product_id'] ?? 0);
    $current_status = intval($_POST['current_status'] ?? -1);

    if ($product_id <= 0 || !in_array($current_status, [0, 1])) {
        echo json_encode(['status' => 'error', 'message' => 'Dữ liệu không hợp lệ.']);
        return;
    }

    $new_status = $current_status == 1 ? 0 : 1;

    $stmt = $conn->prepare("UPDATE cms_products SET prd_status = ? WHERE ID = ?");
    $stmt->bind_param("ii", $new_status, $product_id);

    if ($stmt->execute()) {
        $message = $new_status == 0 ? 'Đã ngừng kinh doanh sản phẩm thành công!' : 'Đã khôi phục kinh doanh sản phẩm thành công!';
        echo json_encode(['status' => 'success', 'message' => $message]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi cập nhật trạng thái.']);
    }
    $stmt->close();
}

function handle_search_products_for_barcode($conn) {
    $term = $_GET['term'] ?? '';
    if (strlen($term) < 1) {
        echo json_encode([]);
        exit;
    }
    $searchTerm = "%" . $term . "%";
    
    $sql = "SELECT ID, prd_code, prd_name, prd_sell_price 
            FROM cms_products 
            WHERE (prd_name LIKE ? OR prd_code LIKE ?) 
            AND deleted = 0 AND prd_status = 1 
            LIMIT 15";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $searchTerm, $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $response_data = [];
    foreach($products as $p) {
        $response_data[] = ['id' => $p['ID'], 'code' => $p['prd_code'], 'name' => $p['prd_name'], 'price' => $p['prd_sell_price']];
    }
    
    echo json_encode($response_data);
}

// --- ĐÃ SỬA: LOẠI BỎ SIZE, COLOR, IMAGE ĐỂ TRÁNH LỖI DATA TABLE ---
function handle_get_products_list($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);

    $baseQuery = "FROM cms_products p LEFT JOIN cms_products_group g ON p.prd_group_id = g.id LEFT JOIN cms_products_manufacture m ON p.prd_manufacture_id = m.id";
    $whereClauses = ["p.deleted = 0"];
    $params = [];
    $types = '';

    $whereClauses[] = "p.prd_status = ?";
    $params[] = 1;
    $types .= 'i';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(p.prd_name LIKE ? OR p.prd_code LIKE ?)";
        $searchTermWildcard = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTermWildcard, $searchTermWildcard);
        $types .= 'ss';
    }
    
    if (isset($_POST['prd_status']) && in_array($_POST['prd_status'], ['0', '1'])) { 
        $whereClauses = array_filter($whereClauses, function($clause) {
            return strpos($clause, 'p.prd_status =') === false;
        });
        $whereClauses[] = "p.prd_status = ?";
        $params = array_filter($params, function($param) {
            return $param !== 1;
        });
        $params[] = $_POST['prd_status'];
        $types = str_replace('i', '', $types) . 'i'; 
    }
    if (!empty($_POST['category_id'])) { 
        $whereClauses[] = "p.prd_group_id = ?"; 
        $params[] = $_POST['category_id']; 
        $types .= 'i'; 
    }
    if (!empty($_POST['manufacturer_id'])) { 
        $whereClauses[] = "p.prd_manufacture_id = ?"; 
        $params[] = $_POST['manufacturer_id']; 
        $types .= 'i'; 
    }

    $whereSql = " WHERE " . implode(" AND ", $whereClauses);

    $summaryQuery = "SELECT COUNT(p.ID) as total_products, 
                            COUNT(DISTINCT p.prd_manufacture_id) as total_manufacturers,
                            SUM(CASE WHEN p.prd_status = 1 THEN p.prd_sls * p.prd_origin_price ELSE 0 END) as total_inventory_value
                            $baseQuery $whereSql";
    $stmtSummary = $conn->prepare($summaryQuery);
    if (!empty($types)) { 
        $stmtSummary->bind_param($types, ...$params); 
    }
    $stmtSummary->execute();
    $summary_data = $stmtSummary->get_result()->fetch_assoc();
    $stmtSummary->close();

    $queryFiltered = "SELECT COUNT(p.ID) as total " . $baseQuery . $whereSql;
    $stmtFiltered = $conn->prepare($queryFiltered);
    if (!empty($types)) { 
        $stmtFiltered->bind_param($types, ...$params); 
    }
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_assoc()['total'];
    $stmtFiltered->close();

    $totalRecords = $conn->query("SELECT COUNT(ID) FROM cms_products WHERE deleted = 0")->fetch_row()[0] ?? 0;

    // QUAN TRỌNG: Đã xóa prd_image_url, prd_size, prd_color khỏi câu SELECT này
    $dataQuery = "SELECT p.ID as id, p.prd_name, p.prd_code, p.prd_status, p.prd_sls AS prd_inventory, p.prd_sell_price, p.prd_sell_price2, g.prd_group_name, m.prd_manuf_name " . $baseQuery . $whereSql . " ORDER BY p.ID DESC LIMIT ?, ?";
    $dataTypes = $types . 'ii';
    $dataParams = array_merge($params, [$start, $length]);
    $stmt = $conn->prepare($dataQuery);
    $stmt->bind_param($dataTypes, ...$dataParams);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

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

function handle_get_product_details($conn) {
    $product_id = intval($_GET['product_id'] ?? 0);
    $response = ['status' => 'error', 'message' => 'ID sản phẩm không hợp lệ.'];
    if ($product_id > 0) {
        $stmt = $conn->prepare("SELECT * FROM cms_products WHERE ID = ?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $data = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if ($data) {
            $response = ['status' => 'success', 'data' => $data];
        } else {
            $response['message'] = 'Không tìm thấy sản phẩm.';
        }
    }
    echo json_encode($response);
}

// --- ĐÃ SỬA: HÀM SỬA SẢN PHẨM KHÔNG CÓ SIZE/MÀU/ẢNH ---
function handle_edit_product($conn) {
    $prd_id = intval($_POST['prd_id'] ?? 0);
    $prd_name = trim($_POST['prd_name'] ?? '');
    
    if (empty($prd_id) || empty($prd_name)) {
        echo json_encode(['status' => 'error', 'message' => 'Dữ liệu không hợp lệ.']);
        return;
    }

    // Đã bỏ phần xử lý upload ảnh ở đây vì server cũ không dùng

    $prd_code = trim($_POST['prd_code'] ?? '');
    $prd_origin_price = floatval($_POST['prd_origin_price'] ?? 0);
    $prd_sell_price = floatval($_POST['prd_sell_price'] ?? 0);
    $prd_sell_price2 = floatval($_POST['prd_sell_price2'] ?? 0);
    $prd_group_id = intval($_POST['prd_group_id'] ?? 0);
    $prd_manufacture_id = intval($_POST['prd_manufacture_id'] ?? 0);
    $prd_unit_id = intval($_POST['prd_unit_id'] ?? 0);
    
    // SQL Update chuẩn cho server cũ (không có size, color, image)
    $sql = "UPDATE cms_products SET 
                prd_name = ?, prd_code = ?, prd_origin_price = ?, 
                prd_sell_price = ?, prd_sell_price2 = ?, prd_group_id = ?, 
                prd_manufacture_id = ?, prd_unit_id = ?, 
                updated = NOW() 
            WHERE ID = ?";
            
    $stmt = $conn->prepare($sql);
    
    // Bind param: ssdddiiii (9 tham số)
    $stmt->bind_param("ssdddiiii", 
        $prd_name, $prd_code, $prd_origin_price, $prd_sell_price, $prd_sell_price2, 
        $prd_group_id, $prd_manufacture_id, $prd_unit_id, 
        $prd_id
    );
    
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Cập nhật sản phẩm thành công!'];
    } else {
        $response = ['status' => 'error', 'message' => 'Lỗi khi cập nhật: ' . $stmt->error];
    }
    $stmt->close();
    echo json_encode($response);
}

function handle_delete_product($conn) {
    $product_id = intval($_POST['product_id'] ?? 0);
    if ($product_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID sản phẩm không hợp lệ.']);
        return;
    }
    $stmt = $conn->prepare("UPDATE cms_products SET deleted = 1, prd_status = 0 WHERE ID = ?");
    $stmt->bind_param("i", $product_id);
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Xóa sản phẩm thành công!'];
    } else {
        $response = ['status' => 'error', 'message' => 'Lỗi khi xóa sản phẩm.'];
    }
    $stmt->close();
    echo json_encode($response);
}
?>