<?php
// diy-gem.com 物流查件 API — GET 客户查询 / POST 主管登记（token 保护）
header('Content-Type: application/json; charset=utf-8');
$DATA  = '/var/www/html/data/shipments.json';
$TOKEN = 'dgtrack2026';

function load_db($f){ return file_exists($f) ? (json_decode(file_get_contents($f), true) ?: []) : []; }
function save_db($f, $d){ file_put_contents($f, json_encode($d, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX); }

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $num = strtoupper(trim($_GET['num'] ?? ''));
    if ($num === '' || strlen($num) > 64 || !preg_match('/^[A-Z0-9-]+$/', $num)) {
        http_response_code(400); echo json_encode(['ok' => false, 'error' => 'bad num']); exit;
    }
    $db  = load_db($DATA);
    $rec = $db[$num] ?? null;
    echo json_encode([
        'num'        => $num,
        'registered' => $rec !== null,
        'carrier'    => $rec['carrier']    ?? null,
        'shipped_at' => $rec['shipped_at'] ?? null,
        'note'       => $rec['note']       ?? null,
        'order_ref'  => $rec['order_ref']  ?? null,
        'track_url'  => 'https://t.17track.net/en#nums=' . urlencode($num),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true);
    if (!is_array($body) || !hash_equals($TOKEN, (string)($body['token'] ?? ''))) {
        http_response_code(403); echo json_encode(['ok' => false, 'error' => 'forbidden']); exit;
    }
    $num = strtoupper(trim($body['num'] ?? ''));
    if ($num === '' || strlen($num) > 64 || !preg_match('/^[A-Z0-9-]+$/', $num)) {
        http_response_code(400); echo json_encode(['ok' => false, 'error' => 'bad num']); exit;
    }
    $db = load_db($DATA);
    $db[$num] = [
        'carrier'    => substr((string)($body['carrier'] ?? ''), 0, 80),
        'note'       => substr((string)($body['note'] ?? ''), 0, 500),
        'order_ref'  => substr((string)($body['order_ref'] ?? ''), 0, 80),
        'shipped_at' => date('Y-m-d H:i'),
    ];
    save_db($DATA, $db);
    echo json_encode(['ok' => true, 'count' => count($db)], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(405); echo json_encode(['ok' => false, 'error' => 'method not allowed']);
