<?php
include 'db.php';

$order_id = intval($_GET['order_id'] ?? 0);
if(!$order_id) die("Invalid Order ID");

// Fetch order
$order = $conn->query("
    SELECT ro.*, u.username AS waiter_name, c.name AS customer_name
    FROM restaurant_orders ro
    LEFT JOIN users u ON ro.waiter_id = u.id
    LEFT JOIN customers c ON ro.customer_id = c.id
    WHERE ro.id=$order_id
")->fetch_assoc();

if(!$order) die("Order not found");

// Fetch items
$items = $conn->query("
    SELECT roi.*, rm.name AS menu_name
    FROM restaurant_order_items roi
    LEFT JOIN restaurant_menu rm ON roi.menu_id = rm.id
    WHERE roi.order_id=$order_id
");

$printer_ip = "192.168.1.131";  // 🔥 CHANGE THIS
$port = 9100;

$fp = fsockopen($printer_ip, $port, $errno, $errstr, 10);

if(!$fp){
    die("Printer Connection Failed: $errstr ($errno)");
}

$receipt  = "\x1B\x40"; // Initialize printer
$receipt .= "\x1B\x61\x01"; // Center align
$receipt .= "RAM'S EXECUTIVE LODGE\n";
$receipt .= "-----------------------------\n";

$receipt .= "\x1B\x61\x00"; // Left align
$receipt .= "Order #: ".$order['id']."\n";
$receipt .= "Waiter: ".$order['waiter_name']."\n";
$receipt .= "Customer: ".($order['customer_name'] ?? 'Walk-in')."\n";
$receipt .= "Date: ".$order['created_at']."\n";
$receipt .= "-----------------------------\n";

while($item = $items->fetch_assoc()){
    $line = $item['qty']." x ".$item['menu_name'];
    $total = number_format($item['price'] * $item['qty'], 2);
    $receipt .= str_pad($line, 20);
    $receipt .= str_pad($total, 10, " ", STR_PAD_LEFT)."\n";
}

$receipt .= "-----------------------------\n";
$receipt .= "Subtotal: ".number_format($order['subtotal'],2)."\n";
$receipt .= "Discount: ".number_format($order['discount'],2)."\n";
$receipt .= "TOTAL: ".number_format($order['grand_total'],2)."\n\n";

$receipt .= "Thank you!\n\n\n";
$receipt .= "\x1D\x56\x41\x10"; // Cut paper

fwrite($fp, $receipt);
fclose($fp);

echo "Printed Successfully!";
?>