<?php
// restaurantadmin/ajax/receipt.php
// Always output JSON — never a blank page

// Session must be started before any output
session_start();

// Output JSON even on fatal errors
header('Content-Type: application/json');

// DB — path relative to this file's location (ajax/ folder → ../config/db.php)
$db_file = __DIR__ . '/../config/db.php';
if (!file_exists($db_file)) {
    echo json_encode(['ok' => false, 'msg' => 'DB config not found at: ' . $db_file]);
    exit;
}
include_once($db_file);

if (!isset($conn) || !$conn) {
    echo json_encode(['ok' => false, 'msg' => 'Database connection failed']);
    exit;
}

// Auth check
$allowed = ['restaurant_admin', 'staff', 'waiter'];
$role    = $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || !in_array($role, $allowed)) {
    echo json_encode(['ok' => false, 'msg' => 'Unauthorized — please log in again']);
    exit;
}

// Read params
$order_id = (int)($_GET['order_id'] ?? 0);
$rid      = (int)($_GET['rid']      ?? 0);

if (!$order_id || !$rid) {
    echo json_encode(['ok' => false, 'msg' => 'Missing order_id or rid parameter']);
    exit;
}

// Fetch order — must belong to this restaurant
$os = $conn->prepare(
    "SELECT o.*, u.name AS customer_name, u2.name AS accepted_by
     FROM orders o
     LEFT JOIN users u  ON o.user_id     = u.id
     LEFT JOIN users u2 ON o.assigned_to = u2.id
     WHERE o.id = ? AND o.restaurant_id = ?
     LIMIT 1"
);
if (!$os) {
    echo json_encode(['ok' => false, 'msg' => 'DB prepare failed: ' . $conn->error]);
    exit;
}
$os->bind_param("ii", $order_id, $rid);
$os->execute();
$order = $os->get_result()->fetch_assoc();

if (!$order) {
    echo json_encode(['ok' => false, 'msg' => "Order #$order_id not found for restaurant #$rid"]);
    exit;
}

// Format date nicely for receipt
$order['created_at'] = date('M j, Y  g:i A', strtotime($order['created_at']));

// Fetch order items
$is = $conn->prepare("SELECT * FROM order_items WHERE order_id = ? ORDER BY id");
$is->bind_param("i", $order_id);
$is->execute();
$items = $is->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch restaurant details
$rs = $conn->prepare("SELECT name, address, phone FROM restaurants WHERE id = ? LIMIT 1");
$rs->bind_param("i", $rid);
$rs->execute();
$restaurant = $rs->get_result()->fetch_assoc();

echo json_encode([
    'ok'         => true,
    'order'      => $order,
    'items'      => $items,
    'restaurant' => $restaurant ?? ['name' => 'Restaurant', 'address' => '', 'phone' => ''],
]);
