<?php
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../mikrotik_lib.php';
require_once __DIR__ . '/../subscribers_lib.php';
require_once __DIR__ . '/../db_bootstrap.php';
ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if ($conn instanceof mysqli && function_exists('subs_ensure_pppoe_cols')) subs_ensure_pppoe_cols($conn);

require_login();
if(function_exists('require_perm')) require_perm('can_mikrotik_sync');

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

function j($a){
  echo json_encode($a, JSON_UNESCAPED_UNICODE);
  exit;
}

try {
  $hotspot = !empty($_GET['hotspot']);
  $ppp     = !empty($_GET['ppp']);

  if(!$hotspot && !$ppp){
    j(['ok'=>true,'total'=>0,'new_count'=>0,'existing_count'=>0,'preview'=>[]]);
  }

  // Fetch from MikroTik
  $items = [];
  if($hotspot){
    foreach(mt_hotspot_users($conn) as $u){
      $items[] = [
        'type' => 'hotspot',
        'username' => $u['username'],
        'password' => $u['password'],
        'profile'  => $u['profile'],
        'rate_limit' => '',
        'service' => '',
        'limit_bytes_in' => (int)($u['limit_bytes_in'] ?? 0),
        'limit_bytes_out' => (int)($u['limit_bytes_out'] ?? 0),
        'limit_bytes_total' => (int)($u['limit_bytes_total'] ?? 0),
        'disabled' => !empty($u['disabled']),
        'comment' => (string)($u['comment'] ?? ''),
      ];
    }
  }
  if($ppp){
    foreach(mt_ppp_secrets($conn) as $u){
      $items[] = [
        'type' => 'pppoe',
        'username' => $u['username'],
        'password' => $u['password'],
        'profile'  => $u['profile'],
        'rate_limit' => $u['rate_limit'],
        'service' => $u['service'],
        'limit_bytes_in' => (int)($u['limit_bytes_in'] ?? 0),
        'limit_bytes_out' => (int)($u['limit_bytes_out'] ?? 0),
        'limit_bytes_total' => 0,
        'disabled' => !empty($u['disabled']),
        'comment' => (string)($u['comment'] ?? ''),
      ];
    }
  }

  // Build set of existing usernames
  $existing = [];
  if(table_exists($conn,'subscribers')){
    $r = $conn->query("SELECT username FROM subscribers WHERE username IS NOT NULL AND username<>''");
    if($r){
      while($row = $r->fetch_assoc()){
        $existing[trim((string)$row['username'])] = true;
      }
    }
  }

  $newCount = 0; $exCount = 0;
  foreach($items as &$it){
    $it['exists'] = !empty($existing[$it['username']]);
    if($it['exists']) $exCount++; else $newCount++;
  }
  unset($it);

  // Preview first 200
  $preview = array_slice($items, 0, 200);

  j([
    'ok'=>true,
    'total'=>count($items),
    'new_count'=>$newCount,
    'existing_count'=>$exCount,
    'preview'=>$preview
  ]);

} catch (Throwable $e) {
  j(['ok'=>false,'error'=>$e->getMessage()]);
}
