<?php
namespace App\Controller;
use App\Service\CourierPleaseService;

class TrackingController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        if ($this->components()->has('Authentication')) {
            $this->Authentication->allowUnauthenticated(['index']);
        }
    }

    public function track($trackingNumber)
    {
        $service = new CourierPleaseService();
        $result = $service->track($trackingNumber);
        $this->set([
            'result' => $result,
            '_serialize' => ['result']
        ]);
    }
    public function index()
    {
        $result = null;
        $localBooking = null;
        $trackingNumber = null;
        $rawInput = $this->request->getData('tracking_number') ?? $this->request->getQuery('tracking_number');
        $trackingNumber = $rawInput ? trim($rawInput) : null;
        if (!empty($trackingNumber)) {
            $shipmentsTable = $this->fetchTable('Shipments');
            $bookingsTable = $this->fetchTable('Bookings');

            $shipment = $shipmentsTable->find()
                ->where(['tracking_no' => $trackingNumber])
                ->first();

            if ($shipment && !empty($shipment->booking_id)) {
                $localBooking = $bookingsTable->find()
                    ->where(['id' => $shipment->booking_id])
                    ->first();
            } else {
                $localBooking = $bookingsTable->find()
                    ->where([
                        'OR' => [
                            'booking_reference' => $trackingNumber,
                            'tracking_number' => $trackingNumber
                        ]
                    ])
                    ->first();
            }
            $apiSearchNumber = $trackingNumber;
            if ($localBooking) {
                if (!empty($localBooking->tracking_number)) {
                    $apiSearchNumber = $localBooking->tracking_number;
                } else {
                    $apiSearchNumber = null;
                }
            }
            if (!empty($apiSearchNumber)) {
                $service = new \App\Service\CourierPleaseService();
                $result = $service->track($apiSearchNumber);
            } else {
                $result = ['success' => false];
            }

            if ($this->request->is('get')) {
                $this->request = $this->request->withData('tracking_number', $trackingNumber);
            }
        }
        $this->set(compact('result', 'localBooking', 'trackingNumber'));
    }
}
