<?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'] ?? '';
$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];
$user_id = $_SESSION['user_id'] ?? 0;
$current_store_id = $_SESSION['store_id'] ?? 1;

// ACTION: TÌM SẢN PHẨM TRONG KHO HIỆN TẠI
if ($action == 'search_products_in_store') {
    $term = $_GET['term'] ?? '';
    $searchTerm = "%" . $term . "%";
    
    $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 ?) 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();
}

// ACTION: TẠO PHIẾU CHUYỂN KHO (Cập nhật logic báo lỗi)
if ($action == 'create_transfer') {
    $to_store_id = intval($_POST['to_store_id'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $products = json_decode($_POST['products'] ?? '[]', true);

    // === KIỂM TRA ĐẦU VÀO VÀ BÁO LỖI CỤ THỂ ===
    if (empty($products)) {
        $response['message'] = 'Vui lòng chọn ít nhất một sản phẩm để chuyển.';
        echo json_encode($response);
        exit();
    }
    if ($to_store_id == 0) {
        $response['message'] = 'Vui lòng chọn kho cần chuyển đến.';
        echo json_encode($response);
        exit();
    }
    if ($to_store_id == $current_store_id) {
        $response['message'] = 'Không thể chuyển hàng đến chính kho hiện tại.';
        echo json_encode($response);
        exit();
    }

    $conn->begin_transaction();
    try {
        $total_quantity = array_reduce($products, function($sum, $item) { return $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);
        
        $sql = "INSERT INTO cms_transfer (transfer_code, from_store, to_store, detail_transfer, total_quantity, notes, user_init, transfer_status) VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
        $stmt = $conn->prepare($sql);
        $products_json = json_encode($products);
        $stmt->bind_param('siisisi', $transfer_code, $current_store_id, $to_store_id, $products_json, $total_quantity, $notes, $user_id);
        
        if (!$stmt->execute()) { throw new Exception("Lỗi khi tạo phiếu chuyển: " . $stmt->error); }

        $conn->commit();
        $response = ['status' => 'success', 'message' => 'Tạo phiếu chuyển kho thành công!'];
    } catch (Exception $e) {
        $conn->rollback();
        $response['message'] = $e->getMessage();
    }
    
    echo json_encode($response);
    exit();
}


// ACTION: LẤY DANH SÁCH PHIẾU CHUYỂN KHO
if ($action == 'get_transfers') {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    $search = $_POST['search_term'] ?? '';

    $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($search)) { $whereClauses[] = "t.transfer_code LIKE ?"; $params[] = "%" . $search . "%"; $types .= 's'; }
    if (isset($_POST['status']) && $_POST['status'] !== '') { $whereClauses[] = "t.transfer_status = ?"; $params[] = $_POST['status']; $types .= 'i'; }
    if (!empty($_POST['start_date']) && !empty($_POST['end_date'])) {
        $whereClauses[] = "DATE(t.created) BETWEEN ? AND ?";
        $params[] = $_POST['start_date']; $params[] = $_POST['end_date'];
        $types .= 'ss';
    }

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

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

    $totalFilteredQuery = $conn->prepare("SELECT COUNT(t.id) " . $baseQuery . $whereSql);
    if (!empty($types)) { $totalFilteredQuery->bind_param($types, ...$params); }
    $totalFilteredQuery->execute();
    $totalFiltered = $totalFilteredQuery->get_result()->fetch_row()[0];
    $totalFilteredQuery->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]);
    $dataStmt->bind_param($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();
}

// ACTION: XÁC NHẬN NHẬN HÀNG
if ($action == 'confirm_transfer') {
    $transfer_id = intval($_POST['id'] ?? 0);
    if ($transfer_id <= 0) {
        $response['message'] = 'ID phiếu chuyển không hợp lệ.';
        echo json_encode($response);
        exit();
    }

    $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ý.");
        if ($transfer['to_store'] != $current_store_id) throw new Exception("Bạn không có quyền xác nhận cho kho này.");

        $products = json_decode($transfer['detail_transfer'], true);

        foreach ($products as $p) {
            $product_id = intval($p['id']);
            $quantity = intval($p['quantity']);

            $conn->query("UPDATE cms_inventory SET quantity = quantity - {$quantity} WHERE product_id = {$product_id} AND store_id = {$transfer['from_store']}");
            
            $sql_receive = "INSERT INTO cms_inventory (store_id, product_id, quantity) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)";
            $stmt_receive = $conn->prepare($sql_receive);
            $stmt_receive->bind_param('iii', $transfer['to_store'], $product_id, $quantity);
            $stmt_receive->execute();
            $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();
        $response = ['status' => 'success', 'message' => 'Xác nhận nhận hàng thành công!'];
    } catch (Exception $e) {
        $conn->rollback();
        $response['message'] = $e->getMessage();
    }
    
    echo json_encode($response);
    exit();
}

echo json_encode($response);
?>