<?php
/**
 * "Call Server" — a customer on the Order Status screen requests assistance.
 * Creates a service_call (shown live on the waiter dashboard) and a bell
 * notification, tagged with the table/office label + the customer's name so
 * the waiter knows exactly who's calling and from where.
 */
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Not signed in.']);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Invalid request.']);
    exit;
}

include_once("config/db.php");

$uid      = (int)$_SESSION['user_id'];
$order_id = (int)($_POST['order_id'] ?? 0);
if (!$order_id) { echo json_encode(['ok' => false, 'error' => 'Missing order.']); exit; }

// Order + source label + customer name
$stmt = $conn->prepare(
    "SELECT o.restaurant_id, o.table_number, u.name AS cname, rt.label AS loc_label
     FROM orders o
     LEFT JOIN users u ON u.id = o.user_id
     LEFT JOIN restaurant_tables rt ON rt.restaurant_id = o.restaurant_id AND rt.table_number = o.table_number
     WHERE o.id = ? AND o.user_id = ?"
);
$stmt->bind_param("ii", $order_id, $uid);
$stmt->execute();
$o = $stmt->get_result()->fetch_assoc();
if (!$o) { echo json_encode(['ok' => false, 'error' => 'Order not found.']); exit; }

$rid   = (int)$o['restaurant_id'];
$tn    = trim((string)$o['table_number']);
$label = trim((string)($o['loc_label'] ?? ''));
$cname = trim((string)($o['cname'] ?? 'A customer'));

$src = $tn !== '' ? (preg_match('/^[0-9]+$/', $tn) ? "Table $tn" : $tn) : ($label ?: 'Online order');
$where = $src . ($label && $tn !== '' ? " ($label)" : '');

// 1) Live service call for the waiter dashboard. Self-heal the table so the
// feature works even if the staff-module migration was never run.
$sh = __DIR__ . '/../staff/includes/schema_heal.php';
if (is_file($sh)) { include_once($sh); try { dabil_staff_schema_heal($conn); } catch (\Throwable $e) {} }
if ($sc = $conn->prepare(
    "INSERT INTO service_calls (restaurant_id, order_id, user_id, table_number, table_label, customer_name, status)
     VALUES (?, ?, ?, ?, ?, ?, 'open')"
)) {
    $sc->bind_param("iiisss", $rid, $order_id, $uid, $tn, $label, $cname);
    $sc->execute();
}

// 2) Bell notification (reuses the existing notifications table)
$order_label = '#' . str_pad($order_id, 4, '0', STR_PAD_LEFT);
$message = "$cname needs assistance — $where (order $order_label).";
$notif_sql = "INSERT INTO notifications (restaurant_id, type, title, message, related_id) VALUES (?, 'new_order', 'Customer Needs Assistance', ?, ?)";
if ($ins = $conn->prepare($notif_sql)) {
    $ins->bind_param("isi", $rid, $message, $order_id);
    $ins->execute();
}

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