<?php
// admin/ppp_sync_speeds.php
// Apply PPP speed/profile for all active (non-archived) subscribers based on DB speed_name/package_name.
// Uses mt_provision_ppp_for_subscriber() to upsert /ppp secret with correct profile.

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/helpers.php';
if (function_exists('ensure_db')) ensure_db(true);

require_login();
if (function_exists('require_perm')) { @require_perm('can_mikrotik'); }

require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/ppp_speed_map.php';

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

$limit = (int)($_POST['limit'] ?? ($_GET['limit'] ?? 3000));
$dry   = (int)($_POST['dry'] ?? ($_GET['dry'] ?? 0));

$ok=0; $fail=0; $updated=0;
$errors=[];

$cond = "COALESCE(is_deleted,0)=0 AND TRIM(COALESCE(ppp_username,''))<>''";
$sql = "SELECT id, username, ppp_username, ppp_password, ppp_profile, speed_name, package_name FROM subscribers WHERE $cond ORDER BY id ASC LIMIT ".$limit;
$res = $conn->query($sql);
if(!$res){
  echo json_encode(['ok'=>false,'msg'=>'DB error: '.$conn->error], JSON_UNESCAPED_UNICODE);
  exit;
}

while($row = $res->fetch_assoc()){
  $sid = (int)$row['id'];
  $speed = (string)($row['speed_name'] ?? '');
  $pkg   = (string)($row['package_name'] ?? '');
  $cur   = trim((string)($row['ppp_profile'] ?? ''));
  $user  = trim((string)($row['ppp_username'] ?? ''));
  if ($user === '') $user = trim((string)($row['username'] ?? ''));
  $want  = ppp_profile_from_speed($speed, $pkg, ($cur !== '' && strtoupper($cur) !== 'UNLIMITED') ? $cur : '');
  if ($want === '' || $want === 'pppoe-profile') {
    $want = ppp_profile_from_username($user, $want);
  }
  if ($want === '') {
    $want = $cur !== '' ? $cur : 'pppoe-profile';
  }

  if($want !== '' && $want !== $cur){
    $st = $conn->prepare("UPDATE subscribers SET ppp_profile=? WHERE id=? LIMIT 1");
    if($st){
      $st->bind_param('si',$want,$sid);
      @$st->execute();
      $st->close();
      $updated++;
    }
  }

  if($dry){
    $ok++;
    continue;
  }

  $r = mt_provision_ppp_for_subscriber($conn, $sid);
  if(!empty($r['ok'])){
    $ok++;
  } else {
    $fail++;
    if(count($errors) < 15){
      $errors[] = ['id'=>$sid,'user'=>$row['ppp_username'],'err'=>$r['msg'] ?? 'failed'];
    }
  }
}

echo json_encode([
  'ok'=>true,
  'dry'=>$dry,
  'total'=>$ok+$fail,
  'success'=>$ok,
  'failed'=>$fail,
  'profiles_updated_in_db'=>$updated,
  'errors'=>$errors,
], JSON_UNESCAPED_UNICODE);
