<?php

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

class AIEO_Courier_Driver_Elta extends AIEO_Courier_Driver_Base {

    const ENDPOINT = 'https://www.elta-courier.gr/track.php';

    public function code()  { return 'elta'; }
    public function label() { return 'ELTA Courier'; }

    public function capabilities() {
        return array('create', 'track');
    }

    public function create_mode() {
        return 'manual';
    }

    public function settings_schema() {
        return array();
    }

    public function tracking_url($voucher_no) {
        return AIEO_Runtime_Fulfillment_URLs::tracking_url('elta', (string) $voucher_no);
    }

    
    public function create_voucher(array $payload) {
        $voucher_no = trim((string) ($payload['manual_voucher_no'] ?? $payload['voucher_no'] ?? ''));
        if ($voucher_no === '') {
            return array('ok' => false, 'error' => __('Tracking number required.', 'ai-eshop-optimizer'));
        }
        
        
        
        $sanitized = preg_replace('/[^A-Za-z0-9]/', '', $voucher_no);
        if (strlen($sanitized) < 10) {
            return array('ok' => false, 'error' => __('ELTA tracking numbers must be at least 10 alphanumeric characters.', 'ai-eshop-optimizer'));
        }
        return array(
            'ok'          => true,
            'voucher_no'  => $sanitized,
            'subvouchers' => array(),
            'job_id'      => null,
        );
    }

    
    public function map_status($raw_code) {
        $raw = mb_strtoupper((string) $raw_code);
        if ($raw === '') { return 'unknown'; }
        
        if (mb_strpos($raw, 'ΠΡΟΣ ΠΑΡΑΔΟΣΗ')   !== false) { return 'out_for_delivery'; }
        if (mb_strpos($raw, 'ΠΡΟΣ ΔΙΑΝΟΜΗ')    !== false) { return 'out_for_delivery'; }
        if (mb_strpos($raw, 'ΕΞΟΔΟΣ')          !== false) { return 'out_for_delivery'; }
        
        
        if (mb_strpos($raw, 'ΠΑΡΑΔΟΘ')         !== false) { return 'delivered'; }
        if (mb_strpos($raw, 'ΕΓΙΝΕ ΠΑΡΑΔΟΣΗ')  !== false) { return 'delivered'; }
        if (mb_strpos($raw, 'ΕΠΙΣΤΡΟΦ')        !== false) { return 'returned'; }
        if (mb_strpos($raw, 'ΑΚΥΡΩΣ')          !== false) { return 'canceled'; }
        if (mb_strpos($raw, 'ΑΠΟΠΕΙΡ')         !== false) { return 'attempted'; }
        if (mb_strpos($raw, 'ΛΑΘΟΣ ΔΙΕΥΘΥΝΣΗ') !== false) { return 'attempted'; }
        if (mb_strpos($raw, 'ΠΑΡΑΛΑΒ')         !== false) { return 'in_transit'; }
        if (mb_strpos($raw, 'ΑΠΟΣΤΟΛ')         !== false) { return 'in_transit'; }
        if (mb_strpos($raw, 'ΔΡΟΜΟΛΟΓ')        !== false) { return 'in_transit'; }
        if (mb_strpos($raw, 'ΦΟΡΤΩΣ')          !== false) { return 'in_transit'; }
        if (mb_strpos($raw, 'ΕΚΦΟΡΤΩΣ')        !== false) { return 'in_transit'; }
        return 'unknown';
    }

    public function track($voucher_no) {
        $voucher_no = trim((string) $voucher_no);
        if ($voucher_no === '') {
            return array('ok' => false, 'error' => 'voucher_no required');
        }

        $resp = wp_remote_post(self::ENDPOINT, array(
            'timeout'     => 20,
            'redirection' => 0,
            'headers'     => array('Accept' => 'application/json, text/plain, */*'),
            'body'        => array('number' => $voucher_no),
        ));
        if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); }
        $code = (int) wp_remote_retrieve_response_code($resp);
        if ($code !== 200) {
            
            return array('ok' => false, 'error' => sprintf(__('ELTA HTTP %d', 'ai-eshop-optimizer'), $code));
        }
        $body = (string) wp_remote_retrieve_body($resp);
        $payload = json_decode($body, true);
        if (!is_array($payload) || !isset($payload['result'])) {
            return array('ok' => false, 'error' => __('ELTA: unexpected response shape', 'ai-eshop-optimizer'));
        }

        
        $outer = $payload['result'];
        if (!is_array($outer) || empty($outer)) {
            return array('ok' => true, 'status_code' => '', 'checkpoints' => array());
        }
        $first = reset($outer);
        $inner = isset($first['result']) ? $first['result'] : null;
        if ($inner === 'wrong number' || !is_array($inner)) {
            return array('ok' => false, 'error' => 'ELTA: tracking number not found');
        }

        $checkpoints = array();
        $latest_code = '';
        $delivered_at = null;

        foreach ($inner as $cp) {
            $status = trim((string) ($cp['status'] ?? ''));
            $place  = trim((string) ($cp['place']  ?? ''));
            $date   = trim((string) ($cp['date']   ?? '')); 
            $time   = trim((string) ($cp['time']   ?? '')); 
            $ts     = null;
            if ($date !== '' && $time !== '') {
                
                
                
                $dt = DateTime::createFromFormat('d-m-Y H:i', $date . ' ' . $time);
                if ($dt) { $ts = $dt->getTimestamp(); }
            }
            $checkpoints[] = array(
                'code'          => $status,
                'description'   => $status,
                'location'      => $place,
                'checkpoint_at' => is_int($ts) ? $ts : null,
            );
            if ($status !== '') { $latest_code = $status; }
            if ($this->map_status($status) === 'delivered' && is_int($ts)) {
                $delivered_at = $ts;
            }
        }

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

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