<?php

namespace PortalPeople\virtualstock\models\db;

use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
 * ActiveRecord for the `virtualstock_orders` table.
 *
 * Stores a lightweight tracking record per VirtualStock order, updated on
 * every import run. Use this to query local status, last-sync timestamps,
 * and raw payloads without calling the VirtualStock API.
 *
 * @property int         $id
 * @property string      $order_no           VirtualStock order number (e.g. VS-12345678901234)
 * @property string|null $vs_order_id        VirtualStock internal order ID
 * @property string      $status             Current order status (ORDER, ORDER_ACK, DISPATCH, etc.)
 * @property string|null $last_sync_at       Datetime of last successful API sync
 * @property string|null $updated_at_source  Cursor value (updatedAt) from last API response
 * @property string|null $shipments_json     Serialised shipment data
 * @property string|null $raw_json           Full raw order JSON from last API response
 * @property int         $created_at
 * @property int         $updated_at
 */
class VirtualstockOrder extends ActiveRecord
{
    /** @inheritdoc */
    public static function tableName(): string
    {
        return '{{%virtualstock_orders}}';
    }

    /** @inheritdoc */
    public function behaviors(): array
    {
        return [
            TimestampBehavior::class,
        ];
    }

    /** @inheritdoc */
    public function rules(): array
    {
        return [
            [['order_no', 'status'], 'required'],
            [['order_no'], 'string', 'max' => 100],
            [['order_no'], 'unique'],
            [['vs_order_id'], 'string', 'max' => 100],
            [['status'], 'string', 'max' => 50],
            [['last_sync_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'],
            [['updated_at_source'], 'string', 'max' => 50],
            [['shipments_json', 'raw_json'], 'string'],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'id'                => 'ID',
            'order_no'          => 'Order No',
            'vs_order_id'       => 'VS Order ID',
            'status'            => 'Status',
            'last_sync_at'      => 'Last Sync At',
            'updated_at_source' => 'Updated At (Source)',
            'shipments_json'    => 'Shipments JSON',
            'raw_json'          => 'Raw JSON',
            'created_at'        => 'Created At',
            'updated_at'        => 'Updated At',
        ];
    }

    // -------------------------------------------------------------------------
    // Helpers
    // -------------------------------------------------------------------------

    /**
     * Find by VirtualStock order number.
     */
    public static function findByOrderNo(string $orderNo): ?self
    {
        return static::findOne(['order_no' => $orderNo]);
    }

    /**
     * Decode shipments_json into an array (empty array if null/invalid).
     */
    public function getShipments(): array
    {
        if ($this->shipments_json === null || $this->shipments_json === '') {
            return [];
        }
        return json_decode($this->shipments_json, true) ?: [];
    }

    /**
     * Decode raw_json into an array (empty array if null/invalid).
     */
    public function getRawData(): array
    {
        if ($this->raw_json === null || $this->raw_json === '') {
            return [];
        }
        return json_decode($this->raw_json, true) ?: [];
    }
}
