<?php
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../print/escpos.php';

$commande_id = (int)$_POST['commande_id'];

$stmt = $conn->prepare("
 SELECT cl.*, p.nom
 FROM commande_lignes cl
 JOIN produits p ON p.id=cl.produit_id
 WHERE cl.commande_id=? AND cl.imprime=0
");
$stmt->execute([$commande_id]);
$lignes = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* groupement par service */
$parService = [];
foreach ($lignes as $l) {
    $parService[$l['service_id']][] = $l;
}

foreach ($parService as $service_id => $items) {
    $stmt = $conn->prepare("
      SELECT imprimante_ip, nom
      FROM services WHERE id=?
    ");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch(PDO::FETCH_ASSOC);

    imprimerTicketService(
        $service['imprimante_ip'],
        $service['nom'],
        $items
    );

    $ids = array_column($items, 'id');
    $conn->exec("
      UPDATE commande_lignes SET imprime=1
      WHERE id IN (".implode(',',$ids).")
    ");
}

echo json_encode(['printed'=>true]);
