<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('../login.php');
if (function_exists('require_perm')) @require_perm('can_view_subscribers');
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../receiver_subscriber_match_lib.php';
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
header('Content-Type: application/json; charset=utf-8');
if (!($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>'DB not ready'], JSON_UNESCAPED_UNICODE);
    exit;
}
$key = trim((string)($_POST['key'] ?? $_GET['key'] ?? ''));
$pseudoId = (int)($_POST['pseudo_id'] ?? $_GET['pseudo_id'] ?? 0);
$name = trim((string)($_POST['name'] ?? $_GET['name'] ?? ''));
if ($key === '' && $pseudoId > 0 && function_exists('ua_rx_router_port_sources_active')) {
    $sources = ua_rx_router_port_sources_active();
    if (!empty($sources[$pseudoId]['key'])) $key = (string)$sources[$pseudoId]['key'];
}
if ($key === '' || $name === '') {
    http_response_code(400);
    echo json_encode(['ok'=>false,'message'=>'حدد المنفذ والاسم الجديد أولاً.'], JSON_UNESCAPED_UNICODE);
    exit;
}
try {
    $res = function_exists('ua_rx_router_port_source_rename')
        ? ua_rx_router_port_source_rename($key, $name)
        : ['ok'=>false,'message'=>'rename_helper_missing'];
    if (empty($res['ok'])) {
        http_response_code(404);
        echo json_encode(['ok'=>false,'message'=>'تعذر تعديل اسم المنفذ المحفوظ.','details'=>$res], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        exit;
    }
    if (function_exists('ua_receiver_match_snapshot')) {
        $snap = ua_receiver_match_snapshot($conn, 0, true);
        $res['snapshot_rebuilt'] = !empty($snap['ok']);
        $res['snapshot_summary'] = (array)($snap['summary'] ?? []);
    }
    if (function_exists('airmax_invalidate_noc_card_cache')) @airmax_invalidate_noc_card_cache();
    echo json_encode($res + ['message'=>'تم تعديل اسم المنفذ وإعادة بناء Snapshot.'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
