<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class SalesReportExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    public function __construct(private readonly Collection $orders)
    {
    }

    public function collection(): Collection
    {
        return $this->orders;
    }

    public function headings(): array
    {
        return [
            'Order No',
            'Tanggal',
            'Type',
            'Meja / Pelanggan',
            'Waiter',
            'Kasir',
            'Status',
            'Grand Total',
        ];
    }

    public function map($order): array
    {
        $typeLabel = $order->type === 'dine_in' ? 'Dine In' : 'Take Away';
        $mejaOrCustomer = $order->type === 'dine_in'
            ? ('Meja ' . ($order->meja?->no_meja ?? '-'))
            : ($order->nama_pelanggan ?? '-');

        return [
            $order->order_no,
            $order->tanggal?->format('d-m-Y H:i'),
            $typeLabel,
            $mejaOrCustomer,
            $order->waiter?->nama ?? '-',
            $order->creator?->name ?? $order->creator?->username ?? '-',
            ucfirst($order->status),
            (float) ($order->grand_total_after_discount ?? $order->grand_total),
        ];
    }
}
