<?php

namespace App\Http\Resources;

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

class OrderResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'order_number' => $this->order_number,
            'order_type' => $this->order_type,
            'order_type_label' => $this->order_type === 'BUY' ? 'خرید' : 'فروش',
            'status' => $this->status,
            'status_label' => $this->getStatusLabel(),
            'order_date' => $this->order_date,
            'money_amount' => $this->money_amount,
            'money_amount_formatted' => number_format($this->money_amount) . ' ریال',
            'notes' => $this->notes,
            'user' => new CustomerResource($this->whenLoaded('user')),
            'customer' => new CustomerResource($this->whenLoaded('user')), // Alias for frontend compatibility
            'user_id' => $this->user_id,
            'customer_id' => $this->user_id, // Alias for frontend compatibility
            'lines' => OrderLineResource::collection($this->whenLoaded('lines')),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'confirmed_at' => $this->confirmed_at?->toISOString(),
            'closed_at' => $this->closed_at?->toISOString(),
            'history' => $this->resource->getHistory(),
        ];
    }

    /**
     * Get localized status label.
     */
    protected function getStatusLabel(): string
    {
        return match ($this->status) {
            'DRAFT' => 'پیش‌نویس',
            'IN_PROGRESS' => 'در حال پردازش',
            'COMPLETED' => 'تکمیل شده',
            'CONFIRMED' => 'تایید شده',
            'CLOSED' => 'بسته شده',
            default => $this->status ?? 'نامشخص',
        };
    }
}
