<?php 

namespace PortalPeople\dx\services;

class NewConsignment extends \PortalPeople\dx\components\ConsignmentService
{
    public function create($cart, $lines)
    {
        $shippingAddress = $cart->shippingAddress ?? null;
        if ($shippingAddress) {
            $model = new \PortalPeople\dx\models\ConsignmentForm();
            $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 {
            $result = Yii::$app->dxClient->createConsignment($consignmentData);
            $decodedResult = $result;
            Yii::warning($decodedResult, 'DX Consignment Result'); // Log the response from DX for debugging
            $tracking = implode(', ', $decodedResult['trackingNumbers'] ?? []);
            $cart->data->dx->tracking_number = $tracking;
            $cart->data->dx->status = 'Consignment Created';
            $cart->data->dx->despatch_date = date('Y-m-d H:i:s');
            $trackingInfo = 'DX Tracking Number(s): ' . ($tracking ?? 'N/A');
            $cart->status = 'Processed';
            $cart->save();
            foreach($decodedResult['trackingNumbers'] as $tn) {
                if(!empty(trim($tn))){
                    $tn = trim($tn);
                    $results[] = Yii::$app->dxClient->printLabelPdf($tn);
                }
            }
            $cart->refresh();
            return $results;
        } catch (\Exception $e) {
            Yii::warning($e, 'DX');
            Yii::warning('DX error: ' . $e->getMessage(), 'DX');
        }    
    }
}