<?php

namespace App\Exports;

use App\Models\OrderTax;
use App\Models\DeliveryArea;
use App\Libraries\AppLibrary;
use App\Services\TodayOrderService;
use App\Http\Requests\PaginateRequest;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;

class TodayOrderExport implements FromCollection, WithHeadings
{

    public TodayOrderService $todayOrderService;
    public PaginateRequest $request;

    public function __construct(TodayOrderService $todayOrderService, $request)
    {
        $this->todayOrderService = $todayOrderService;
        $this->request      = $request;
    }

    public function collection(): \Illuminate\Support\Collection
    {
        $orderArray  = [];
        $ordersArray = $this->todayOrderService->list($this->request);


        foreach ($ordersArray as $order) {
            $orderItems = $order?->order->orderItems->where('item_category_id', $order->order_item_category_id);
            $itemIds = $orderItems->pluck('item_id');

            $itemsTotal = $orderItems->sum('total_price');
            $taxTotal = OrderTax::where('order_id', $order->order_id)->whereIn('item_id', $itemIds)->sum('tax_amount');
            $deliveryCharge = DeliveryArea::whereKey($order?->order->order_area_id)->value('delivery_charge');
            $orderArray[] = [
                $order->order->order_serial_no,
                optional($order->category)->name,
                optional($order->order->user)->name,
                AppLibrary::flatAmountFormat($itemsTotal + $taxTotal + $deliveryCharge),
                AppLibrary::date($order->date),
                trans('orderStatus.' . $order->status),
            ];
        }
        return collect($orderArray);
    }

    public function headings(): array
    {
        return [
            trans('all.label.order_serial_no'),
            trans('all.label.item_category_id'),
            trans('all.label.customer'),
            trans('all.label.amount'),
            trans('all.label.date'),
            trans('all.label.status'),
        ];
    }
}