<?php
/**
 * utmify-retry.php
 * Reprocessa pedidos que falharam no envio para a Utmify.
 *
 * Uso:
 *   php utmify-retry.php          -> Lista pedidos falhados
 *   php utmify-retry.php --send   -> Reenvia todos os pedidos falhados
 *   php utmify-retry.php --log    -> Mostra ultimas 50 linhas do log
 *
 * Tambem pode ser chamado via browser (protegido por token):
 *   /utmify-retry.php?token=SEU_TOKEN&action=list
 *   /utmify-retry.php?token=SEU_TOKEN&action=send
 *   /utmify-retry.php?token=SEU_TOKEN&action=log
 */

// Carregar credenciais do arquivo de config centralizado
$_secrets = require __DIR__ . '/secrets-config.php';

define('UTMIFY_API_URL', $_secrets['utmify_api_url']);
define('UTMIFY_API_TOKEN', $_secrets['utmify_api_token']);
define('FAILED_DIR', __DIR__ . '/.utmify_pending/failed');
define('LOG_FILE', __DIR__ . '/.utmify_pending/utmify_log.jsonl');
define('RETRY_TOKEN', $_secrets['utmify_retry_token']);

unset($_secrets);

$isCli = php_sapi_name() === 'cli';

if (!$isCli) {
    header('Content-Type: application/json; charset=utf-8');
    $token = $_GET['token'] ?? '';
    if ($token !== RETRY_TOKEN) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden']);
        exit;
    }
}

function utmify_send_retry(array $payload): array {
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE);
    $ch = curl_init(UTMIFY_API_URL);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'x-api-token: ' . UTMIFY_API_TOKEN,
        ],
        CURLOPT_POSTFIELDS => $json,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    $respJson = null;
    if (is_string($response) && $response !== '') {
        $respJson = json_decode($response, true);
    }

    $ok = ($err === '' && $http >= 200 && $http < 300);
    return [$ok, $http, $respJson, $err];
}

// Determinar acao
$action = 'list';
if ($isCli) {
    if (in_array('--send', $argv ?? [])) $action = 'send';
    elseif (in_array('--log', $argv ?? [])) $action = 'log';
} else {
    $action = $_GET['action'] ?? 'list';
}

// === LOG ===
if ($action === 'log') {
    if (!file_exists(LOG_FILE)) {
        $msg = "Nenhum log encontrado.";
        if ($isCli) { echo $msg . "\n"; exit; }
        echo json_encode(['message' => $msg]); exit;
    }
    $lines = file(LOG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $last50 = array_slice($lines, -50);
    if ($isCli) {
        foreach ($last50 as $line) echo $line . "\n";
    } else {
        $parsed = array_map(function($l) { return json_decode($l, true) ?: $l; }, $last50);
        echo json_encode(['log' => $parsed], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
    exit;
}

// === LIST / SEND ===
if (!is_dir(FAILED_DIR)) {
    $msg = "Nenhum pedido falhado encontrado.";
    if ($isCli) { echo $msg . "\n"; exit; }
    echo json_encode(['message' => $msg, 'files' => []]); exit;
}

$files = glob(FAILED_DIR . '/*.json');
if (empty($files)) {
    $msg = "Nenhum pedido falhado pendente.";
    if ($isCli) { echo $msg . "\n"; exit; }
    echo json_encode(['message' => $msg, 'files' => []]); exit;
}

$results = [];
foreach ($files as $file) {
    $data = json_decode(file_get_contents($file), true);
    if (!is_array($data) || !isset($data['payload'])) {
        if ($isCli) echo "SKIP: " . basename($file) . " (formato invalido)\n";
        continue;
    }

    $orderId = $data['payload']['orderId'] ?? '?';
    $status = $data['payload']['status'] ?? '?';
    $failedAt = $data['failed_at'] ?? '?';

    if ($action === 'list') {
        $info = [
            'file' => basename($file),
            'orderId' => $orderId,
            'status' => $status,
            'failed_at' => $failedAt,
            'original_http' => $data['http'] ?? null,
        ];
        $results[] = $info;
        if ($isCli) {
            echo sprintf("  [%s] orderId=%s status=%s failed_at=%s http=%s\n",
                basename($file), $orderId, $status, $failedAt, $data['http'] ?? '?');
        }
    }

    if ($action === 'send') {
        [$ok, $http, $resp, $err] = utmify_send_retry($data['payload']);
        $info = [
            'file' => basename($file),
            'orderId' => $orderId,
            'ok' => $ok,
            'http' => $http,
            'response' => $resp,
        ];
        $results[] = $info;

        if ($ok) {
            unlink($file);
            if ($isCli) echo "  OK: $orderId (http $http) - arquivo removido\n";
        } else {
            if ($isCli) echo "  FAIL: $orderId (http $http, err: $err)\n";
        }

        usleep(300000); // 300ms entre requests
    }
}

if ($action === 'list') {
    $count = count($results);
    if ($isCli) {
        echo "\nTotal: $count pedidos falhados pendentes.\n";
        echo "Use --send para reenviar todos.\n";
    } else {
        echo json_encode(['total' => $count, 'files' => $results], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
}

if ($action === 'send') {
    $okCount = count(array_filter($results, function($r) { return $r['ok'] ?? false; }));
    $failCount = count($results) - $okCount;
    if ($isCli) {
        echo "\nResultado: $okCount reenviados com sucesso, $failCount falharam.\n";
    } else {
        echo json_encode([
            'sent' => $okCount,
            'failed' => $failCount,
            'details' => $results,
        ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
}
