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

// Apply setup (Transit + Sectors PPPoE) from Quick Setup Wizard — Ensure / Idempotent
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_mikrotik_sync');
}

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');
  $payload = $raw ? json_decode($raw, true) : [];
  if(!is_array($payload)) $payload = [];

  $r1_ip = trim($payload['r1_transit_ip'] ?? '10.255.255.1/30');
  $r2_ip = trim($payload['r2_transit_ip'] ?? '10.255.255.2/30');

  $dry = !empty($payload['dry_run']);

  // Detect topology first
  $det = comms_detect_topology($conn);
  if(empty($det['ok'])){
    echo json_encode(['ok'=>false,'stage'=>'detect','result'=>$det], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $links = $det['links'] ?? [];

  if($dry){
    echo json_encode(['ok'=>true,'stage'=>'detect','detect'=>$det], JSON_UNESCAPED_UNICODE);
    exit;
  }


  // Apply Transit (Ensure)
  $opts = [
    'transit_uplink' => $payload['transit_uplink'] ?? ($links['transit_uplink'] ?? ''),
    'transit_pppoe'  => $payload['transit_pppoe'] ?? ($links['transit_pppoe'] ?? ''),
    'r1_ip' => $r1_ip,
    'r2_ip' => $r2_ip,
  ];
  $transitRes = comms_apply_transit($conn, $opts);

  // Apply Sectors (Ensure) on PPPoE router
  $router2 = comms_router_by_role($conn,'pppoe');
  $sectors = comms_sectors_list($conn);

  $sectorResults = [];
  if(!$router2){
    $sectorResults[] = ['ok'=>false,'msg'=>'لا يوجد Router2 بدور PPPoE | No PPPoE router defined'];
  } else {
    foreach($sectors as $s){
      // Fill missing pool fields by suggestion
      $vid = intval($s['vlan_id'] ?? 0);
      if($vid <= 0){
        $sectorResults[] = ['ok'=>false,'sector_id'=>$s['id']??null,'sector_name'=>$s['sector_name']??'','msg'=>'VLAN ID غير صالح | Invalid VLAN ID'];
        continue;
      }
      if(empty($s['pppoe_pool_name']) || empty($s['pppoe_pool_range']) || empty($s['pppoe_local_ip']) || empty($s['pppoe_server_name'])){
        $sg = comms_suggest_pool_for_vlan($vid);
        $s['pppoe_pool_name'] = $s['pppoe_pool_name'] ?: ($sg['pool_name'] ?? ('pool_vlan'.$vid));
        $s['pppoe_pool_range'] = $s['pppoe_pool_range'] ?: ($sg['pool_range'] ?? '');
        $s['pppoe_local_ip'] = $s['pppoe_local_ip'] ?: ($sg['local_ip'] ?? '');
        $s['pppoe_server_name'] = $s['pppoe_server_name'] ?: ('pppoe_vlan'.$vid);
        // We do NOT force-save suggestions to DB here to avoid unexpected edits; apply uses in-memory values.
      }
      $err='';
      $res = comms_apply_sector_pppoe($conn, $router2, $s, $err);
      if(!$res || empty($res['ok'])){
        $sectorResults[] = ['ok'=>false,'sector_id'=>$s['id']??null,'sector_name'=>$s['name']??'','msg'=>$err ?: ($res['error'] ?? ($res['msg']??'فشل تطبيق القطاع | Sector apply failed'))];
      } else {
        $sectorResults[] = ['ok'=>true,'sector_id'=>$s['id']??null,'sector_name'=>$s['name']??'','msg'=>$res['msg'] ?? 'OK'];
      }
    }
    if(count($sectors)===0){
      $sectorResults[] = ['ok'=>false,'msg'=>'لا توجد قطاعات معرفة | No sectors defined'];
    }
  }

  echo json_encode([
    'ok'=>true,
    'stage'=>'apply',
    'detect'=>$det,
    'transit'=>$transitRes,
    'sectors'=>$sectorResults
  ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e){
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
