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

$commande_id = (int)($_POST['commande_id'] ?? 0);
if ($commande_id <= 0) {
    echo json_encode(['success'=>false,'message'=>'Commande invalide']);
    exit;
}

/* =========================
   LIGNES NON IMPRIMÉES
========================= */
$stmt = $conn->prepare("
    SELECT
        cl.id,
        cl.quantite,
        p.nom AS produit,
        s.id  AS service_id,
        s.nom AS service,
        s.imprimante_ip
    FROM commande_lignes cl
    JOIN produits p ON p.id = cl.produit_id
    JOIN services s ON s.id = cl.service_id
    WHERE cl.commande_id = ?
      AND cl.imprime = 0
    ORDER BY s.id
");
$stmt->execute([$commande_id]);
$lignes = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$lignes) {
    echo json_encode(['success'=>true,'message'=>'Rien à imprimer']);
    exit;
}

/* =========================
   GROUPEMENT PAR SERVICE
========================= */
$parService = [];
foreach ($lignes as $l) {
    $parService[$l['service_id']]['service'] = $l['service'];
    $parService[$l['service_id']]['printer'] = $l['imprimante_ip'];
    $parService[$l['service_id']]['ids'][] = $l['id'];
}

/* =========================
   IMPRESSION JASPER
========================= */
foreach ($parService as $service_id => $data) {

    $cmd = sprintf(
        'jasperstarter print %s -t mysql -H %s -n %s -u %s -p %s '.
        '--param COMMANDE_ID=%d --param SERVICE_ID=%d '.
        '--printer-name "%s"',
        escapeshellarg(__DIR__.'/../../rapports/pos/ticket_service.jasper'),
        DB_HOST,
        DB_NAME,
        DB_USER,
        DB_PASS,
        $commande_id,
        $service_id,
        $data['printer']
    );

    exec($cmd, $out, $code);

    if ($code !== 0) {
        echo json_encode(['success'=>false,'message'=>"Erreur impression {$data['service']}"]);
        exit;
    }

    /* marquer imprimé */
    $conn->exec("
        UPDATE commande_lignes
        SET imprime = 1
        WHERE id IN (".implode(',', $data['ids']).")
    ");
}

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