<?php
ini_set('display_errors', 0);
require_once("../../common/lib.php");
require_once("../../common/define.php");

if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit();
}

$id_client = isset($_GET['id_client']) ? (int)$_GET['id_client'] : 0;
if ($id_client === 0) {
    echo json_encode([]);
    exit();
}

$bl_ids = [];

$query = "SELECT ref_bl FROM pm_facture";
$result = @$db->query($query);

if ($result !== false) {
    foreach ($result as $row) {
        $refs = explode(',', $row["ref_bl"]);
        foreach ($refs as $ref) {
            $ref = trim($ref);
            if (is_numeric($ref)) {
                $bl_ids[] = (int)$ref;
            }
        }
    }

    // Nettoyer doublons
    $bl_ids = array_unique($bl_ids);

    if (!empty($bl_ids)) {
        $ids_list = implode(',', $bl_ids);
        $query_bl = "SELECT id FROM pm_bl WHERE id IN ($ids_list) OR id_client <> $id_client";
		// echo $query_bl;
        $result_bl = @$db->query($query_bl);

        $outp = [];
        if ($result_bl !== false) {
            foreach ($result_bl as $row_bl) {
                $outp[] = $row_bl['id'];
            }
        }

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

echo json_encode([]);
?>
