<?php
require_once __DIR__ . '/../../config/db.php';
session_start();

$table_id = (int)$_POST['table_id'];
$user_id  = $_SESSION['user']['id'];

/* chercher commande ouverte */
$stmt = $conn->prepare("
  SELECT * FROM commandes
  WHERE table_id=? AND statut='ouverte'
  LIMIT 1
");
$stmt->execute([$table_id]);
$cmd = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$cmd) {
    $stmt = $conn->prepare("
      INSERT INTO commandes (table_id, utilisateur_id)
      VALUES (?,?)
    ");
    $stmt->execute([$table_id, $user_id]);
    $commande_id = $conn->lastInsertId();

    $conn->prepare("
      UPDATE tables_restaurant SET statut='Occupée'
      WHERE id=?
    ")->execute([$table_id]);
} else {
    $commande_id = $cmd['id'];
}

echo json_encode(['commande_id'=>$commande_id]);
