<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');
if (session_status() == PHP_SESSION_NONE) { session_start(); }

$action = $_REQUEST['action'] ?? '';
$user_id = $_SESSION['user_id'] ?? 0;
$current_store_id = $_SESSION['store_id'] ?? 1;

function json_response($status, $message, $data = []) {
    $response = ['status' => $status, 'message' => $message];
    if (!empty($data)) $response = array_merge($response, $data);
    echo json_encode($response);
    exit();
}

function bind_dynamic_params($stmt, $types, &$params) {
    if (empty($types) || empty($params)) return;
    $refs = [];
    foreach ($params as $key => $value) $refs[$key] = &$params[$key];
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types], $refs));
}

switch ($action) {
    case 'search_products_in_store': handle_search_products($conn, $current_store_id); break;
    case 'get_users_by_store': handle_get_users_by_store($conn); break;
    case 'create_transfer': handle_create_transfer($conn, $user_id, $current_store_id); break;
    case 'get_transfers': handle_get_transfers($conn); break;
    case 'confirm_transfer': handle_confirm_transfer($conn, $user_id, $current_store_id); break;
    default: json_response('error', 'Hành động không hợp lệ.');
}

function handle_search_products($conn, $current_store_id) {
    $term = $_GET['term'] ?? '';
    $searchTerm = "%" . $term . "%";
    
    // SỬA LỖI: Dùng bảng cms_inventory để lấy tồn kho chính xác
    $sql = "SELECT p.id, p.prd_code, p.prd_name, i.quantity as inventory
            FROM cms_products p
            JOIN cms_inventory i ON p.id = i.product_id
            WHERE i.store_id = ? AND i.quantity > 0 AND (p.prd_name LIKE ? OR p.prd_code LIKE ?) 
            AND p.deleted = 0 AND p.prd_status = 1
            LIMIT 20";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iss", $current_store_id, $searchTerm, $searchTerm);
    $stmt->execute();
    $products = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    echo json_encode($products);
    exit();
}

function handle_get_users_by_store($conn) {
    $store_id = intval($_GET['store_id'] ?? 0);
    $term = $_GET['term'] ?? '';
    $searchTerm = "%" . $term . "%";

    $sql = "SELECT id, display_name as text 
            FROM cms_users 
            WHERE store_id = ? AND user_status = 1 AND display_name LIKE ?
            ORDER BY display_name ASC LIMIT 10";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $store_id, $searchTerm);
    $stmt->execute();
    $users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    echo json_encode($users);
    exit();
}

function handle_create_transfer($conn, $user_id, $current_store_id) {
    $to_store_id = intval($_POST['to_store_id'] ?? 0);
    $receiver_id = intval($_POST['receiver_id'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $products = json_decode($_POST['products'] ?? '[]', true);

    if (empty($products)) json_response('error', 'Vui lòng chọn sản phẩm.');
    if ($to_store_id == 0) json_response('error', 'Vui lòng chọn kho nhận.');
    if ($receiver_id == 0) json_response('error', 'Vui lòng chọn người nhận.');
    if ($to_store_id == $current_store_id) json_response('error', 'Không thể chuyển đến chính kho hiện tại.');

    $conn->begin_transaction();
    try {
        $total_quantity = array_reduce($products, fn($sum, $item) => $sum + intval($item['quantity']), 0);
        
        $last_id_result = $conn->query("SELECT id FROM cms_transfer ORDER BY id DESC LIMIT 1");
        $last_id = $last_id_result ? $last_id_result->fetch_row()[0] : 0;
        $transfer_code = 'CK' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
        
        $products_json = json_encode($products);

        $sql = "INSERT INTO cms_transfer (transfer_code, from_store, to_store, detail_transfer, total_quantity, notes, user_init,user_upd, transfer_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('siisisii', $transfer_code, $current_store_id, $to_store_id, $products_json, $total_quantity, $notes, $user_id, $receiver_id);
        
        if (!$stmt->execute()) { throw new Exception("Lỗi khi tạo phiếu: " . $stmt->error); }
        $stmt->close();
        
        $conn->commit();
        json_response('success', 'Tạo phiếu chuyển kho thành công!');
    } catch (Exception $e) {
        $conn->rollback();
        json_response('error', $e->getMessage());
    }
}

function handle_get_transfers($conn) {
    // Giữ nguyên hàm này từ lần trước
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    
    $baseQuery = "FROM cms_transfer t 
                  LEFT JOIN cms_stores from_s ON t.from_store = from_s.id
                  LEFT JOIN cms_stores to_s ON t.to_store = to_s.id
                  LEFT JOIN cms_users creator ON t.user_init = creator.id
                  LEFT JOIN cms_users confirmer ON t.user_upd = confirmer.id";
    
    $whereClauses = ["t.deleted = 0"];
    $params = [];
    $types = '';

    if (!empty($_POST['search_term'])) { $whereClauses[] = "t.transfer_code LIKE ?"; $params[] = "%" . $_POST['search_term'] . "%"; $types .= 's'; }
    if (isset($_POST['status']) && $_POST['status'] !== '') { $whereClauses[] = "t.transfer_status = ?"; $params[] = $_POST['status']; $types .= 'i'; }
    if (!empty($_POST['start_date'])) { $whereClauses[] = "DATE(t.created) >= ?"; $params[] = $_POST['start_date']; $types .= 's'; }
    if (!empty($_POST['end_date'])) { $whereClauses[] = "DATE(t.created) <= ?"; $params[] = $_POST['end_date']; $types .= 's'; }

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

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

    $stmtFiltered = $conn->prepare("SELECT COUNT(t.id) {$baseQuery} {$whereSql}");
    bind_dynamic_params($stmtFiltered, $types, $params);
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_row()[0];
    $stmtFiltered->close();
    
    $dataQuery = "SELECT t.id, t.transfer_code, from_s.store_name as from_store_name, to_s.store_name as to_store_name, t.total_quantity, t.transfer_status, t.created as transfer_date, creator.display_name as creator_name, t.updated as received_date, confirmer.display_name as confirmer_name, t.to_store {$baseQuery} {$whereSql} ORDER BY t.id DESC LIMIT ?, ?";
    $dataStmt = $conn->prepare($dataQuery);
    $data_types = $types . 'ii';
    $data_params = array_merge($params, [$start, $length]);
    bind_dynamic_params($dataStmt, $data_types, $data_params);
    $dataStmt->execute();
    $data = $dataStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $dataStmt->close();

    $summaryQuery = $conn->query("SELECT transfer_status, COUNT(id) as count FROM cms_transfer WHERE deleted = 0 GROUP BY transfer_status");
    $summary = ['pending' => 0, 'completed' => 0];
    while($row = $summaryQuery->fetch_assoc()) {
        if ($row['transfer_status'] == 0) $summary['pending'] = $row['count'];
        if ($row['transfer_status'] == 1) $summary['completed'] = $row['count'];
    }

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

function handle_confirm_transfer($conn, $user_id, $current_store_id) {
    // Giữ nguyên hàm này từ lần trước
     $transfer_id = intval($_POST['id'] ?? 0);
    if ($transfer_id <= 0) json_response('error', 'ID phiếu chuyển không hợp lệ.');

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("SELECT * FROM cms_transfer WHERE id = ? AND transfer_status = 0");
        $stmt->bind_param('i', $transfer_id);
        $stmt->execute();
        $transfer = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$transfer) throw new Exception("Phiếu chuyển không tồn tại hoặc đã được xử lý.");
        
        $products = json_decode($transfer['detail_transfer'], true);

        // Trừ kho xuất
        $stmt_deduct = $conn->prepare("UPDATE cms_inventory SET quantity = quantity - ? WHERE product_id = ? AND store_id = ?");
        // Cộng kho nhận
        $stmt_receive = $conn->prepare("INSERT INTO cms_inventory (store_id, product_id, quantity) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)");

        foreach ($products as $p) {
            $quantity = intval($p['quantity']);
            $product_id = intval($p['id']);
            
            $stmt_deduct->bind_param('iii', $quantity, $product_id, $transfer['from_store']);
            $stmt_deduct->execute();
            
            $stmt_receive->bind_param('iii', $transfer['to_store'], $product_id, $quantity);
            $stmt_receive->execute();
        }
        $stmt_deduct->close();
        $stmt_receive->close();

        $stmt_update = $conn->prepare("UPDATE cms_transfer SET transfer_status = 1, user_upd = ?, updated = NOW() WHERE id = ?");
        $stmt_update->bind_param('ii', $user_id, $transfer_id);
        $stmt_update->execute();
        $stmt_update->close();

        $conn->commit();
        json_response('success', 'Xác nhận nhận hàng thành công!');
    } catch (Exception $e) {
        $conn->rollback();
        json_response('error', $e->getMessage());
    }
}
?>