<?php
/**
 * Consignment Queue Job – GForce Module
 *
 * @category    PortalPeople
 * @package     GForce
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\gforce\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;

/**
 * UpdateStatus
 *
 * Updates the status of a consignment in GForce asynchronously via the
 * Yii2 queue component.
 */
class UpdateStatus extends BaseObject implements JobInterface
{
    const background_run = true;
    

    /** @var string Tracking number to query. */
    public $trackingCode = '';

    /** @var string Cart ID to query. */
    public $cartId = '';

    /** @var bool If true, commit=true is used (stores as live consignment). */
    public $commit = true;

    /** @var string Unique transaction reference for logging. */
    public $uniqueRef = '';

    /**
     * Execute the job.
     *
     * @param \yii\queue\Queue $queue
     */
    public function execute($queue)
    {
         $consignments = \PortalPeople\gforce\models\Cart::findConsignmentsDays(1);
        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;
            }
        }
    }
}
