<?php

namespace PortalPeople\virtualstock\models;

/**
 * Represents a single line item within a VirtualStock order.
 */
class OrderItem
{
    public string $lineRef = '';
    public string $partNumber = '';
    public string $description = '';
    public int $quantity = 0;
    public float $unitPrice = 0.0;
    public float $totalPrice = 0.0;
    public string $subStatus = '';
    public ?string $supplierDispatchDate = null;
    public ?string $supplierDeliveryDate = null;

    /** Raw API payload for any fields not explicitly mapped */
    public array $raw = [];

    public static function fromArray(array $data): self
    {
        $item = new self();
        $item->lineRef               = (string) ($data['line_ref'] ?? $data['lineRef'] ?? '');
        $item->partNumber            = (string) ($data['part_number'] ?? $data['partNumber'] ?? '');
        $item->description           = (string) ($data['description'] ?? '');
        $item->quantity              = (int) ($data['quantity'] ?? 0);
        $item->unitPrice             = (float) ($data['unit_price'] ?? $data['unitPrice'] ?? 0.0);
        $item->totalPrice            = (float) ($data['total_price'] ?? $data['totalPrice'] ?? ($item->unitPrice * $item->quantity));
        $item->subStatus             = (string) ($data['sub_status'] ?? $data['subStatus'] ?? '');
        $item->supplierDispatchDate  = $data['supplier_dispatch_date'] ?? $data['supplierDispatchDate'] ?? null;
        $item->supplierDeliveryDate  = $data['supplier_delivery_date'] ?? $data['supplierDeliveryDate'] ?? null;
        $item->raw                   = $data;

        return $item;
    }

    public function toArray(): array
    {
        return [
            'line_ref'               => $this->lineRef,
            'part_number'            => $this->partNumber,
            'description'            => $this->description,
            'quantity'               => $this->quantity,
            'unit_price'             => $this->unitPrice,
            'total_price'            => $this->totalPrice,
            'sub_status'             => $this->subStatus,
            'supplier_dispatch_date' => $this->supplierDispatchDate,
            'supplier_delivery_date' => $this->supplierDeliveryDate,
        ];
    }

    /**
     * Build the acknowledge payload array for this line item.
     * $subStatus should be 'Pending' or 'Booked' (Screwfix requires 'Booked').
     */
    public function toAcknowledgePayload(string $subStatus, string $dispatchDate, string $deliveryDate): array
    {
        return [
            'part_number'            => $this->partNumber,
            'line_ref'               => $this->lineRef,
            'quantity'               => $this->quantity,
            'sub_status'             => $subStatus,
            'supplier_dispatch_date' => $dispatchDate,
            'supplier_delivery_date' => $deliveryDate,
        ];
    }
}
