<?php
ini_set('display_errors','0');

// Save Quick Setup Wizard payload (routers + sectors)
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/api_common.php';

api_require_login();
if (function_exists('require_perm')) {
  require_perm('can_settings');
}

require_once __DIR__ . '/../comms_admin_lib.php';

header('Content-Type: application/json; charset=utf-8');

try {
  $conn = ensure_db(false);
  if (!$conn || !($conn instanceof mysqli)) {
    echo json_encode(['ok'=>false,'code'=>'DB','msg'=>'Database connection not initialized']);
    exit;
  }
  comms_ensure_tables($conn);

  $raw = file_get_contents('php://input');
  $data = json_decode($raw, true);
  if (!is_array($data)) {
    echo json_encode(['ok'=>false,'msg'=>'Invalid JSON']);
    exit;
  }

  $scenario = isset($data['scenario']) ? trim((string)$data['scenario']) : '';
  $routers  = isset($data['routers']) && is_array($data['routers']) ? $data['routers'] : [];
  $sectors  = isset($data['sectors']) && is_array($data['sectors']) ? $data['sectors'] : [];

  // Save scenario
  if ($scenario !== '') {
    $k = $conn->real_escape_string('scenario');
    $v = $conn->real_escape_string($scenario);
    $conn->query("INSERT INTO comms_settings (k,v) VALUES ('$k','$v') ON DUPLICATE KEY UPDATE v=VALUES(v)");
  }

  // Upsert routers
  $savedRouters = [];
  foreach ($routers as $r) {
    $name = trim((string)($r['name'] ?? ''));
    $host = trim((string)($r['host'] ?? ''));
    $port = (int)($r['api_port'] ?? 8728);
    $user = trim((string)($r['username'] ?? ''));
    $pass = (string)($r['password'] ?? '');
    $role = trim((string)($r['role'] ?? 'other'));
    $model = trim((string)($r['model'] ?? ''));

    if ($name === '' || $host === '' || $user === '') continue;
    if (!in_array($role, ['uplink','pppoe','monitor','other'], true)) $role = 'other';
    if ($port <= 0) $port = 8728;

    $nameE = $conn->real_escape_string($name);
    $hostE = $conn->real_escape_string($host);
    $userE = $conn->real_escape_string($user);
    $passE = $conn->real_escape_string($pass);
    $roleE = $conn->real_escape_string($role);
    $modelE = $conn->real_escape_string($model);

    // Try match by host+port
    $q = $conn->query("SELECT id FROM routers WHERE host='$hostE' AND api_port=".(int)$port." LIMIT 1");
    if ($q && $q->num_rows > 0) {
      $id = (int)$q->fetch_assoc()['id'];
      $conn->query("UPDATE routers SET name='$nameE', username='$userE', password='$passE', role='$roleE', model='$modelE', is_enabled=1 WHERE id=$id");
    } else {
      $conn->query("INSERT INTO routers (name,host,api_port,username,password,model,role,is_enabled) VALUES ('$nameE','$hostE',".(int)$port.",'$userE','$passE','$modelE','$roleE',1)");
      $id = (int)$conn->insert_id;
    }
    $savedRouters[] = ['id'=>$id,'role'=>$role,'name'=>$name];
  }

  // Pick PPPoE router for sectors
  $pppoe = comms_router_by_role($conn, 'pppoe');
  $pppoeId = $pppoe ? (int)$pppoe['id'] : 0;
  if ($pppoeId === 0 && !empty($savedRouters)) {
    // fallback: first router
    $pppoeId = (int)$savedRouters[0]['id'];
  }

  // Upsert sectors
  foreach ($sectors as $s) {
    $name = trim((string)($s['name'] ?? ''));
    $vlan = (int)($s['vlan_id'] ?? 0);
    $trunk = trim((string)($s['trunk_interface'] ?? 'ether2'));
    $bridge = trim((string)($s['bridge_name'] ?? 'bridge-pppoe'));
    $profile = trim((string)($s['pppoe_profile'] ?? ''));

    if ($name === '' || $vlan <= 0) continue;
    if ($pppoeId <= 0) continue;

    $plan = comms_suggest_pool_for_vlan($vlan);

    $nameE = $conn->real_escape_string($name);
    $trunkE = $conn->real_escape_string($trunk);
    $bridgeE = $conn->real_escape_string($bridge);
    $poolNameE = $conn->real_escape_string($plan['pool_name']);
    $poolRangeE = $conn->real_escape_string($plan['pool_range']);
    $localE = $conn->real_escape_string($plan['local_ip']);
    $srvE = $conn->real_escape_string($plan['server_name']);
    $svcE = $conn->real_escape_string($plan['service']);
    $profileE = $conn->real_escape_string($profile);

    $q = $conn->query("SELECT id FROM sectors WHERE vlan_id=$vlan AND router_id=$pppoeId LIMIT 1");
    if ($q && $q->num_rows > 0) {
      $id = (int)$q->fetch_assoc()['id'];
      $conn->query("UPDATE sectors SET name='$nameE', trunk_interface='$trunkE', bridge_name='$bridgeE', pppoe_pool_name='$poolNameE', pppoe_pool_range='$poolRangeE', pppoe_local_ip='$localE', pppoe_service='$svcE', pppoe_server_name='$srvE', pppoe_profile='$profileE', is_enabled=1 WHERE id=$id");
    } else {
      $conn->query("INSERT INTO sectors (name,vlan_id,router_id,trunk_interface,bridge_name,pppoe_pool_name,pppoe_pool_range,pppoe_local_ip,pppoe_service,pppoe_server_name,pppoe_profile,is_enabled) VALUES ('$nameE',$vlan,$pppoeId,'$trunkE','$bridgeE','$poolNameE','$poolRangeE','$localE','$svcE','$srvE','$profileE',1)");
    }
  }

  echo json_encode(['ok'=>true,'msg'=>'Saved','routers'=>$savedRouters]);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'msg'=>$e->getMessage()]);
}
