<?php
// admin/api/mikrotik_set_api_any.php
// Set /ip service api address to 0.0.0.0/0 (Any)

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/api_common.php';


require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../mikrotik_lib.php';

ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;

require_login('login.php');
if (function_exists('require_perm')) require_perm('can_settings');

$api = mt_api_connect($conn);
if(!$api){
  out(['ok'=>false,'error'=> (string)($GLOBALS['mt_last_error'] ?? 'فشل الاتصال بالراوتر')], 200);
}

try {
  // Find api service row
  $rows = $api->command(['/ip/service/print', '?name=api']);
  $id = null;
  foreach($rows as $r){
    if (($r['.type'] ?? '') !== '!re') continue;
    $id = $r['.id'] ?? null;
    break;
  }
  if(!$id){
    out(['ok'=>false,'error'=>'لم يتم العثور على خدمة api ضمن /ip service'], 200);
  }

  $api->command(['/ip/service/set', '=.id='.$id, '=address=0.0.0.0/0']);

  out(['ok'=>true,'msg'=>'API set to Any (0.0.0.0/0)']);
} catch (Throwable $e) {
  out(['ok'=>false,'error'=>$e->getMessage()], 200);
} finally {
  try { $api->disconnect(); } catch (Throwable $e) {}
}
