<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'company_id' => $this->company_id,
            'branch_id' => $this->branch_id,
            'shift_id' => $this->shift_id,
            'user_id' => $this->user_id,
            'customer_id' => $this->customer_id,
            'order_number' => $this->order_number,
            'type' => $this->type,
            'status' => $this->status,
            'currency_code' => $this->currency_code,
            'exchange_rate' => $this->exchange_rate,
            'subtotal' => $this->subtotal,
            'discount_amount' => $this->discount_amount,
            'discount_type' => $this->discount_type,
            'promotion_id' => $this->promotion_id,
            'tax_amount' => $this->tax_amount,
            'total_amount' => $this->total_amount,
            'amount_paid' => $this->amount_paid,
            'change_amount' => $this->change_amount,
            'loyalty_points_earned' => $this->loyalty_points_earned,
            'loyalty_points_redeemed' => $this->loyalty_points_redeemed,
            'notes' => $this->notes,
            'device_id' => $this->device_id,
            'local_id' => $this->local_id,
            'items' => $this->items->map(fn ($item) => [
                'id' => $item->id,
                'product_id' => $item->product_id,
                'variant_id' => $item->variant_id,
                'batch_id' => $item->batch_id,
                'name' => $item->name,
                'sku' => $item->sku,
                'quantity' => $item->quantity,
                'unit_price' => $item->unit_price,
                'cost_price' => $item->cost_price,
                'discount_amount' => $item->discount_amount,
                'tax_rate' => $item->tax_rate,
                'tax_amount' => $item->tax_amount,
                'total_amount' => $item->total_amount,
                'is_returned' => $item->is_returned,
                'returned_quantity' => $item->returned_quantity,
            ]),
            'payments' => PaymentResource::collection($this->whenLoaded('payments')),
            'customer' => $this->whenLoaded('customer', fn () => $this->customer?->only(['id', 'name', 'phone'])),
        ];
    }
}
