<?php

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

abstract class AIEO_Courier_Driver_Base {

    
    abstract public function code();

    
    abstract public function label();

    
    abstract public function capabilities();

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

    
    public function map_status($raw_code) {
        $map = $this->code_map();
        return isset($map[$raw_code]) ? $map[$raw_code] : 'unknown';
    }

    
    protected function code_map() {
        return array();
    }

    
    public function tracking_url($voucher_no) {
        $tpl = (string) $this->get_setting('tracking_url_template', '');
        if ($tpl !== '') {
            return str_replace('{voucher_no}', rawurlencode((string) $voucher_no), $tpl);
        }
        return '';
    }

    
    protected function get_setting($key, $default = '') {
        if (!class_exists('AIEO_Fulfillment_Settings')) { return $default; }
        $code = method_exists($this, 'code') ? (string) $this->code() : '';
        if ($code === '') { return $default; }
        $cfg = (array) AIEO_Fulfillment_Settings::get('courier_' . $code, array());
        return array_key_exists($key, $cfg) ? $cfg[$key] : $default;
    }

    
    
    
    

    
    public function authenticate(array $creds) {
        return array('ok' => true, 'auth_token' => null, 'expires_at' => null);
    }

    
    public function create_voucher(array $payload) {
        return $this->unsupported('create_voucher');
    }

    
    public function get_label_pdf($voucher_no, $format = 'A4') {
        return $this->unsupported('get_label_pdf');
    }

    
    public function cancel($voucher_no) {
        return $this->unsupported('cancel');
    }

    
    public function track($voucher_no) {
        return $this->unsupported('track');
    }

    
    public function calculate_cost(array $payload) {
        return $this->unsupported('calculate_cost');
    }

    
    public function track_simple($voucher_no) {
        $r = $this->track($voucher_no);
        if (!is_array($r) || empty($r['ok'])) { return $r; }
        
        unset($r['checkpoints']);
        return $r;
    }

    
    public function close_pending($voucher_nos = null) {
        return $this->unsupported('close_pending');
    }

    
    public function close_pending_by_date($from_iso, $to_iso) {
        return $this->unsupported('close_pending_by_date');
    }

    
    public function shop_list() {
        return $this->unsupported('shop_list');
    }

    private function unsupported($method) {
        return array(
            'ok'    => false,
            
            'error' => sprintf( __('Driver "%1$s" does not support %2$s.', 'ai-eshop-optimizer'), $this->code(), $method),
        );
    }

    
    public function has_capability($cap) {
        return in_array($cap, $this->capabilities(), true);
    }

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