<?php

namespace PortalPeople\virtualstock\models;

/**
 * Represents a VirtualStock supplier as returned by the REST API.
 * This is a plain value object — not an ActiveRecord or DynamicModel.
 */
class Supplier
{
    /** Supplier ID as assigned by VirtualStock. */
    public string $id = '';

    /** Human-readable supplier name. */
    public string $name = '';

    /** Supplier code / short identifier. */
    public string $code = '';

    /** Primary contact email address. */
    public ?string $email = null;

    /** Primary contact telephone number. */
    public ?string $phone = null;

    /** Whether the supplier account is currently active on the platform. */
    public bool $active = true;

    /** ISO 8601 creation timestamp. */
    public ?string $createdAt = null;

    /** ISO 8601 last-updated timestamp. */
    public ?string $updatedAt = null;

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

    // -------------------------------------------------------------------------

    public static function fromArray(array $data): self
    {
        $supplier = new self();
        $supplier->id        = (string) ($data['id']            ?? $data['supplier_id'] ?? '');
        $supplier->name      = (string) ($data['name']          ?? $data['supplier_name'] ?? '');
        $supplier->code      = (string) ($data['code']          ?? $data['supplier_code'] ?? '');
        $supplier->email     = isset($data['email'])            ? (string) $data['email']   : null;
        $supplier->phone     = isset($data['phone'])            ? (string) $data['phone']   : null;
        $supplier->active    = (bool)   ($data['active']        ?? $data['is_active'] ?? true);
        $supplier->createdAt = $data['created_at'] ?? $data['createdAt'] ?? null;
        $supplier->updatedAt = $data['updated_at'] ?? $data['updatedAt'] ?? null;
        $supplier->raw       = $data;

        return $supplier;
    }

    public function toArray(): array
    {
        return [
            'id'         => $this->id,
            'name'       => $this->name,
            'code'       => $this->code,
            'email'      => $this->email,
            'phone'      => $this->phone,
            'active'     => $this->active,
            'created_at' => $this->createdAt,
            'updated_at' => $this->updatedAt,
        ];
    }

    /**
     * Returns true if the supplier has enough data to be usable in order operations.
     */
    public function isIdentifiable(): bool
    {
        return $this->id !== '' && $this->name !== '';
    }
}
