<?php

namespace PortalPeople\gforce\commands;

use Yii;
use yii\console\{Controller, ExitCode};
use yii\helpers\{Console, Json};
use common\components\Tracing;

class GforceController extends Controller
{
   
    public function actionRun(): int
    {
        $consignments = \PortalPeople\gforce\models\Cart::findTodaysConsignments();
        foreach ($consignments as $cart) {
           try {
                /** @var \PortalPeople\gforce\components\GForceClient $client */
                $client = Yii::$app->gforceClient;
                $result = $client->getConStatusByTrackingId($cart->data->gforce->tracking_number, $cart->id);
                //print_r($result['Payload'] ?? []);
                if (array_key_exists('Payload', $result) && array_key_exists('Statuses', $result['Payload'])) {
                    $statuses = $result['Payload']['Statuses'];
                    $arrivals = array_values(array_filter($statuses, function($s) {
                        $code = is_array($s) ? ($s['Code'] ?? '') : (is_object($s) ? ($s->Code ?? '') : '');
                        return $code === 'ARR';
                    }));
                    if (count($arrivals) > 0) {
                        $arrival = $arrivals[0];
                        $date = is_array($arrival) ? ($arrival['Captured'] ?? null) : (is_object($arrival) ? ($arrival->Captured ?? null) : null);
                        \PortalPeople\gforce\models\Cart::markDelivered($cart, $date);
                        return true;
                    }
                    $ofd = array_values(array_filter($statuses, function($s) {
                        $code = is_array($s) ? ($s['Code'] ?? '') : (is_object($s) ? ($s->Code ?? '') : '');
                        return $code === 'DSV';
                    }));
                    
                    if (count($ofd) > 0) {
                        $ofdItem = $ofd[0];
                        $date = is_array($ofdItem) ? ($ofdItem['Captured'] ?? null) : (is_object($ofdItem) ? ($ofdItem->Captured ?? null) : null);
                        \PortalPeople\gforce\models\Cart::markInProgress($cart, $date);
                        return true;
                    }
                
                } else {
                    Yii::warning(
                        "ConsignmentJob: no status codes found in response for cart {$cart->id}",
                        'gforce getStatus'
                    );
                }

            } catch (\Exception $e) {
                Yii::error(
                    "ConsignmentJob: exception for ref {$cart->data->gforce->tracking_number}: " . $e->getMessage(),
                    'gforce getStatus'
                );
                // Re-throw so the queue marks the job as failed and can retry
                throw $e;
            }
        }
        return ExitCode::OK;
    }

    public function actionStart() {
        Yii::$app->queue->push(new \PortalPeople\gforce\jobs\UpdateStatus());
    }
}
