<?php

namespace App\Exports\Ecommerce\Product\Order;

use App\Models\Ecommerce\Product\Order\OrderItem;
use App\Models\Ecommerce\Product\Order\Status\OrderStatus;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class ExportOrderReport implements FromQuery, ShouldAutoSize, WithHeadings, WithMapping
{
    use Exportable;

    /**
     * Get the start & end date to filter
     */
    public function __construct(
        public string $start_date,
        public string $end_date
    ) {}

    /**
     * @return \Illuminate\Support\Collection
     */
    public function query()
    {
        return OrderItem::join(
            table: 'orders',
            first: fn ($join) => $join->on('order_items.order_id', '=', 'orders.id')
                ->where('orders.status', '=', OrderStatus::COMPLETED)
                ->whereNull('deleted_at')
        )->whereRaw('(orders.created_at >= ? AND orders.created_at <= ?)', [
            $this->start_date.' 00:00:00',
            $this->end_date.' 23:59:59',
        ]);
    }

    /**
     * @var Order
     */
    public function map($order): array
    {
        $orderDeliveryTime = match ($order->shipping_method) {
            'express' => 'Ekspres',
            default => $order->time,
        };

        return [
            $order->order_id,
            $order->name,
            $orderDeliveryTime,
            $order->quantity,
            $order->unit_price_amount,
            $order->unit_price_amount * $order->quantity,
        ];
    }

    /**
     * Headings for stylesheet
     */
    public function headings(): array
    {
        return [
            'Sargyt ID',
            'Ady',
            'Sene',
            'Sany',
            'Satylan Bahasy',
            'Satylan umumy bahasy',
        ];
    }
}
