<?php

namespace PortalPeople\netsuite\models;

use Yii;

class Carts extends \backend\models\Cartsbe
{

    public static function printLabels(array $data)
    {
        try {
            if ($data['eventType'] !== 'PICKORDER') {
                return false;
            }
            $id = substr($data['snapshot']['body']['externalid']['value'], 0, 36) ?? null;
            $id !== null ? $cart = self::findOne(['id' => $id]) : $cart = false;
            if ($cart == false) {
                Yii::$app->response->statusCode = 400;
                return [
                    'status' => 'error',
                    'message' => 'Incorrect Cart ID',
                ];
            }
            $results = [];
            if ($id !== null && $cart) {
                $deliveryLines = $cart->deliveryCartlines;
                $hauliers = array_unique(array_column($deliveryLines, 'haulierint'));
                $shippingAddress = $cart->fulladdresses['shipping'] ?? null;
                $trackingInfo = 'No tracking information available.';
                $trackingNo = '';
                $results = [];
                foreach ($hauliers as $haulier) {
                    $account = \backend\models\Accounts::find()
                        ->where(['intid' => $haulier])
                        ->one();
                    $lines = \backend\models\Cartlines::find()
                        ->where(['basketid' => $cart->id, 'haulierint' => $haulier])
                        ->andWhere(['not', ['product_name' => 'Delivery']])
                        ->andWhere(['status' => 'active'])
                        ->all();

                    if ($account && $lines) {
                        Yii::$app->trigger("netsuite.createlabels-{$account->account_code}", $result = new \common\events\UserDataEvent(['model' => $cart]));
                        return $result->result ?? null;
                    }
                    return  [
                        'status' => 100,
                        'message' => 'No Account or Lines Found',
                        'trackinginfo' => '',
                        'body' => '',
                    ];
                }
            }
        } catch (\Throwable $e) {
            \backend\models\ActionLog::create([
                'class' => self::class,
                'action' => 'printLabels',
                'relatedid' => $cart->id ?? null,
                'type' => 'Error',
                'message' => $e->getMessage(),
            ]);
            Yii::error($e, 'DX');
            Yii::error('Label error: ' . $e->getMessage(), 'DX');
        }
    }
}
