<?php

namespace Modules\Printer\Templates;

use Illuminate\Support\Str;
use Modules\Printer\Contracts\BufferTemplateInterface;

class KitchenBufferTemplate implements BufferTemplateInterface
{
    /** @inheritDoc */
    public static function build(array $order): string
    {
        $totalItems = count($order['items']);
        $totalQuantity = 0;
        $buf = "==============================\n";
        $buf .= "     KITCHEN ORDER TICKET     \n";
        $buf .= "==============================\n";
        $buf .= "ORDER  : #{$order['order_number']}\n";
        $buf .= "TYPE   : {$order['type']->trans()}\n";
        $buf .= "MODE   : " . ($order['is_modified'] ? 'EDITED' : 'NEW') . "\n";
        if ($order['table']) {
            $buf .= "TABLE  : {$order['table']['floor']} • {$order['table']['zone']} • {$order['table']['table']}\n";
        }
        $buf .= "DATE   : {$order['date']} {$order['time']}\n";
        $buf .= str_repeat('-', 32) . "\n";

        foreach ($order['items'] as $item) {
            $buf .= "[" . strtoupper($item['status']->value) . "] " . Str::upper($item['name']) . "\n";
            $buf .= "QTY: {$item['quantity']}\n";
            $totalQuantity += $item['quantity'];

            foreach ($item['options'] ?? [] as $option) {
                $name = $option['name'] ?? '-';
                $value = $option['value'] ?? '';

                $label = is_array($value)
                    ? implode(', ', array_map(fn($v) => $v['label'], $value))
                    : $value;

                $buf .= "  • {$name}: {$label}\n";
            }

            $buf .= str_repeat('-', 32) . "\n";
        }

        $buf .= "TOTAL ITEMS   : {$totalItems}\n";
        $buf .= "TOTAL QUANTITY: {$totalQuantity}\n";
        $buf .= "==============================\n";

        return $buf;
    }
}
