<?php
// customer/order_status.php
// AJAX endpoint polled by order_detail.php every 8 seconds
// Returns current order status + name of staff who accepted the order
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'unauthorized']); exit;
}

include_once("config/db.php");

$uid = (int)$_SESSION['user_id'];
$oid = (int)($_GET['id'] ?? 0);

if (!$oid) { echo json_encode(['error' => 'no id']); exit; }

$stmt = $conn->prepare(
    "SELECT o.order_status, o.assigned_to, o.updated_at,
            u.name AS accepted_by
     FROM orders o
     LEFT JOIN users u ON o.assigned_to = u.id
     WHERE o.id = ? AND o.user_id = ?
     LIMIT 1"
);
$stmt->bind_param("ii", $oid, $uid);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if (!$row) { echo json_encode(['error' => 'not found']); exit; }

echo json_encode([
    'order_status' => $row['order_status'],
    'accepted_by'  => $row['accepted_by'] ?? null,
    'updated_at'   => $row['updated_at'],
]);
