<?php
require_once __DIR__ . '/app_paths.php';
if (!function_exists('h')) {
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

require_once __DIR__ . '/db_schema_helpers.php';

/* =========================
   Language (AR/EN)
========================= */
require_once __DIR__ . '/i18n_lib.php';

if (!function_exists('current_lang')) {
function current_lang(): string {
  return ua_i18n_current_lang();
}
}

if (!function_exists('t')) {
function t(string $key, ?string $fallback=null): string {
  return ua_i18n_translate_text($key, $fallback);
}
}

/* =========================
   App Version
========================= */
if (!function_exists('app_version_info')) {
function app_version_info(): array {
  static $info = null;
  if ($info !== null) return $info;

  $file = __DIR__ . '/version.php';
  $info = ['version' => '0.0.0', 'build' => null];
  if (is_file($file)) {
    $arr = include $file;
    if (is_array($arr)) {
      $v = $arr['version'] ?? null;
      $b = $arr['build'] ?? null;
      if (is_string($v) && $v !== '') $info['version'] = $v;
      if (is_string($b) && $b !== '') $info['build'] = $b;
    }
  }
  return $info;
}
}

if (!function_exists('app_version')) {
function app_version(): string {
  $i = app_version_info();
  $v = (string)($i['version'] ?? '0.0.0');
  return $v !== '' ? $v : '0.0.0';
}
}

if (!function_exists('app_build')) {
function app_build(): string {
  $i = app_version_info();
  return (string)($i['build'] ?? '');
}

/* =========================
   audit_log (compat)
   بعض الصفحات (مثل subscribers_cancel.php) تستدعي audit_log() بصيغة قديمة:
     audit_log($conn, 'ACTION', 'table', $row_id, 'details', $created_by?)
   ونسخ أخرى تستدعيها بصيغة جديدة:
     audit_log('ACTION', ['k'=>'v'], $created_by?)

   هذا التعريف يدعم الصيغتين بدون كسر المشروع.
========================= */
if (!function_exists('audit_log')) {
  function audit_log(...$args): void {
    $conn = null;
    $action_key = '';
    $payload = [];
    $created_by = null;

    if (isset($args[0]) && $args[0] instanceof mysqli) {
      $conn = $args[0];
      $action_key = (string)($args[1] ?? '');
      $table = (string)($args[2] ?? '');
      $row_id = (int)($args[3] ?? 0);
      $details = (string)($args[4] ?? '');
      $created_by = isset($args[5]) ? (is_null($args[5]) ? null : (int)$args[5]) : null;
      $payload = ['table'=>$table, 'row_id'=>$row_id, 'details'=>$details];
    } else {
      $conn = $GLOBALS['conn'] ?? null;
      $action_key = (string)($args[0] ?? '');
      $payload = (is_array($args[1] ?? null)) ? $args[1] : ['details'=>(string)($args[1] ?? '')];
      $created_by = isset($args[2]) ? (is_null($args[2]) ? null : (int)$args[2]) : null;
    }

    if (!($conn instanceof mysqli) || trim($action_key) === '') return;
    @mysqli_report(MYSQLI_REPORT_OFF);

    @$conn->query("CREATE TABLE IF NOT EXISTS action_log (
      id INT AUTO_INCREMENT PRIMARY KEY,
      action_key VARCHAR(190) NOT NULL,
      payload_hash CHAR(64) NULL,
      payload_json LONGTEXT NULL,
      action VARCHAR(190) NULL,
      details LONGTEXT NULL,
      created_by INT NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $ensureCol = static function(mysqli $c, string $table, string $col, string $ddl): void {
      $te = $c->real_escape_string($table);
      $ce = $c->real_escape_string($col);
      $rs = @$c->query("SHOW COLUMNS FROM `{$te}` LIKE '{$ce}'");
      if (!$rs || $rs->num_rows < 1) @ $c->query("ALTER TABLE `{$te}` ADD COLUMN {$ddl}");
    };
    $ensureCol($conn, 'action_log', 'action_key', '`action_key` VARCHAR(190) NOT NULL DEFAULT \'\'');
    $ensureCol($conn, 'action_log', 'payload_hash', '`payload_hash` CHAR(64) NULL');
    $ensureCol($conn, 'action_log', 'payload_json', '`payload_json` LONGTEXT NULL');
    $ensureCol($conn, 'action_log', 'action', '`action` VARCHAR(190) NULL');
    $ensureCol($conn, 'action_log', 'details', '`details` LONGTEXT NULL');
    $ensureCol($conn, 'action_log', 'created_by', '`created_by` INT NULL');
    $ensureCol($conn, 'action_log', 'created_at', '`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP');

    $json = json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    if (!is_string($json)) $json = '{}';
    $hash = hash('sha256', $action_key . '|' . $json);

    $ak = $conn->real_escape_string($action_key);
    $hj = $conn->real_escape_string($json);
    $hh = $conn->real_escape_string($hash);
    $cb = is_null($created_by) ? 'NULL' : (string)((int)$created_by);
    $detailsText = '';
    if (isset($payload['details'])) $detailsText = (string)$payload['details'];
    $de = $conn->real_escape_string($detailsText);

    @$conn->query("INSERT INTO action_log (action_key, payload_hash, payload_json, details, created_by)
                  VALUES ('$ak', '$hh', '$hj', '$de', $cb)");

    // ربط مباشر بسجل المشترك عندما يكون السجل يخص جدول subscribers.
    try {
      $table = (string)($payload['table'] ?? '');
      $rowId = (int)($payload['row_id'] ?? ($payload['subscriber_id'] ?? 0));
      if ($table === 'subscribers' && $rowId > 0) {
        $lib = __DIR__ . '/subscriber_history_lib.php';
        if (is_file($lib)) require_once $lib;
        if (function_exists('sh_log_event') && function_exists('sh_action_label')) {
          $label = sh_action_label($action_key);
          @sh_log_event($conn, $rowId, $action_key, $label, $detailsText, date('Y-m-d H:i:s'), null);
        }
      }
    } catch (Throwable $e) {}
  }
}
}

// Added: map speed/package to PPPoE profile on MikroTik
if (!function_exists('ppp_profile_from_speed')) {
function ppp_profile_from_speed(string $speed_name = '', string $package_name = '', string $fallback = 'pppoe-profile'): string {
  $sRaw = trim($speed_name);
  $pRaw = trim($package_name);
  $s = strtoupper($sRaw);
  $p = strtoupper($pRaw);
  $fb = trim($fallback);
  $fbUpper = strtoupper($fb);

  // إذا كانت السرعة نفسها اسم بروفايل فعلي، نعتمدها كما هي.
  if ($s !== '' && (strpos($s, 'PPPOE-') === 0 || strpos($s, 'HOTSPOT') === 0 || $s === 'UNLIMITED' || $s === 'LASER-UNLIMITED')) {
    return $s;
  }

  // مهم: كلمة "مفتوح" في الباقة تعني غالباً كوتا مفتوحة، وليس سرعة مفتوحة.
  // لذلك لا نعيد قيمة فارغة لمجرد أن الباقة مفتوحة إذا كانت السرعة محددة مثل 2M أو 4M.
  $openKeys = ['UNLIMITED','OPEN','FREE','مفتوح','غير محدود'];
  if ($s !== '' && in_array($s, array_map('strtoupper', $openKeys), true)) {
    return ($fb !== '') ? $fb : 'UNLIMITED';
  }

  if (preg_match('/(\d{1,3})\s*M/i', $sRaw, $m)) {
    $n = (int)$m[1];
    if ($n > 0) return 'PPPOE-' . $n . 'M';
  }
  if (preg_match('/^(\d{1,3})$/', $sRaw, $m)) {
    $n = (int)$m[1];
    if ($n > 0) return 'PPPOE-' . $n . 'M';
  }
  if ($pRaw !== '' && preg_match('/(\d{1,3})\s*M/i', $pRaw, $m2)) {
    $n = (int)$m2[1];
    if ($n > 0) return 'PPPOE-' . $n . 'M';
  }

  if ($fb !== '') return $fb;
  return 'pppoe-profile';
}
}


if (!function_exists('ua_parent_page_url')) {
function ua_parent_page_url(string $fallback = 'dashboard.php'): string {
  $raw = trim((string)($_GET['back'] ?? $_GET['return'] ?? ''));
  if ($raw !== '') {
    $raw = preg_replace('#^(https?:)?//.*$#i', '', $raw);
    if ($raw !== '' && $raw[0] !== '/' && $raw[0] !== '\\') return $raw;
  }

  $self = basename((string)($_SERVER['PHP_SELF'] ?? ''));
  $map = [
    'subscribers_view.php' => 'subscribers.php',
    'subscribers_edit.php' => 'subscribers.php',
    'subscribers_add.php' => 'subscribers.php',
    'subscribers_history.php' => 'subscribers.php',
    'subscribers_cancel.php' => 'subscribers.php',
    'subscribers_ppp_toggle.php' => 'subscribers.php',
    'subscribers_delete.php' => 'subscribers.php',
    'subscribers_archive.php' => 'subscribers.php',
    'subscribers_restore.php' => 'subscribers_archive.php',
    'subscribers_archive_purge.php' => 'subscribers_archive.php',
    'pay_invoice.php' => 'invoices.php',
    'print_invoice.php' => 'invoices.php',
    'print_preview.php' => 'invoices.php',
    'billing_approve.php' => 'billing_alerts.php',
    'billing_message_requests.php' => 'billing_alerts.php',
    'billing_cut_requests.php' => 'billing_alerts.php',
    'billing_limit_requests.php' => 'billing_alerts.php',
    'sales_view.php' => 'sales.php',
    'sales_new.php' => 'sales.php',
    'purchases_view.php' => 'purchases_report.php',
    'purchases_new.php' => 'purchases_report.php',
  ];
  return $map[$self] ?? $fallback;
}
}


if (!function_exists('ua_current_page_url')) {
function ua_current_page_url(): string {
  $uri = (string)($_SERVER['REQUEST_URI'] ?? '');
  if ($uri !== '') {
    $u = parse_url($uri);
    $path = $u['path'] ?? $uri;
    $q = [];
    if (!empty($u['query'])) {
      parse_str($u['query'], $q);
      unset($q['minimized'], $q['_']);
    }
    $url = basename($path);
    if (count($q)) $url .= '?' . http_build_query($q);
    return $url;
  }
  $self = basename((string)($_SERVER['PHP_SELF'] ?? 'dashboard.php'));
  return $self ?: 'dashboard.php';
}
}

if (!function_exists('ua_page_title_text')) {
function ua_page_title_text(string $fallback = ''): string {
  $t = trim((string)($GLOBALS['page_title'] ?? $GLOBALS['title'] ?? ''));
  if ($t !== '') return $t;
  return $fallback !== '' ? $fallback : 'صفحة';
}
}

if (!function_exists('ua_close_button_html')) {
function ua_close_button_html(?string $href = null, string $label = 'إغلاق'): string {
  $href = $href ?: ua_parent_page_url();
  $current = ua_current_page_url();
  $title = ua_page_title_text($label);
  return '<div class="ua-close-strip ua-page-windowbar" data-ua-page-chrome="1" data-ua-page-url="'.h($current).'" data-ua-page-title="'.h($title).'">'
    .'<div class="ua-page-windowbar__title"><i class="fa fa-layer-group" aria-hidden="true"></i><span>'.h($title).'</span></div>'
    .'<div class="ua-close-float ua-window-link" title="'.h($label).'" aria-label="'.h($label).'">'
    .'<span class="ua-window-controls">'
    .'<a class="ua-window-btn ua-window-close" href="'.h($href).'" title="'.h($label).'" aria-label="'.h($label).'">×</a>'
    .'<button type="button" class="ua-window-btn ua-window-max" title="تكبير" aria-label="تكبير" data-ua-page-max="1"><span class="ua-win11-max-icon" aria-hidden="true"></span></button>'
    .'<button type="button" class="ua-window-btn ua-window-min" title="تصغير" aria-label="تصغير" data-ua-page-min="1" data-ua-page-url="'.h($current).'" data-ua-page-title="'.h($title).'" data-ua-home-url="dashboard.php"><span class="ua-win11-min-icon" aria-hidden="true"></span></button>'
    .'</span>'
    .'</div></div>';
}
}
