<?php
if (!defined('ABSPATH'))
    exit;

use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Address\Action_Wear_Address as Address;
use AC_SYNC\Includes\Classes\Api\Action_Wear_Api as Api;

$route = new Action_Wear_Api_Route("/import_remote_addresses");
$route->setMethods("POST");
$route->setCallback(function () {
    $response = new ApiResponse();

    // Build request body
    $codice_cliente = get_option('_ACTIONWEAR_TOKEN_CODE');
    if (empty($codice_cliente)) {
        $response->fail("Codice cliente non configurato");
        return $response->getResponse();
    }

    $requestBody = [
        'codice_cliente_spedizione' => $codice_cliente,
    ];

    if (get_option('_ACTIONWEAR_ORDER_TEST_MODE', 0)) {
        $requestBody['test'] = 1;
    }

    // Fetch destinations from ActionWear API
    $result = Api::external('POST', '/customer_destinations', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($requestBody),
    ]);

    if ($result['code'] !== 200) {
        $response->fail("API error: HTTP {$result['code']}");
        return $response->getResponse();
    }

    $body = is_string($result['body']) ? json_decode($result['body'], true) : $result['body'];

    if (empty($body['success']) || empty($body['destinations'])) {
        $response->fail("No destinations found or API error");
        return $response->getResponse();
    }

    $existing = Address::getAll();
    $existingKeys = [];
    foreach ($existing as $addr) {
        // Dedup key: ragione_sociale + indirizzo + cap
        $key = mb_strtolower(trim($addr['ragione_sociale']) . '|' . trim($addr['indirizzo']) . '|' . trim($addr['cap']));
        $existingKeys[$key] = true;
    }

    $imported = 0;
    $skipped = 0;
    $errors = 0;

    foreach ($body['destinations'] as $dest) {
        $ragione = trim($dest['ragione_sociale'] ?? '');
        $indirizzo = trim($dest['indirizzo'] ?? '');
        $cap = trim($dest['cap'] ?? '');

        if (empty($ragione) || empty($indirizzo) || empty($cap)) {
            $skipped++;
            continue;
        }

        // Skip duplicates
        $key = mb_strtolower($ragione . '|' . $indirizzo . '|' . $cap);
        if (isset($existingKeys[$key])) {
            $skipped++;
            continue;
        }

        // Address::sanitize() requires: label, ragione_sociale, indirizzo, localita, cap, provincia
        // Use fallback '-' for optional-but-required fields to avoid silent failure
        $localita = trim($dest['localita'] ?? '');
        $provincia = trim($dest['provincia'] ?? '');

        $id = Address::create([
            'label' => $ragione,
            'ragione_sociale' => $ragione,
            'indirizzo' => $indirizzo,
            'localita' => $localita ?: '-',
            'cap' => $cap,
            'provincia' => $provincia ?: '-',
            'telefono' => trim($dest['telefono'] ?? ''),
            'nazione' => trim($dest['nazione'] ?? 'IT'),
            'fermo_deposito' => trim($dest['fermo_deposito'] ?? ''),
            'codice_destinazione' => trim($dest['codice_destinazione'] ?? ''),
        ]);

        if ($id) {
            $imported++;
            $existingKeys[$key] = true;
        } else {
            global $wpdb;
            error_log("[ActionWear] Address::create failed for '{$ragione}' - DB error: " . ($wpdb->last_error ?: 'sanitize rejected'));
            $errors++;
        }
    }

    $response->success([
        'imported' => $imported,
        'skipped' => $skipped,
        'errors' => $errors,
    ]);

    return $response->getResponse();
});
$route->registerRoute();
