<?php

namespace PortalPeople\cart\models;

use Yii;
use backend\models\Cartsbe as BaseCart;
use backend\models\Cartlines;
use backend\models\Products;
use backend\models\Accounts;

/**
 * Cart model extension providing API-based cart creation.
 *
 * Extends the base NGauge Cart model with `fromApi()` for EDI/API order ingestion.
 */
class Cart extends BaseCart
{
    /**
     * Create one or more carts from API/EDI payload data.
     *
     * Accepts either a single order array or an indexed array of order arrays.
     * Each order must contain at minimum: deliveryCustomerCode, orderNumber,
     * deliveryDate, lines (array of stockCode, qty, price, product).
     *
     * @param array|object $data Order data from API
     * @return array Result containing order, lines, edi_orderref, or errors
     */
    public static function fromApi($data): array
    {
        if (is_array($data) && count($data) > 0 && array_key_exists(0, $data)) {
            foreach ($data as $orderArray) {
                if (isset($orderArray['deliveryCustomerCode']) && strlen($orderArray['deliveryCustomerCode']) > 0 && $orderArray['deliveryCustomerCode'][0] === '0') {
                    $orderArray['deliveryCustomerCode'] = 'O' . substr($orderArray['deliveryCustomerCode'], 1);
                }

                $account = Accounts::find()->where(['account_code' => $orderArray['deliveryCustomerCode']])->one();

                if (!$account) {
                    Yii::$app->response->statusCode = 200;
                    return [
                        'errors' => 'Account with code ' . $orderArray['deliveryCustomerCode'] . ' not found',
                        'code' => 404,
                    ];
                }

                $model = new self();
                $model->id = ($id = self::Tempid());
                $model->type = 'ediOrder';
                $model->language = 'en';
                $model->status = 'New';
                $model->porderref = substr($orderArray['orderNumber'], 0, 10);
                $model->accountid = $account ? $account->id : null;
                $model->account_code = $orderArray['deliveryCustomerCode'];
                $model->companyname = $account?->name;
                $model->deliveryaddress = $account->addressl ? $account->addressl->id : null;
                $model->billingaddress = $account->addressl ? $account->addressl->id : null;

                foreach ($orderArray['lines'] as $lineArray) {
                    $cartline = new Cartlines();
                    $product = Products::find()->where(['stock_code' => $lineArray['stockCode']])->one();
                    $cartline->basketid = $id;
                    $cartline->productid = $product ? $product->id : null;
                    $cartline->stock_code = $lineArray['stockCode'];
                    $cartline->product_description = $product?->product_name ?? $lineArray['product'];
                    $cartline->qty = $lineArray['qty'];
                    $cartline->requested_date = date('Y-m-d', strtotime($orderArray['deliveryDate']));
                    $cartline->pricelocked = true;
                    $cartline->save();
                }

                $model->save();
                $model->Order();
            }
        } else {
            $orderArray = (array)$data;

            if (isset($orderArray['deliveryCustomerCode']) && strlen($orderArray['deliveryCustomerCode']) > 0 && $orderArray['deliveryCustomerCode'][0] === '0') {
                $orderArray['deliveryCustomerCode'] = 'O' . substr($orderArray['deliveryCustomerCode'], 1);
            }

            $account = Accounts::find()->where(['account_code' => $orderArray['deliveryCustomerCode']])->one();

            if (!$account) {
                Yii::$app->response->statusCode = 200;
                return [
                    'account' => $orderArray['deliveryCustomerCode'],
                    'edi_orderref' => $orderArray['orderNumber'],
                    'errors' => 'Account with code ' . $orderArray['deliveryCustomerCode'] . ' not found',
                    'code' => 422,
                ];
            }

            $model = new self();
            $model->extended->delivery_account_code = $orderArray['deliveryCustomerCode'];
            $model->extended->delivery_date = $orderArray['deliveryDate'];

            if (in_array('edi_orderref', array_keys((array)$model->extended->localAttributes()))) {
                $model->extended->edi_orderref = $orderArray['orderNumber'];
            }

            $model->id = ($id = self::Tempid());
            $model->type = 'ediOrder';
            $model->language = 'en';
            $model->status = 'New';
            $model->porderref = $orderArray['orderNumber'];
            $model->accountid = $account ? $account->id : null;
            $model->account_code = $orderArray['deliveryCustomerCode'];
            $model->companyname = $account?->name;
            $model->deliveryaddress = $account->addressl ? $account->addressl->id : null;
            $model->billingaddress = $account->addressl ? $account->addressl->id : null;
            $model->terms = true;
            $model->contact = $orderArray['contactName'];
            $model->email = $orderArray['contactEmail'];

            $baddress = $model->fulladdresses['billing'];
            $daddress = $model->fulladdresses['shipping'];
            $daddress->loadAddress($model->deliveryaddress);
            $baddress->loadAddress($model->billingaddress);

            foreach ($orderArray['lines'] as $lineArray) {
                $cartline = new Cartlines();
                $product = Products::find()->where(['stock_code' => $lineArray['stockCode']])->one();
                $cartline->basketid = $id;
                $cartline->productid = $product ? $product->id : null;
                $cartline->stock_code = $product ? $product->stock_code : 'ERR-' . $lineArray['stockCode'];
                $cartline->product_description = $product?->product_name ?? 'ERR-' . $lineArray['product'];
                $cartline->qty = $lineArray['qty'];
                $cartline->price = $lineArray['price'];
                $cartline->pricelocked = true;
                $cartline->dispatch = true;
                $cartline->requested_date = date('Y-m-d', strtotime(str_replace('/', '-', $orderArray['deliveryDate'])));
                $cartline->save();
            }

            $model->save();
            $model->Order();
        }

        return [
            'edi_orderref' => $model->extended->edi_orderref ?? null,
            'order' => $model,
            'lines' => $model->cartlines,
        ];
    }
}
