<?php

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

class AIEO_MOI_Provider_Skroutz implements AIEO_MOI_Provider {

    const API_BASE = 'https://api.skroutz.gr';

    public function slug()  { return 'skroutz'; }
    public function label() { return 'Skroutz'; }

    public function credential_fields() {
        return array(
            array(
                'name'        => 'api_token',
                'label'       => __('API Token', 'marketplace-order-importer'),
                'type'        => 'password',
                'required'    => true,
                'description' => __('From your Skroutz Merchant Account → API settings.', 'marketplace-order-importer'),
            ),
        );
    }

    public function validate_credentials(array $credentials) {
        return !empty($credentials['api_token']) && strlen((string) $credentials['api_token']) >= 8;
    }

    
    public function verify_webhook($request, array $vendor) {
        $body = $request->get_json_params();
        if (!is_array($body) || empty($body['event_type'])) {
            return new WP_Error('bad_body', 'Missing event_type');
        }
        return true;
    }

    
    public function parse_webhook_payload(array $body) {
        $event = (string) ($body['event_type'] ?? 'order_updated');
        
        
        
        
        
        
        if (isset($body['order']) && is_array($body['order']) && !empty($body['order'])) {
            $skz = $body['order'];
        } elseif (isset($body['id']) || isset($body['code'])) {
            $skz = $body;
        } else {
            $skz = array();
        }
        if (empty($skz)) { return array(); }

        $customer = isset($skz['customer']) ? $skz['customer'] : array();
        $caddr    = isset($customer['address']) ? $customer['address'] : array();
        $billing = array(
            'first_name' => (string) ($customer['first_name'] ?? ''),
            'last_name'  => (string) ($customer['last_name'] ?? ''),
            'address_1'  => trim((string) ($caddr['street_name'] ?? '') . ' ' . (string) ($caddr['street_number'] ?? '')),
            'city'       => (string) ($caddr['city'] ?? ''),
            'postcode'   => (string) ($caddr['zip'] ?? ''),
            'country'    => 'GR',
            'phone'      => (string) ($customer['phone'] ?? ''),
            'email'      => (string) ($customer['email'] ?? ''),
        );
        $shipping = $billing;

        
        
        
        
        
        
        
        
        
        
        $line_items   = array();
        $computed_sum = 0.0;
        foreach ((array) ($skz['line_items'] ?? array()) as $li) {
            $unit_price = (float) ($li['unit_price'] ?? $li['price'] ?? 0);
            $qty        = (int) ($li['quantity'] ?? 1);
            $title      = (string) ($li['product_name'] ?? $li['name'] ?? '');
            $tax        = (float) ($li['readjusted_vat'] ?? $li['tax'] ?? 0);
            $line_total = (float) ($li['total_price'] ?? ($unit_price * $qty));
            $computed_sum += $line_total;
            $line_items[] = array(
                'remote_id'  => (string) ($li['shop_uid'] ?? ''),
                'qty'        => $qty,
                'unit_price' => $unit_price,
                'tax'        => $tax,
                'title'      => $title,
            );
        }

        $tracking_codes = isset($skz['courier_tracking_codes']) && is_array($skz['courier_tracking_codes'])
            ? array_values(array_map('strval', $skz['courier_tracking_codes']))
            : array();

        $invoice_payload = null;
        if (!empty($skz['invoice'])) {
            $inv = isset($skz['invoice_details']) ? $skz['invoice_details'] : array();
            $invoice_payload = array(
                'company'    => (string) ($inv['company']    ?? ''),
                'profession' => (string) ($inv['profession'] ?? ''),
                'vat'        => (string) ($inv['vat_number'] ?? ''),
                'doy'        => (string) ($inv['doy']        ?? ''),
                'address_1'  => trim((string) ($inv['address']['street_name'] ?? '') . ' ' . (string) ($inv['address']['street_number'] ?? '')),
                'city'       => (string) ($inv['address']['city']   ?? ''),
                'postcode'   => (string) ($inv['address']['zip']    ?? ''),
                'region'     => (string) ($inv['address']['region'] ?? ''),
            );
        }

        
        
        
        
        
        
        
        $accept_options = null;
        if (isset($skz['accept_options']) && is_array($skz['accept_options'])) {
            $accept_options = array(
                'pickup_location' => isset($skz['accept_options']['pickup_location']) && is_array($skz['accept_options']['pickup_location'])
                    ? array_values($skz['accept_options']['pickup_location'])
                    : array(),
                'pickup_window'   => isset($skz['accept_options']['pickup_window']) && is_array($skz['accept_options']['pickup_window'])
                    ? array_values($skz['accept_options']['pickup_window'])
                    : array(),
            );
        }

        
        
        
        
        
        
        return array(
            'event_type'      => $event,
            'remote_order_id' => (string) ($skz['id']   ?? ($skz['code'] ?? '')),
            'remote_code'     => (string) ($skz['code'] ?? ''),
            'state'           => (string) ($skz['state'] ?? ''),
            'billing'         => $billing,
            'shipping'        => $shipping,
            'line_items'      => $line_items,
            
            
            
            'totals'          => array(
                'shipping' => (float) ($skz['shipping_cost'] ?? 0),
                'tax'      => (float) ($skz['tax_total']     ?? 0),
                'fees'     => 0.0,
                'total'    => (float) ($skz['total'] ?? $computed_sum),
            ),
            'courier'         => (string) ($skz['courier'] ?? ''),
            'voucher_url'     => (string) ($skz['courier_voucher'] ?? ''),
            'tracking_codes'  => $tracking_codes,
            'invoice'         => $invoice_payload,
            'gift_wrap'       => !empty($skz['gift_wrap']),
            'accept_options'  => $accept_options,
            'raw'             => $body,
        );
    }

    public function accept_order(array $vendor, $remote_order_id, array $opts = array()) {
        $resp = $this->api_request($vendor, 'POST', '/merchants/ecommerce/orders/' . rawurlencode((string) $remote_order_id) . '/accept', $opts);
        return $this->translate_response($resp, __('Order accepted on Skroutz.', 'marketplace-order-importer'));
    }

    public function reject_order(array $vendor, $remote_order_id, $reason = '') {
        $body = array();
        if ($reason !== '') { $body['reason'] = (string) $reason; }
        $resp = $this->api_request($vendor, 'POST', '/merchants/ecommerce/orders/' . rawurlencode((string) $remote_order_id) . '/reject', $body);
        return $this->translate_response($resp, __('Order rejected on Skroutz.', 'marketplace-order-importer'));
    }

    public function fetch_voucher(array $vendor, $remote_order_id) {
        $resp = $this->api_request($vendor, 'GET', '/merchants/ecommerce/orders/' . rawurlencode((string) $remote_order_id), array());
        if (is_wp_error($resp) || empty($resp['order']['courier_voucher'])) { return ''; }
        return (string) $resp['order']['courier_voucher'];
    }

    public function poll_orders(array $vendor, $since_ts) {
        
        
        
        return array();
    }

    
    public function backfill_orders(array $vendor, $since_ts, $until_ts) {
        $since = max(0, (int) $since_ts);
        $until = (int) $until_ts > 0 ? (int) $until_ts : time();
        if ($until < $since) { return array(); }

        $orders_out = array();
        $page = 1;
        $loop_guard = 0;

        while ($loop_guard++ < 40) {
            $resp = $this->api_request($vendor, 'GET', '/merchants/ecommerce/orders?page=' . $page . '&per=25', array());
            if (is_wp_error($resp)) { break; }
            $list = isset($resp['orders']) && is_array($resp['orders']) ? $resp['orders'] : array();
            if (empty($list)) { break; }

            $any_in_window = false;
            $any_older     = false;
            foreach ($list as $skz) {
                if (!is_array($skz)) { continue; }
                $created_iso = (string) ($skz['created_at'] ?? $skz['expected_dispatch_after'] ?? '');
                $created_ts  = $created_iso !== '' ? (int) strtotime($created_iso) : 0;

                
                
                if ($created_ts > 0) {
                    if ($created_ts < $since) { $any_older = true; continue; }
                    if ($created_ts > $until) { continue; }
                }
                $any_in_window = true;

                
                
                $canonical = $this->parse_webhook_payload(array(
                    'event_type' => 'reconcile',
                    'order'      => $skz,
                ));
                if (!empty($canonical['remote_order_id'])) {
                    $orders_out[] = $canonical;
                }
            }

            
            
            if ($any_older && !$any_in_window) { break; }

            
            
            if (count($list) < 25) { break; }
            $page++;
        }

        return $orders_out;
    }

    
    private function api_request(array $vendor, $method, $path, array $body = array()) {
        $api_token = (string) ($vendor['credentials']['api_token'] ?? '');
        if ($api_token === '') {
            return new WP_Error('no_token', __('Skroutz API token not configured.', 'marketplace-order-importer'));
        }
        $url = self::API_BASE . $path;
        $args = array(
            'method'  => $method,
            'timeout' => 30,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_token,
                
                
                
                
                'Accept'        => 'application/vnd.skroutz+json; version=3.0',
                'Content-Type'  => 'application/json',
                
                
                
                
                
                
                
                'User-Agent'    => 'AIEO-MarketplaceOrderImporter/' . (defined('AIEO_MOI_VERSION') ? AIEO_MOI_VERSION : '1.0.0') . ' (+https://eshop-optimizer.com)',
            ),
        );
        if ($method !== 'GET' && !empty($body)) {
            $args['body'] = wp_json_encode($body);
        }
        $resp = wp_remote_request($url, $args);
        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 ($code >= 400) {
            $msg = is_array($json) && !empty($json['error']) ? (string) $json['error'] : ('HTTP ' . $code);
            return new WP_Error('skroutz_api_error', $msg, array('status' => $code, 'body' => $raw));
        }
        return is_array($json) ? $json : array();
    }

    private function translate_response($resp, $success_msg) {
        if (is_wp_error($resp)) {
            return array('ok' => false, 'message' => $resp->get_error_message());
        }
        $voucher = '';
        if (is_array($resp) && !empty($resp['order']['courier_voucher'])) {
            $voucher = (string) $resp['order']['courier_voucher'];
        }
        return array('ok' => true, 'message' => $success_msg, 'voucher_url' => $voucher);
    }
}

AIEO_MOI_Provider_Registry::register(new AIEO_MOI_Provider_Skroutz());
