<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Courier_Driver_Courrier_Centre extends AIEO_Courier_Driver_Base {

    
    const ENDPOINT_DEFAULT = 'https://funship.cc.qualco.eu/ccservice/api';

    public function code()  { return 'courrier_centre'; }
    public function label() { return 'Courier Center'; }

    public function capabilities() {
        
        
        return array('create', 'print', 'cancel', 'track', 'shop_list', 'manifest');
    }

    public function settings_schema() {
        return array(
            'user_alias'       => array('type' => 'text',     'label' => __('User alias',       'ai-eshop-optimizer'), 'required' => true,
                                        'help'  => __('Context.UserAlias — supplied by Courier Center.', 'ai-eshop-optimizer')),
            'credential_value' => array('type' => 'password', 'label' => __('Credential value', 'ai-eshop-optimizer'), 'required' => true,
                                        'help'  => __('Context.CredentialValue.', 'ai-eshop-optimizer')),
            'api_key'          => array('type' => 'password', 'label' => __('API key',          'ai-eshop-optimizer'), 'required' => true,
                                        'help'  => __('Context.ApiKey.', 'ai-eshop-optimizer')),
            'billing_account'  => array('type' => 'text',     'label' => __('Carrier billing account', 'ai-eshop-optimizer'), 'required' => true,
                                        'help'  => __('e.g. 100-0120-0004 — used as the Requestor + Shipper CarrierBillingAccount.', 'ai-eshop-optimizer')),
            'base_url'         => array('type' => 'text',     'label' => __('API base URL', 'ai-eshop-optimizer'),
                                        'help'  => __('Your production base URL (Courier Center send it by email). Leave empty to use the funship test endpoint.', 'ai-eshop-optimizer')),
            'basic_service'    => array('type' => 'text',     'label' => __('Basic service code', 'ai-eshop-optimizer'),
                                        'help'  => __('Optional BasicService code (supplied by Courier Center, e.g. door-to-door). Leave empty to use the account default.', 'ai-eshop-optimizer')),
            'bill_to'          => array('type' => 'select',   'label' => __('Bill to', 'ai-eshop-optimizer'),
                                        'options' => array('Requestor' => __('Requestor (sender)', 'ai-eshop-optimizer'),
                                                           'Consignee' => __('Consignee (recipient)', 'ai-eshop-optimizer'))),
            'default_template' => array('type' => 'select',   'label' => __('Voucher template', 'ai-eshop-optimizer'),
                                        'options' => array(
                                            'singlepdf'         => __('Single 205×100 mm', 'ai-eshop-optimizer'),
                                            'singleclean'       => __('Single 205×100 mm (preprinted)', 'ai-eshop-optimizer'),
                                            'singlepdf_100x150' => __('Single 100×150 mm (thermal)', 'ai-eshop-optimizer'),
                                            'singlepdf_100x170' => __('Single 100×170 mm (thermal)', 'ai-eshop-optimizer'),
                                            'pdf'               => __('A4 — 3 vouchers/sheet', 'ai-eshop-optimizer'),
                                            'clean'             => __('A4 — 3 vouchers/sheet (preprinted)', 'ai-eshop-optimizer'),
                                            'pdfvertical'       => __('A4 — 4 vouchers/sheet', 'ai-eshop-optimizer'),
                                        )),
            'data_culture'     => array('type' => 'text',     'label' => __('Data culture', 'ai-eshop-optimizer'),
                                        'help'  => __('Optional locale for API messages, e.g. el-GR.', 'ai-eshop-optimizer')),
            'tracking_url_template' => array('type' => 'text', 'label' => __('Tracking URL template', 'ai-eshop-optimizer'),
                                        'help'  => __('Public tracking page with {voucher_no} placeholder (used in emails + my-account).', 'ai-eshop-optimizer')),
        );
    }

    
    protected function code_map() {
        return array(
            'created'          => 'created',
            'in_transit'       => 'in_transit',
            'out_for_delivery' => 'out_for_delivery',
            'delivered'        => 'delivered',
            'returning'        => 'returning',
            'returned'         => 'returned',
            'canceled'         => 'canceled',
            'attempted'        => 'attempted',
            'on_hold'          => 'on_hold',
        );
    }

    public function authenticate(array $creds) {
        $cfg     = array_merge($this->credentials(), $creds);
        $missing = array();
        foreach (array('user_alias', 'credential_value', 'api_key', 'billing_account') as $req) {
            if (empty($cfg[$req])) { $missing[] = $req; }
        }
        if (!empty($missing)) {
            return array(
                'ok'    => false,
                
                'error' => sprintf(__('Courier Center credentials missing: %s', 'ai-eshop-optimizer'), implode(', ', $missing)),
            );
        }
        return array('ok' => true, 'auth_token' => null, 'expires_at' => null);
    }

    
    public function create_voucher(array $payload) {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $cfg       = $this->credentials();
        $recipient = isset($payload['recipient']) && is_array($payload['recipient']) ? $payload['recipient'] : array();

        list($phone_land, $phone_cell) = $this->norm_phone((string) ($recipient['phone'] ?? ''));

        $name = trim((string) ($recipient['name'] ?? ''));
        $city = trim((string) ($recipient['city'] ?? ''));
        $area = trim((string) ($recipient['region'] ?? ''));
        if ($area === '') { $area = $city; }

        
        
        
        $consignee = array(
            'CompanyName' => $name,
            'ContactName' => $name,
            'Address'     => trim((string) ($recipient['address'] ?? '')),
            'City'        => $city,
            'Area'        => $area,
            'ZipCode'     => (string) ($recipient['zip'] ?? ''),
            'Country'     => (string) ($recipient['country'] ?? 'GR'),
        );
        if ($phone_cell !== '') { $consignee['Mobile1'] = $phone_cell; }
        if ($phone_land !== '') { $consignee['Phone1']  = $phone_land; }
        $ref1 = (string) ($payload['reference_1'] ?? '');
        if ($ref1 !== '') { $consignee['Reference'] = $ref1; }

        
        
        
        $weight = (float) ($payload['weight'] ?? 0.5);
        if ($weight <= 0) { $weight = 0.5; }
        $pieces = max(1, (int) ($payload['pieces'] ?? 1));
        $per    = round($weight / $pieces, 3);
        if ($per <= 0) { $per = $weight; }
        $content = trim((string) ($payload['content_description'] ?? ''));
        if ($content === '') { $content = 'ΔΕΜΑΤΑ'; }
        $items = array();
        for ($i = 0; $i < $pieces; $i++) {
            $items[] = array(
                'GoodsType'        => 'NoDocs',
                'Content'          => $content,
                'IsDangerousGoods' => false,
                'IsDryIce'         => false,
                'IsFragile'        => false,
                'Weight'           => array('Unit' => 'kg', 'Value' => $per),
            );
        }

        $account = (string) ($cfg['billing_account'] ?? '');
        $bill_to = (string) ($cfg['bill_to'] ?? '');
        if ($bill_to === '') { $bill_to = 'Requestor'; }

        $body = array(
            'ShipmentDate' => (isset($payload['pickup_date']) && $payload['pickup_date'] !== '') ? (string) $payload['pickup_date'] : gmdate('Y-m-d'),
            'comments'     => (string) ($payload['comments'] ?? ''),
            'Requestor'    => array('CarrierBillingAccount' => $account),
            'Shipper'      => array('CarrierBillingAccount' => $account),
            'Consignee'    => $consignee,
            'BillTo'       => $bill_to,
            'Items'        => $items,
            'Reference1'   => $ref1,
            'Reference2'   => (string) ($payload['reference_2'] ?? ''),
        );
        $basic = trim((string) ($cfg['basic_service'] ?? ''));
        if ($basic !== '') { $body['BasicService'] = $basic; }

        
        $cod_amount = (float) ($payload['cod_amount'] ?? 0);
        if ($cod_amount > 0) {
            $body['CODs'] = array(array(
                'Type'   => 'cash',
                'Amount' => array('Currency' => 'EUR', 'Value' => $cod_amount),
            ));
        }

        $resp = $this->post('Shipment', $body);
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $result     = isset($resp['Result']) ? (string) $resp['Result'] : '';
        $voucher_no = isset($resp['ShipmentNumber']) ? (string) $resp['ShipmentNumber'] : '';
        if (($result !== 'Success' && $result !== 'PartialSuccess') || $voucher_no === '') {
            $err = $this->errors_to_string($resp);
            if ($err === '') {
                
                $err = ($result !== '') ? sprintf(__('Courier Center returned %s', 'ai-eshop-optimizer'), $result)
                                        : __('No shipment number in Courier Center response', 'ai-eshop-optimizer');
            }
            
            error_log('[AIEO-CC-CREATE-FAIL] body=' . wp_json_encode($body) . ' response=' . substr(wp_json_encode($resp), 0, 1200));
            return array('ok' => false, 'error' => $err, 'raw' => $resp);
        }

        $subs = array();
        if (!empty($resp['TrackingNumbers']) && is_array($resp['TrackingNumbers'])) {
            foreach ($resp['TrackingNumbers'] as $tn) {
                $tn = trim((string) $tn);
                if ($tn !== '') { $subs[] = $tn; }
            }
        }

        return array(
            'ok'          => true,
            'voucher_no'  => $voucher_no,
            'subvouchers' => $subs,
            'job_id'      => null,
            'raw'         => $resp,
        );
    }

    
    public function get_label_pdf($voucher_no, $format = 'A4') {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $cfg      = $this->credentials();
        $template = trim((string) ($cfg['default_template'] ?? ''));
        if ($template === '') {
            $template = (strtoupper($format) === 'THERMAL') ? 'singlepdf_100x150' : 'singlepdf';
        }

        $resp = $this->post('Voucher', array(
            'ShipmentNumber' => (string) $voucher_no,
            'VoucherFormat'  => 'PDF',
            'Template'       => $template,
        ));
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $b64 = isset($resp['Voucher']) ? (string) $resp['Voucher'] : '';
        if ($b64 === '') {
            $err = $this->errors_to_string($resp);
            if ($err === '') { $err = __('No voucher PDF in Courier Center response', 'ai-eshop-optimizer'); }
            error_log('[AIEO-CC-PRINT-FAIL] voucher=' . $voucher_no . ' msg="' . $err . '" response=' . substr(wp_json_encode($resp), 0, 800));
            return array('ok' => false, 'error' => $err, 'raw' => $resp);
        }

        $pdf = base64_decode($b64, true);
        if ($pdf === false || substr((string) $pdf, 0, 4) !== '%PDF') {
            error_log('[AIEO-CC-PRINT-FAIL] voucher=' . $voucher_no . ' base64 decode failed or not a PDF (got ' . strlen((string) $pdf) . ' bytes)');
            return array('ok' => false, 'error' => __('Courier Center returned a non-PDF payload', 'ai-eshop-optimizer'), 'raw' => $resp);
        }

        return array('ok' => true, 'pdf' => $pdf, 'pdf_url' => null);
    }

    public function cancel($voucher_no) {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $resp = $this->post('Shipment/Void', array('ShipmentNumber' => (string) $voucher_no));
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $result = isset($resp['Result']) ? (string) $resp['Result'] : '';
        if ($result === 'Success' || $result === 'PartialSuccess') { return array('ok' => true); }

        $err = $this->errors_to_string($resp);
        return array('ok' => false, 'error' => ($err !== '' ? $err : ($result !== '' ? $result : 'cancel_failed')));
    }

    public function track($voucher_no) {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $vn = trim((string) $voucher_no);
        if ($vn === '') { return array('ok' => false, 'error' => __('Missing voucher number.', 'ai-eshop-optimizer')); }

        
        
        
        
        
        
        $det = $this->post('Shipment/GetShipmentDetails', array(
            'Identifier'         => $vn,
            'ReturnShipmentInfo' => true,
            'ReturnPodInfo'      => true,
            'ReturnTrackingInfo' => true,
        ));
        if (!is_wp_error($det) && is_array($det)) {
            $res = strtolower((string) ($det['Result'] ?? ''));
            if (($res === 'success' || $res === 'partialsuccess')
                && isset($det['ShipmentDetails'][0]) && is_array($det['ShipmentDetails'][0])) {
                return $this->parse_shipment_details($det['ShipmentDetails'][0]);
            }
        }

        
        return $this->track_via_tracking($vn);
    }

    
    private function parse_shipment_details(array $sd) {
        $pod = (isset($sd['ShipmentPodInfo']) && is_array($sd['ShipmentPodInfo'])) ? $sd['ShipmentPodInfo'] : array();
        $si  = (isset($sd['ShipmentInfo']) && is_array($sd['ShipmentInfo'])) ? $sd['ShipmentInfo'] : array();
        $ti  = (isset($sd['ShipmentTrackingInfo']) && is_array($sd['ShipmentTrackingInfo'])) ? $sd['ShipmentTrackingInfo'] : array();

        $delivered    = false;
        $delivered_at = null;
        $consignee    = null;

        
        $pod_date = trim((string) ($pod['DeliveryDate'] ?? ''));
        if ($pod_date !== '') {
            $pod_time = trim((string) ($pod['DeliveryTime'] ?? ''));
            $ts = strtotime(trim($pod_date . ' ' . $pod_time));
            if (is_int($ts)) { $delivered_at = $ts; }
            $delivered = true;
            $dt = trim((string) ($pod['DeliveredTo'] ?? ''));
            if ($dt !== '') { $consignee = $dt; }
        }

        
        $sstatus = isset($si['ShipmentStatus']) ? (int) $si['ShipmentStatus'] : 0;
        $sdesc   = (string) ($si['ShipmentStatusDesc'] ?? '');
        if (!$delivered && ($sstatus === 29
            || stripos($sdesc, 'deliverycompleted') !== false
            || stripos($sdesc, 'delivered') !== false)) {
            $delivered = true;
        }

        
        $checkpoints  = array();
        $latest_state = '';
        $latest_ts    = null;
        foreach ($ti as $e) {
            if (!is_array($e)) { continue; }
            $type = (string) ($e['Type'] ?? '');
            $name = trim((string) ($e['SystemTrackingName'] ?? ($e['Note'] ?? '')));
            $when = (string) ($e['Date'] ?? ($e['RequestTime'] ?? ($e['ExecutedOn'] ?? '')));
            $time = (string) ($e['Time'] ?? '');
            $ts   = ($when !== '') ? strtotime(trim($when . ' ' . $time)) : false;
            $ts   = is_int($ts) ? $ts : null;
            $state = $this->derive_state($name, $type);
            $checkpoints[] = array(
                'code'          => ($state !== '' ? $state : $type),
                'description'   => ($name !== '' ? $name : $type),
                'location'      => trim((string) ($e['Area'] ?? '')),
                'checkpoint_at' => $ts,
            );
            if ($state !== '' && ($latest_ts === null || ($ts !== null && $ts >= $latest_ts))) {
                $latest_ts    = $ts;
                $latest_state = $state;
            }
        }
        if ($latest_state === '' && $sdesc !== '') { $latest_state = $this->derive_state($sdesc, ''); }

        $status = $delivered ? 'delivered' : ($latest_state !== '' ? $latest_state : 'in_transit');

        return array(
            'ok'           => true,
            'status_code'  => $status,
            'checkpoints'  => $checkpoints,
            'consignee'    => $consignee,
            'delivered_at' => $delivered_at,
        );
    }

    
    private function track_via_tracking($voucher_no) {
        $resp = $this->post('Tracking', array('Identifier' => (string) $voucher_no));
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $list = (isset($resp['TrackingList']) && is_array($resp['TrackingList'])) ? $resp['TrackingList'] : array();

        $checkpoints  = array();
        $latest_state = '';
        $latest_ts    = null;
        $consignee    = null;
        $delivered_at = null;
        $delivered    = false;

        foreach ($list as $e) {
            if (!is_array($e)) { continue; }
            $note    = trim((string) ($e['Note'] ?? ''));
            $station = trim((string) ($e['StationName'] ?? ''));
            $type    = (string) ($e['Type'] ?? '');
            $when    = (string) ($e['ExecutedOn'] ?? ($e['Date'] ?? ($e['TimeStamp'] ?? '')));
            $ts      = ($when !== '') ? strtotime($when) : false;
            $ts      = is_int($ts) ? $ts : null;
            $state   = $this->derive_state($note, $type);

            $checkpoints[] = array(
                'code'          => ($state !== '' ? $state : (string) ($e['Status'] ?? '')),
                'description'   => ($note !== '' ? $note : $type),
                'location'      => $station,
                'checkpoint_at' => $ts,
            );

            
            if (strtolower($type) === 'pod' || $state === 'delivered') {
                $delivered = true;
                if ($ts !== null && ($delivered_at === null || $ts >= $delivered_at)) { $delivered_at = $ts; }
                $pod = trim((string) ($e['PODConsigneeName'] ?? ''));
                if ($consignee === null && $pod !== '') { $consignee = $pod; }
            }

            
            if ($state !== '' && ($latest_ts === null || ($ts !== null && $ts >= $latest_ts))) {
                $latest_ts    = $ts;
                $latest_state = $state;
            }
        }

        $status = $delivered ? 'delivered' : ($latest_state !== '' ? $latest_state : 'in_transit');

        return array(
            'ok'           => true,
            'status_code'  => $status,
            'checkpoints'  => $checkpoints,
            'consignee'    => $consignee,
            'delivered_at' => $delivered_at,
        );
    }

    public function shop_list() {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $resp = $this->post('Station/GetStations', array());
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $stations = (isset($resp['StationDataInfo']) && is_array($resp['StationDataInfo'])) ? $resp['StationDataInfo'] : array();
        $shops    = array();
        foreach ($stations as $s) {
            if (!is_array($s)) { continue; }
            $shops[] = array(
                'id'      => (string) ($s['ID'] ?? ($s['Code'] ?? '')),
                'code'    => (string) ($s['Code'] ?? ''),
                'prefix'  => (string) ($s['Prefix'] ?? ''),
                'name'    => (string) ($s['Name'] ?? ($s['ShortName'] ?? '')),
                'address' => trim((string) ($s['Address'] ?? '') . ' ' . (string) ($s['ZipCode'] ?? '') . ' ' . (string) ($s['City'] ?? '')),
                'city'    => (string) ($s['City'] ?? ''),
                'zip'     => (string) ($s['ZipCode'] ?? ''),
                
                'lat'     => isset($s['Latitude'])   ? (float) $s['Latitude']   : null,
                'lng'     => isset($s['Longtitude']) ? (float) $s['Longtitude'] : null,
                'clever'  => !empty($s['IsCleverPoint']),
            );
        }
        return array('ok' => true, 'shops' => $shops);
    }

    
    public function manifest($date = '') {
        $auth = $this->authenticate(array());
        if (!$auth['ok']) { return $auth; }

        $account = trim((string) ($this->credentials()['billing_account'] ?? ''));
        if ($account === '') {
            return array('ok' => false, 'error' => __('Courier Center billing account is not configured.', 'ai-eshop-optimizer'));
        }
        $date = trim((string) $date);
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) { $date = gmdate('Y-m-d'); }

        $resp = $this->post('Manifest', array('Date' => $date, 'CustomerAccount' => $account));
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }

        $result = isset($resp['Result']) ? (string) $resp['Result'] : '';
        if ($result !== 'Success' && $result !== 'PartialSuccess') {
            $err = $this->errors_to_string($resp);
            error_log('[AIEO-CC-MANIFEST-FAIL] date=' . $date . ' response=' . substr(wp_json_encode($resp), 0, 800));
            return array('ok' => false, 'error' => ($err !== '' ? $err : ($result !== '' ? $result : 'manifest_failed')), 'raw' => $resp);
        }

        
        
        $b64 = isset($resp['Manifest']) ? (string) $resp['Manifest'] : '';
        if ($b64 !== '') {
            $pdf = base64_decode($b64, true);
            if ($pdf !== false && substr((string) $pdf, 0, 4) === '%PDF') {
                return array('ok' => true, 'pdf' => $pdf);
            }
        }
        return array('ok' => true, 'pdf' => null);
    }

    

    private function credentials() {
        if (!class_exists('AIEO_Fulfillment_Settings')) { return array(); }
        $cfg = AIEO_Fulfillment_Settings::get('courier_courrier_centre', array());
        return is_array($cfg) ? $cfg : array();
    }

    
    private function context() {
        $cfg = $this->credentials();
        $ctx = array(
            'UserAlias'       => (string) ($cfg['user_alias'] ?? ''),
            'CredentialValue' => (string) ($cfg['credential_value'] ?? ''),
            'ApiKey'          => (string) ($cfg['api_key'] ?? ''),
        );
        $dc = trim((string) ($cfg['data_culture'] ?? ''));
        if ($dc !== '') { $ctx['DataCulture'] = $dc; }
        return $ctx;
    }

    private function endpoint() {
        $base = trim((string) ($this->credentials()['base_url'] ?? ''));
        if ($base === '') { $base = self::ENDPOINT_DEFAULT; }
        return rtrim($base, '/');
    }

    
    private function post($path, array $params) {
        $url  = $this->endpoint() . '/' . ltrim((string) $path, '/');
        $body = array_merge(array('Context' => $this->context()), $params);

        $resp = wp_remote_post($url, array(
            'timeout'     => 40,
            'redirection' => 0,
            'headers'     => array(
                'Content-Type' => 'application/json',
                'Accept'       => 'application/json',
            ),
            'body'        => wp_json_encode($body),
        ));
        if (is_wp_error($resp)) { return $resp; }

        $code = (int) wp_remote_retrieve_response_code($resp);
        $raw  = (string) wp_remote_retrieve_body($resp);
        $json = json_decode($raw, true);

        
        
        if (is_array($json)) { return $json; }
        if ($code !== 200) {
            
            return new WP_Error('cc_http', sprintf(__('Courier Center HTTP %d', 'ai-eshop-optimizer'), $code));
        }
        return new WP_Error('cc_payload', __('Courier Center returned non-JSON.', 'ai-eshop-optimizer'));
    }

    
    private function errors_to_string($resp) {
        if (!is_array($resp) || empty($resp['Errors']) || !is_array($resp['Errors'])) { return ''; }
        $msgs = array();
        foreach ($resp['Errors'] as $e) {
            if (is_array($e)) {
                $m = trim((string) ($e['Message'] ?? ''));
                $c = trim((string) ($e['Code'] ?? ''));
                if ($m !== '') { $msgs[] = ($c !== '' ? $c . ': ' : '') . $m; }
                elseif ($c !== '') { $msgs[] = $c; }
            } elseif (is_string($e) && trim($e) !== '') {
                $msgs[] = trim($e);
            }
        }
        return implode('; ', array_values(array_unique($msgs)));
    }

    
    private function norm_phone($raw) {
        $p = preg_replace('/\D+/', '', (string) $raw);
        if ($p !== '' && strpos($p, '0030') === 0) { $p = substr($p, 4); }
        if ($p !== '' && strpos($p, '30') === 0 && strlen($p) === 12) { $p = substr($p, 2); }
        if ($p !== '' && strlen($p) === 10) {
            return ($p[0] === '6') ? array('', $p) : array($p, '');
        }
        return array('', $p);
    }

    
    private function derive_state($note, $type) {
        $t = strtolower((string) $type);
        if ($t === 'pod')               { return 'delivered'; }
        if ($t === 'podfailure')        { return 'attempted'; }
        if ($t === 'returnedtoshipper') { return 'returned'; }

        $n = trim((string) $note);
        if ($n === '') { return ''; }

        
        
        
        $nl = strtolower($n);
        if (strpos($nl, 'undelivered') !== false || strpos($nl, 'not delivered') !== false || strpos($nl, 'failed deliver') !== false) { return 'attempted'; }
        if (strpos($nl, 'returned to ship') !== false || strpos($nl, 'return to ship') !== false) { return 'returned'; }
        if (strpos($nl, 'delivered') !== false || strpos($nl, 'deliverycompleted') !== false) { return 'delivered'; }

        $n = function_exists('mb_strtoupper') ? mb_strtoupper($n, 'UTF-8') : strtoupper($n);
        
        
        
        $n = strtr($n, array('Ά' => 'Α', 'Έ' => 'Ε', 'Ή' => 'Η', 'Ί' => 'Ι', 'Ϊ' => 'Ι', 'Ό' => 'Ο', 'Ύ' => 'Υ', 'Ϋ' => 'Υ', 'Ώ' => 'Ω'));
        $has = static function ($needle) use ($n) {
            return function_exists('mb_strpos') ? (mb_strpos($n, $needle, 0, 'UTF-8') !== false) : (strpos($n, $needle) !== false);
        };

        
        if ($has('ΠΑΡΑΔΟΘΗΚΕ'))                                   { return 'delivered'; }
        if ($has('ΠΡΟΣ ΠΑΡΑΔΟΣΗ') || $has('ΕΞΗΛΘΕ') || $has('ΔΡΟΜΟΛΟΓ')) { return 'out_for_delivery'; }
        if ($has('ΑΠΟΠΕΙΡΑ') || $has('ΑΠΟΥΣΙΑ') || $has('ΑΡΝΗΣΗ') || $has('ΛΑΘΟΣ ΔΙΕΥΘ')) { return 'attempted'; }
        if ($has('ΕΠΙΣΤΡΑΦΗΚΕ') || $has('ΕΠΕΣΤΡΑΦΗ'))             { return 'returned'; }
        if ($has('ΕΠΙΣΤΡΟΦ'))                                     { return 'returning'; }
        if ($has('ΑΚΥΡΩ'))                                        { return 'canceled'; }
        if ($has('ΕΚΚΡΕΜ') || $has('ΑΝΑΜΟΝΗ'))                    { return 'on_hold'; }
        if ($has('ΠΑΡΑΛ') || $has('ΑΠΟΣΤΟΛ') || $has('ΦΟΡΤΩ') || $has('ΕΚΦΟΡΤΩ') || $has('ΑΦΙΞ') || $has('ΕΞΟΔΟ') || $has('ΜΕΤΑΦΟΡ') || $has('ΔΙΑΛΟΓ')) { return 'in_transit'; }
        return '';
    }
}

add_filter('aieo_fulfillment_couriers', static function (array $drivers) {
    if (!isset($drivers['courrier_centre']) && class_exists('AIEO_Courier_Driver_Courrier_Centre')) {
        $drivers['courrier_centre'] = new AIEO_Courier_Driver_Courrier_Centre();
    }
    return $drivers;
});
