<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method', [], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$type = $input['type'] ?? 'kitchen_ticket';
$orderId = (int) ($input['order_id'] ?? 0);

if (!$orderId) {
    jsonResponse(false, 'Invalid order ID');
}

$auth = new Auth();
if (!$auth->check()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$restaurantId = $auth->restaurantId();
if (!$restaurantId) {
    jsonResponse(false, 'No restaurant associated', [], 403);
}

$db = Database::getInstance();
$pdo = $db->getConnection();

$stmt = $pdo->prepare(
    "SELECT o.*, t.table_number, t.table_name
     FROM orders o
     LEFT JOIN tables t ON o.table_id = t.id
     WHERE o.id = ? AND o.restaurant_id = ? LIMIT 1"
);
$stmt->execute([$orderId, $restaurantId]);
$order = $stmt->fetch();

if (!$order) {
    jsonResponse(false, 'Order not found');
}

$itemStmt = $pdo->prepare(
    "SELECT id, item_name, variation_name, quantity, unit_price, variation_price,
            addons_total, item_total, item_notes
     FROM order_items WHERE order_id = ?"
);
$itemStmt->execute([$orderId]);
$order['items'] = $itemStmt->fetchAll();

foreach ($order['items'] as &$item) {
    $addonStmt = $pdo->prepare(
        "SELECT addon_name, addon_price FROM order_item_addons WHERE order_item_id = ?"
    );
    $addonStmt->execute([$item['id']]);
    $item['addons'] = $addonStmt->fetchAll();
}
unset($item);

$restStmt = $pdo->prepare("SELECT name, logo, phone, email, address, currency FROM restaurants WHERE id = ?");
$restStmt->execute([$restaurantId]);
$restaurant = $restStmt->fetch();

$currency = $restaurant['currency'] ?? 'USD';
$symbols = ['LKR' => 'Rs.', 'USD' => '$', 'EUR' => "\xE2\x82\xAC", 'GBP' => "\xC2\xA3", 'INR' => "\xE2\x82\xB9"];
$currencySymbol = $symbols[$currency] ?? $currency . ' ';

ob_start();

if ($type === 'invoice') {
    include BASE_PATH . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'invoice.php';
} else {
    include BASE_PATH . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'kitchen_ticket.php';
}

$html = ob_get_clean();

jsonResponse(true, 'Print data generated', [
    'html' => $html,
    'order_number' => $order['order_number'],
]);
