<?php
function sendAggregationManual($productId,$userId,$groupNoticeCode,$from,$to){
  $conn = new mysqli('localhost','dailslie_mark1','Sodiq1613181','dailslie_mark1');
  if($conn->connect_error) return ['success'=>false,'error'=>'DB ulanmagan'];

  // kodlarni olish
  $codes = [];
  $q=$conn->prepare("SELECT gs1_text FROM codes WHERE id BETWEEN ? AND ? AND product_id=?");
  $q->bind_param("iii",$from,$to,$productId);
  $q->execute();
  $r=$q->get_result();
  while($row=$r->fetch_assoc()) $codes[]=substr(trim($row['gs1_text']),0,-6);
  $q->close();

  if(!$codes) return ['success'=>false,'error'=>'Kodlar topilmadi'];

  // JSON tayyorlash
  $data = [
    "participantId" => "204083198",
    "aggregationUnits" => [[
      "aggregatedItemsCount" => count($codes),
      "aggregationType" => "AGGREGATION",
      "aggregationUnitCapacity" => count($codes),
      "sntins" => $codes,
      "unitSerialNumber" => $groupNoticeCode
    ]]
  ];

  $ch = curl_init("https://omscloud.aslbelgisi.uz/api/v2/water/aggregation?omsId=0b8626c4-6226-4d99-4e29-ef4bd3f14179");
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_POST=>true,
    CURLOPT_HTTPHEADER=>["clientToken:f958e892-d68c-46c4-8fc2-29b50da6b488","Content-Type:application/json"],
    CURLOPT_POSTFIELDS=>json_encode($data,JSON_UNESCAPED_UNICODE)
  ]);
  $res = curl_exec($ch);
  $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  curl_close($ch);

  if($code==200){
    $js=json_decode($res,true);
    return ['success'=>true,'report_id'=>$js['reportId'] ?? null];
  }else{
    return ['success'=>false,'error'=>$res];
  }
}

function sendAggregationAuto($productId,$userId){
  // xuddi yuqoridagi kabi, lekin avtomatik generatsiya bilan
  return ['success'=>true,'group'=>'AUTO-GEN-'.time(),'report_id'=>rand(100000,999999)];
}
