<?php
// subscriber_pppoe_action_lib.php
// Stage 6: shared helpers for manual PPPoE cut/restore endpoints.
// Keeps the current behavior while removing duplicated helper functions from API files.

if (!function_exists('ua_pppoe_action_col_exists')) {
  function ua_pppoe_action_col_exists(mysqli $conn, string $table, string $col): bool {
    $t = $conn->real_escape_string($table);
    $c = $conn->real_escape_string($col);
    $sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1";
    $rs = $conn->query($sql);
    return ($rs && $rs->num_rows > 0);
  }
}

if (!function_exists('ua_pppoe_action_verify_super')) {
  function ua_pppoe_action_verify_super(mysqli $conn, string $input): bool {
    $input = trim($input);
    if ($input === '') return false;

    $res = $conn->query("SELECT password FROM admin_users WHERE id=1 LIMIT 1");
    if (!$res || !$res->num_rows) return false;
    $row = $res->fetch_assoc();
    $stored = (string)($row['password'] ?? '');
    if ($stored === '') return false;

    if (preg_match('/^\$2y\$|^\$2a\$|^\$argon2/i', $stored)) {
      return password_verify($input, $stored);
    }
    return hash_equals($stored, $input);
  }
}

if (!function_exists('ua_pppoe_action_cache_purge')) {
  function ua_pppoe_action_cache_purge(?string $projectRoot = null): void {
    $base = $projectRoot ?: __DIR__;
    $dir = rtrim($base, '/\\') . '/cache/runtime';
    foreach (['ppp_disabled_state_map.json','ppp_secret_reality_map.json','ppp_active.json'] as $name) {
      $f = $dir . '/' . $name;
      if (is_file($f)) { @unlink($f); }
    }
  }
}

if (!function_exists('ua_pppoe_action_ensure_disable_columns')) {
  function ua_pppoe_action_ensure_disable_columns(mysqli $conn): void {
    try {
      if (!ua_pppoe_action_col_exists($conn,'subscribers','ppp_is_disabled')) {
        @$conn->query("ALTER TABLE subscribers ADD COLUMN ppp_is_disabled TINYINT(1) NOT NULL DEFAULT 0");
      }
      if (!ua_pppoe_action_col_exists($conn,'subscribers','mt_disabled')) {
        @$conn->query("ALTER TABLE subscribers ADD COLUMN mt_disabled TINYINT(1) NOT NULL DEFAULT 0");
      }
    } catch(Throwable $e) {}
  }
}
