<?php 
namespace PortalPeople\netsuite\models;

use PortalPeople\dx\models\ConsignmentForm;
use PortalPeople\dx\jobs\ConsignmentJob;
use Yii;

class Carts extends \backend\models\Cartsbe
{
    public static function printLabels($data)
    {
        try {
            if ($data['eventType'] !== 'PICKORDER') {
                return false;
            }
            $id = substr($data['snapshot']['body']['externalid']['value'], 0, 36) ?? null;
            $model = new ConsignmentForm();
            $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) {
                        if ($account->name === 'DX Network Services Ltd') {
                            /** @var \backend\models\Address $shippingAddress */
                            if ($shippingAddress) {
                                $country = strtoupper((string) ($shippingAddress->country ?? ''));
                                $countryCode = strlen($country) === 2 ? $country : ($country === 'UNITED KINGDOM' ? 'GB' : 'GB');
                                $model->recipient = (string) ($cart->contact ?? $shippingAddress->firstname . ' '. $shippingAddress->lastname  ?? '');
                                $model->company = (string) ($shippingAddress->company_name ?? $shippingAddress->companyname ?? '');
                                $model->address1 = (string) ($shippingAddress->address1 ?? '');
                                $model->address2 = (string) ($shippingAddress->address2 ?? '');
                                $model->address3 = (string) ($shippingAddress->address3 ?? '');
                                $model->town = (string) ($shippingAddress->town ?? '');
                                $model->county = (string) ($shippingAddress->county ?? '');
                                $model->postcode = (string) ($shippingAddress->postcode ?? '');
                                $model->countryCode = $countryCode;
                                $model->phone = (string) ($shippingAddress->telephone ?? '');
                                $model->email = (string) ($shippingAddress->email ?? $cart->email ?? '');
                                $model->itemDescriptions = array_column($lines, 'product_description');
                            }
                            $items = [];
                            foreach ($lines as $line) {
                                $i = 1;
                                while($i <= $line->erpqty) {
                                    $items[] = [
                                        'weight' => (float) ($line->weight / $line->erpqty) / 1000, // Convert grams to kg
                                        'quantity' => (int) '1',
                                        'packageTypeCode' => 'Bx',
                                        ];
                                        $i++;
                                }
                            }

                            $model->specialInstructions = (string) implode(', ', array_column($lines, 'product_description'));
                            $model->items = $items;
                            $model->reference = (string) $cart->porderref;
                            $model->despatchDate = date('Y-m-d');

                            /** @var \PortalPeople\dx\Module $module */
                            $module = Yii::$app->getModule('dx');
                            $accountCode = $module ? $module->accountCode : '';
                            // Build service code dropdown from API response if available
                            $services = Yii::$app->dxClient->getServices($model->postcode) ?? [];
                            $serviceOptions = [];
                            if (!empty($services)) {
                                foreach ($services as $svc) {
                                    $code = $svc['serviceCode'] ?? ($svc['code'] ?? '');
                                    $name = $svc['serviceName'] ?? ($svc['name'] ?? $code);
                                    if ($code) {
                                        $serviceOptions[$code] = "{$code} – {$name}";
                                    }
                                }
                            }       
                            if (in_array('NS', $serviceOptions, true)) {
                                $model->servicecode = 'NS';
                            }       
                            $consignmentData = $model->getConsignmentData($accountCode);
                            Yii::warning($consignmentData, 'DX Consignment Data'); // Log the data being sent to DX for debugging
                            // Direct send (default when queue unavailable or send is selected)
                            try {
                                $client = Yii::$app->dxClient;
                                $result = $client->createConsignment($consignmentData);
                                $decodedResult = $result;
                                Yii::warning($decodedResult, 'DX Consignment Result'); // Log the response from DX for debugging
                                $tracking = implode(', ', $decodedResult['trackingNumbers'] ?? []);
                                
                                /** @var \PortalPeople\dx\models\products\Dx $dx */
                                $dx = $cart->data->dx;
                                $dx->tracking_number = $tracking;
                                $dx->status = 'Consignment Created';
                                $dx->despatch_date = date('Y-m-d H:i:s');
                                $cart->data->dx = $dx;
                                $trackingInfo = 'DX Tracking Number(s): ' . ($tracking ?? 'N/A');
                                $cart->status = 'Processed';
                                $cart->save();
                                $results = $client->printLabelPdf($result['trackingNumbers'][array_key_first($result['trackingNumbers'])] ?? $result['trackingNumbers']);
                                $cart->refresh();
                                return $results;
                            } catch (\Exception $e) {
                                Yii::warning($e, 'Label');
                                Yii::warning('Label error: ' . $e->getMessage(), 'Label');
                            }
                        
                        } elseif ($account->name == 'Palletforce Logistics Sussex Limited') {

                            $module = Yii::$app->getModule('palletways');
                            $model = new \PortalPeople\palletways\models\ConsignmentForm();
                            /** @var \PortalPeople\palletways\components\ConsignmentService $consignmentService */
                            $consignmentService = Yii::createObject(\PortalPeople\palletways\components\ConsignmentService::class);

                            if ($cart !== null) {
                                $consignmentService->prepopulateModelFromCart($model, $module, $cart);
                            }
                            /** @var \PortalPeople\palletways\Module $module */
                            $confirm      = $module ? $module->autoConfirm : false;
                            $uniqueRef    = $consignmentService->buildUniqueRef();
                            $manifest     = $model->getManifest($confirm);
                            try {
                                $preflight = $consignmentService->validateRouteAndPreflight($model, $module, $manifest);
                                if (!$preflight['ok']) {
                                    // Direct send (default)
                                    $result = $consignmentService->createConsignment($manifest);
                                    $statusCode = $consignmentService->getStatusCode($result);

                                    if ($statusCode === 'OK') {
                                        $responseId = $result['Detail']['ImportDetail'][0]['ResponseID'] ?? '';
                                        $info       = $result['Detail']['ImportDetail'][0]['Information'] ?? '';

                                        if ($cart !== null) {
                                            $consignmentService->persistCartConsignmentResult($cart, $responseId);
                                        }
                                    }
                                    $description = $consignmentService->getStatusDescription($result, 'unknown error');
                                    if (!empty($result['ValidationErrors'])) {
                                        $description .= ' Validation: ' . json_encode($result['ValidationErrors'], JSON_UNESCAPED_SLASHES);
                                    }
                                    Yii::$app->session->setFlash('error', 'Palletways error: ' . $description);
                                }
                            } catch (\Exception $e) {
                                Yii::$app->session->setFlash('error', 'Palletways error: ' . $e->getMessage());
                            }
                            // Direct send (default)
                            try {
                                $result = $consignmentService->createConsignment($manifest);
                                $statusCode = $consignmentService->getStatusCode($result);

                                if ($statusCode === 'OK') {
                                    $responseId = $result['Detail']['ImportDetail'][0]['ResponseID'] ?? '';
                                    $info       = $result['Detail']['ImportDetail'][0]['Information'] ?? '';

                                    if ($cart !== null) {
                                        $client = Yii::$app->palletwaysClient;
                                        $consignmentResults = $consignmentService->persistCartConsignmentResult($cart, $responseId);
                                        $pdf      = $client->getLabelsById($responseId);
                                        return [
                                            [
                                                'trackingInfo' => 'Palletways Consignment ID: ' . $responseId,
                                                'data' => base64_encode($pdf),
                                            ]
                                        ];
                                        // Yii::warning($pdf, 'Palletways Consignment PDF');
                                    }
                                    Yii::$app->session->setFlash('success', 'Consignment created (Ref: ' . $uniqueRef . '). Response ID: ' . $responseId . ($info ? ' | ' . $info : ''));
                                }
                                $description = $consignmentService->getStatusDescription($result, 'unknown error');

                                if (!empty($result['ValidationErrors'])) {
                                    $description .= ' Validation: ' . json_encode($result['ValidationErrors'], JSON_UNESCAPED_SLASHES);
                                }

                                Yii::$app->session->setFlash('error', 'Palletways error: ' . $description);
                            } catch (\Exception $e) {
                                Yii::$app->session->setFlash('error', 'Palletways error: ' . $e->getMessage());
                            }
                        } elseif ($account->name == 'Palletforce Logistics Sussex Limited1') {
                            // Handle palletforce integration here if needed, similar to the Palletways block above but using Palletforce's API and data requirements.
                            
                        } elseif ($account->name == 'UPN') {
                            // Handle UPN integration here if needed, similar to the DX block above but using UPN's API and data requirements.
                        }
                        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) {
            Yii::error($e, 'DX');
            Yii::error('DX error: ' . $e->getMessage(), 'DX');
        }
    }
    
}