<?php

namespace PortalPeople\palletline\services;
use yii;
use backend\models\ActionLog;
class NewConsignment extends \PortalPeople\palletline\components\ConsignmentService
{
    public function create($cart, $lines)
    {
        /** @var \PortalPeople\palletline\Module $module */
        $module = Yii::$app->getModule('palletline');
        $model = new \PortalPeople\palletline\models\ConsignmentForm();
        /** @var \PortalPeople\palletline\components\ConsignmentService $consignmentService */
        $consignmentService = Yii::createObject(\PortalPeople\palletline\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', 'Palletline error: ' . $description);
            }
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', 'Palletline error: ' . $e->getMessage());
        }
        // Direct send (default)
        try {
            $this->logAction($cart, 'Info', 'Palletline consignment creation attempt');
            $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->palletlineClient;
                    $consignmentResults = $consignmentService->persistCartConsignmentResult($cart, $responseId);
                    $pdf      = $client->getLabelsById($responseId);
                    $filepath = \PortalPeople\delivery\components\DeliveryService::storeConsignmentPdf($cart, $pdf, 'palletline');
                    $this->logAction($cart, 'Info', "Palletline consignment created (Response ID: {$responseId}); label saved to {$filepath}");
                    return [
                        [
                            'trackingInfo' => 'Palletline Consignment ID: ' . $responseId,
                            'filepath' => $filepath,
                            'data' => base64_encode($pdf),
                        ]
                    ];
                    // Yii::warning($pdf, 'Palletline 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);
            }

            $this->logAction($cart, 'error', 'Palletline consignment creation failed: ' . $description);
            Yii::$app->session->setFlash('error', 'Palletline error: ' . $description);
        } catch (\Exception $e) {
            $this->logAction($cart, 'error', 'Palletline consignment creation failed: ' . $e->getMessage());
            Yii::$app->session->setFlash('error', 'Palletline error: ' . $e->getMessage());
        }
    }

    private function logAction($cart, string $type, string $message): void
    {
        if (!is_object($cart) || empty($cart->id)) {
            Yii::warning($message, 'palletline');
            return;
        }

        ActionLog::create([
            'class' => self::class,
            'action' => 'create',
            'relatedid' => $cart->id,
            'type' => $type,
            'message' => $message . (!empty($cart->orderref) ? " for cart #{$cart->orderref}" : ''),
        ]);
    }
}