<?php
require_once __DIR__ . '/app_runtime.php';
require_once __DIR__ . '/app_access.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/app_assets.php';
require_once __DIR__ . '/theme_assets_lib.php';
// admin/header.php (Clean Modern Layout - NO AdminLTE)

ua_session_start();

// Dedicated presentation contract for the official Android client only.
if (!defined('UA_ANDROID_APP')) {
  $uaAndroidAgent = (string)($_SERVER['HTTP_USER_AGENT'] ?? '');
  $uaAndroidQuery = isset($_GET['ua_android']) && (string)$_GET['ua_android'] === '1';
  define('UA_ANDROID_APP', $uaAndroidQuery || stripos($uaAndroidAgent, 'NetworkCustomersAndroid/') !== false);
}

// Embed/frame mode (for modal pages and window-manager iframes).
if (!defined('UA_EMBED')) {
  define('UA_EMBED', isset($_GET['embed']) && $_GET['embed'] == '1');
}
if (!defined('UA_FRAME_CONTEXT')) {
  define('UA_FRAME_CONTEXT', UA_EMBED || isset($_GET['iframe']) || isset($_GET['ua_tab']) || isset($_GET['ua_modal']));
}

ua_enforce_install_access();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/auth.php';

require_once __DIR__ . '/db_bootstrap.php';
ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;

// UI settings (themes, density, etc.)
require_once __DIR__ . '/ui_settings.php';
require_once __DIR__ . '/ui_design_system.php';
if ($conn instanceof mysqli) {
  ua_ensure_settings_table($conn);
}

// Public pages that may render without login
$cur = basename($_SERVER['PHP_SELF'] ?? '');
$UA_PAGE_CSS = array_values(array_unique(array_merge(
  isset($UA_PAGE_CSS) && is_array($UA_PAGE_CSS) ? $UA_PAGE_CSS : [],
  function_exists('ua_page_component_css') ? ua_page_component_css($cur) : []
)));
$PUBLIC = ['index.php','login.php','logout.php','setup_first_admin.php','install_link.php'];
if (!in_array($cur, $PUBLIC, true) && empty($GLOBALS['UA_AGENT_EDIT_CONTEXT'])) {
  require_login('index.php?login=1');
}

$logged = !empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']);

// Unified shell rules
// - Dashboard keeps its own tested layout.
// - Normal pages get sidebar + stats topbar + page windowbar + custom side scrollbar.
// - Popup/embed pages do not get sidebar/topbar/windowbar.
$ua_print_pages = ['print_invoice.php','print_preview.php','vouchers_print.php','settings_print.php'];
$ua_popup_by_query = UA_FRAME_CONTEXT || isset($_GET['popup']) || isset($_GET['modal']);
$ua_popup_by_global = !empty($GLOBALS['UA_POPUP']) || (defined('UA_POPUP') && UA_POPUP);
$ua_is_popup = (UA_EMBED || $ua_popup_by_query || $ua_popup_by_global || in_array($cur, $ua_print_pages, true));
$ua_subscriber_modal_pages = [
  'subscribers_view.php',
  'subscribers_edit.php',
  'subscribers_add.php',
  'subscribers_history.php',
  'subscribers_distribution.php',
  'subscribers_archive.php',
  'subscribers_import_excel.php',
  'subscribers_history_clear.php',
  'subscribers_cancel.php',
  'subscriber_router_setup.php',
  'android_router_setup.php',
  'sync_mikrotik.php',
  'mikrotik_import.php',
  'import_ppp_from_mikrotik.php',
  'finance_payments.php',
];
$ua_subscriber_modal_embed = !empty($_GET['ua_sub_modal'])
  || !empty($_GET['ua_subscriber_modal'])
  || !empty($_GET['subscriber_modal'])
  || (!empty($_GET['ua_modal']) && in_array($cur, $ua_subscriber_modal_pages, true))
  || (UA_FRAME_CONTEXT && in_array($cur, $ua_subscriber_modal_pages, true));

if (!defined('UA_SHELL_CHROME')) {
  define('UA_SHELL_CHROME', (bool)($logged && !$ua_is_popup));
}
$UA_IS_DASHBOARD = ($cur === 'dashboard.php');
$UA_RENDER_GLOBAL_SHELL = (UA_SHELL_CHROME && $logged && !$UA_IS_DASHBOARD && !UA_ANDROID_APP);
$ua_link_approval_prompt_enabled = $logged
  && UA_SHELL_CHROME
  && function_exists('ua_is_server_install')
  && ua_is_server_install()
  && (!function_exists('has_perm') || has_perm('can_manage_settings'));


// Company name (company display first; APP_NAME is only a fallback, not the visible company chip)
$companyName = '';
if ($conn instanceof mysqli) {
  try {
    if (function_exists('table_exists') && table_exists($conn, 'company_info')) {
      $r = $conn->query("SELECT company_name FROM company_info WHERE id=1 LIMIT 1");
      if ($r && $r->num_rows) $companyName = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      if ($companyName === '') {
        $r = $conn->query("SELECT company_name FROM company_info WHERE COALESCE(company_name,'')<>'' LIMIT 1");
        if ($r && $r->num_rows) $companyName = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      }
    }
    if ($companyName === '' && function_exists('table_exists') && table_exists($conn, 'system_settings')) {
      if (function_exists('col_exists') && col_exists($conn, 'system_settings', 'company_name')) {
        $r = $conn->query("SELECT company_name FROM system_settings WHERE id=1 LIMIT 1");
        if ($r && $r->num_rows) $companyName = trim((string)($r->fetch_assoc()['company_name'] ?? ''));
      }
      if ($companyName === '') {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='company_name' LIMIT 1");
        if ($r && $r->num_rows) $companyName = trim((string)($r->fetch_assoc()['setting_value'] ?? ''));
      }
    }
  } catch (Throwable $e) {}
}
if ($companyName === '') $companyName = 'اسم الشركة';

$adminDisplay = $_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'المدير');

$adminAvatar = '';
$uaAvatarRel = trim((string)($_SESSION['admin_avatar'] ?? ''));
$uaAvatarRel = str_replace(['\\', "\0"], ['/', ''], $uaAvatarRel);
$uaAvatarRel = ltrim($uaAvatarRel, '/');
if ($uaAvatarRel !== '' && strpos($uaAvatarRel, '..') === false && preg_match('~^uploads/admin_users/[a-zA-Z0-9_\-\.]+$~', $uaAvatarRel) && is_file(__DIR__ . '/' . $uaAvatarRel)) {
  $adminAvatar = $uaAvatarRel;
}
if ($adminAvatar === '' && ($conn instanceof mysqli)) {
  try {
    $uaAdminId = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
    if ($uaAdminId > 0 && function_exists('col_exists') && col_exists($conn, 'admin_users', 'avatar_path')) {
      $r = $conn->query("SELECT avatar_path FROM admin_users WHERE id=$uaAdminId LIMIT 1");
      if ($r && $r->num_rows) {
        $rel = trim((string)($r->fetch_assoc()['avatar_path'] ?? ''));
        $rel = str_replace(['\\', "\0"], ['/', ''], $rel);
        $rel = ltrim($rel, '/');
        if ($rel !== '' && strpos($rel, '..') === false && preg_match('~^uploads/admin_users/[a-zA-Z0-9_\-\.]+$~', $rel) && is_file(__DIR__ . '/' . $rel)) {
          $adminAvatar = $rel;
          $_SESSION['admin_avatar'] = $rel;
        }
      }
    }
  } catch (Throwable $e) {}
}

// ----- UI theme settings (stored in app_settings) -----
$ua_setting_defaults = function_exists('ua_design_setting_defaults') ? ua_design_setting_defaults() : [
  'ui_design_mode' => 'v2',
  'ui_theme' => 'armoury_dark',
  'ui_accent' => '',
  'ui_density' => 'comfy',
  'ui_radius' => '16',
  'ui_sidebar' => 'hover',
  'ui_font_family' => 'system',
  'ui_font_size' => '15',
  'ui_font_weight' => '700',
  'ui_text_color' => '',
  'ui_border_color' => '',
  'ui_border_style' => 'solid',
  'ui_border_width' => '1',
  'ui_card_style' => 'soft',
  'ui_page_max_width' => 'none',
  'ui_control_height' => '40',
  'ui_table_row_height' => '46',
  'ui_surface_alpha' => '82',
  'ui_menu_alpha' => '76',
  'ui_spacing_scale' => 'normal',
  'ui_body_bg' => '#07111f',
  'ui_surface_color' => '#071827',
  'ui_surface_alt_color' => '#0a2431',
  'ui_topbar_color' => '#071a28',
  'ui_windowbar_color' => '#071624',
  'ui_sidebar_color' => '#063238',
  'ui_sidebar_item_color' => '#0b4a4d',
  'ui_input_color' => '#061d2a',
  'ui_input_text_color' => '#eaf0ff',
  'ui_table_head_color' => '#08373e',
  'ui_table_row_color' => '#062532',
  'ui_table_row_alt_color' => '#082e3a',
  'ui_menu_color' => '#061923',
  'ui_modal_color' => '#071827',
  'ui_alert_color' => '#102b3f',
  'ui_security_alert_color' => '#44151d',
  'ui_title_font_size' => '22',
  'ui_bar_font_size' => '12',
  'ui_input_font_size' => '13',
  'ui_table_font_size' => '13',
  'ui_menu_font_size' => '13',
  'ui_modal_font_size' => '14',
];
$ua_settings = [];
if ($conn instanceof mysqli && function_exists('ua_get_ui_settings_map')) {
  $ua_settings = ua_get_ui_settings_map($conn, array_keys($ua_setting_defaults), 120);
}
$ua_device_disconnect_alert_enabled = true;
if ($conn instanceof mysqli && function_exists('ua_get_setting')) {
  $ua_device_disconnect_alert_enabled = (string)ua_get_setting($conn, 'noc_device_disconnect_alert_enabled', '1') !== '0';
}
$ua_setting = static function(string $key) use ($ua_settings, $ua_setting_defaults): string {
  $value = $ua_settings[$key] ?? ($ua_setting_defaults[$key] ?? '');
  return is_scalar($value) ? (string)$value : (string)($ua_setting_defaults[$key] ?? '');
};

$ua_design_mode  = $ua_setting('ui_design_mode');
$ua_theme        = $ua_setting('ui_theme');
$ua_accent       = $ua_setting('ui_accent');
$ua_density      = $ua_setting('ui_density'); // comfy|compact
$ua_radius       = $ua_setting('ui_radius');
$ua_sidebar      = $ua_setting('ui_sidebar'); // hover|pinned|compact
$ua_font_family  = $ua_setting('ui_font_family');
$ua_font_size    = $ua_setting('ui_font_size');
$ua_font_weight  = $ua_setting('ui_font_weight');
$ua_text_color   = $ua_setting('ui_text_color');
$ua_border_color = $ua_setting('ui_border_color');
$ua_border_style = $ua_setting('ui_border_style');
$ua_border_width = $ua_setting('ui_border_width');
$ua_card_style   = $ua_setting('ui_card_style');
$ua_page_max_width = $ua_setting('ui_page_max_width');
$ua_control_height = $ua_setting('ui_control_height');
$ua_table_row_height = $ua_setting('ui_table_row_height');
$ua_surface_alpha = $ua_setting('ui_surface_alpha');
$ua_menu_alpha = $ua_setting('ui_menu_alpha');
$ua_spacing_scale = $ua_setting('ui_spacing_scale');
$ua_body_bg = $ua_setting('ui_body_bg');
$ua_surface_color = $ua_setting('ui_surface_color');
$ua_surface_alt_color = $ua_setting('ui_surface_alt_color');
$ua_topbar_color = $ua_setting('ui_topbar_color');
$ua_windowbar_color = $ua_setting('ui_windowbar_color');
$ua_sidebar_color = $ua_setting('ui_sidebar_color');
$ua_sidebar_item_color = $ua_setting('ui_sidebar_item_color');
$ua_input_color = $ua_setting('ui_input_color');
$ua_input_text_color = $ua_setting('ui_input_text_color');
$ua_table_head_color = $ua_setting('ui_table_head_color');
$ua_table_row_color = $ua_setting('ui_table_row_color');
$ua_table_row_alt_color = $ua_setting('ui_table_row_alt_color');
$ua_menu_color = $ua_setting('ui_menu_color');
$ua_modal_color = $ua_setting('ui_modal_color');
$ua_alert_color = $ua_setting('ui_alert_color');
$ua_security_alert_color = $ua_setting('ui_security_alert_color');
$ua_title_font_size = $ua_setting('ui_title_font_size');
$ua_bar_font_size = $ua_setting('ui_bar_font_size');
$ua_input_font_size = $ua_setting('ui_input_font_size');
$ua_table_font_size = $ua_setting('ui_table_font_size');
$ua_menu_font_size = $ua_setting('ui_menu_font_size');
$ua_modal_font_size = $ua_setting('ui_modal_font_size');

// Sanitize
$ua_design_mode = in_array($ua_design_mode, ['legacy','v2'], true) ? $ua_design_mode : 'v2';
$ua_density = in_array($ua_density, ['comfy','compact'], true) ? $ua_density : 'comfy';
$ua_sidebar = in_array($ua_sidebar, ['hover','pinned','compact'], true) ? $ua_sidebar : 'hover';
$ua_font_family = in_array($ua_font_family, ['system','cairo','tajawal','noto_kufi','ibm_plex_arabic','almarai','tahoma','segoe','arial'], true) ? $ua_font_family : 'system';
$ua_font_weight = in_array($ua_font_weight, ['500','600','700','800'], true) ? $ua_font_weight : '700';
$ua_border_style = in_array($ua_border_style, ['solid','dashed','double'], true) ? $ua_border_style : 'solid';
$ua_card_style = in_array($ua_card_style, ['soft','flat','strong'], true) ? $ua_card_style : 'soft';
$ua_radius_i = (int)$ua_radius;
if ($ua_radius_i < 10 || $ua_radius_i > 26) $ua_radius_i = 16;
$ua_font_size_i = (int)$ua_font_size;
if ($ua_font_size_i < 12 || $ua_font_size_i > 20) $ua_font_size_i = 15;
$ua_border_width_i = (int)$ua_border_width;
if ($ua_border_width_i < 1 || $ua_border_width_i > 3) $ua_border_width_i = 1;
$ua_control_height_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_control_height, 32, 54, 40) : (int)$ua_control_height;
$ua_table_row_height_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_table_row_height, 36, 64, 46) : (int)$ua_table_row_height;
$ua_surface_alpha_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_surface_alpha, 30, 96, 82) : (int)$ua_surface_alpha;
$ua_menu_alpha_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_menu_alpha, 30, 96, 76) : (int)$ua_menu_alpha;
$ua_spacing_scale = in_array($ua_spacing_scale, ['tight','normal','roomy'], true) ? $ua_spacing_scale : 'normal';
$ua_page_max_width = in_array($ua_page_max_width, ['none','1280','1440','1600'], true) ? $ua_page_max_width : 'none';
$ua_page_max_width_css = $ua_page_max_width === 'none' ? 'none' : ($ua_page_max_width . 'px');

$ua_hex_setting = static function($value, string $fallback): string {
  $value = trim((string)$value);
  if ($value === '') return $fallback;
  if ($value[0] !== '#') $value = '#' . $value;
  return preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value) ? $value : $fallback;
};
$ua_body_bg = $ua_hex_setting($ua_body_bg, '#07111f');
$ua_surface_color = $ua_hex_setting($ua_surface_color, '#071827');
$ua_surface_alt_color = $ua_hex_setting($ua_surface_alt_color, '#0a2431');
$ua_topbar_color = $ua_hex_setting($ua_topbar_color, '#071a28');
$ua_windowbar_color = $ua_hex_setting($ua_windowbar_color, '#071624');
$ua_sidebar_color = $ua_hex_setting($ua_sidebar_color, '#063238');
$ua_sidebar_item_color = $ua_hex_setting($ua_sidebar_item_color, '#0b4a4d');
$ua_input_color = $ua_hex_setting($ua_input_color, '#061d2a');
$ua_input_text_color = $ua_hex_setting($ua_input_text_color, '#eaf0ff');
$ua_table_head_color = $ua_hex_setting($ua_table_head_color, '#08373e');
$ua_table_row_color = $ua_hex_setting($ua_table_row_color, '#062532');
$ua_table_row_alt_color = $ua_hex_setting($ua_table_row_alt_color, '#082e3a');
$ua_menu_color = $ua_hex_setting($ua_menu_color, '#061923');
$ua_modal_color = $ua_hex_setting($ua_modal_color, '#071827');
$ua_alert_color = $ua_hex_setting($ua_alert_color, '#102b3f');
$ua_security_alert_color = $ua_hex_setting($ua_security_alert_color, '#44151d');
$ua_title_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_title_font_size, 16, 34, 22) : 22;
$ua_bar_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_bar_font_size, 10, 18, 12) : 12;
$ua_input_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_input_font_size, 11, 18, 13) : 13;
$ua_table_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_table_font_size, 10, 18, 13) : 13;
$ua_menu_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_menu_font_size, 10, 18, 13) : 13;
$ua_modal_font_size_i = function_exists('ua_design_int_range') ? ua_design_int_range($ua_modal_font_size, 12, 20, 14) : 14;
$ua_force_design_v2 = !empty($GLOBALS['UA_FORCE_DESIGN_V2']) || !empty($UA_FORCE_DESIGN_V2);
$ua_effective_design_mode = $logged ? 'v2' : ($ua_force_design_v2 ? 'v2' : $ua_design_mode);

$ua_font_family_css_map = [
  'system' => 'system-ui, -apple-system, "Segoe UI", Tahoma, Arial, sans-serif',
  'cairo' => '"Cairo", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
  'tajawal' => '"Tajawal", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
  'noto_kufi' => '"Noto Kufi Arabic", "Noto Sans Arabic", Tahoma, Arial, sans-serif',
  'ibm_plex_arabic' => '"IBM Plex Sans Arabic", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
  'almarai' => '"Almarai", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
  'tahoma' => 'Tahoma, Arial, sans-serif',
  'segoe'  => '"Segoe UI", Tahoma, Arial, sans-serif',
  'arial'  => 'Arial, Tahoma, sans-serif',
];
$ua_font_family_css = $ua_font_family_css_map[$ua_font_family] ?? $ua_font_family_css_map['system'];

$ua_css_value = static function(string $value): string {
  return str_replace(['</', '<!--'], ['<\/', '<\!--'], $value);
};

// Accent pair
[$ua_accent_1, $ua_accent_2] = ua_accent_pair($ua_accent);
$ua_text_color = preg_match('/^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', trim($ua_text_color)) ? (trim($ua_text_color)[0] === '#' ? trim($ua_text_color) : '#'.trim($ua_text_color)) : '';
$ua_border_color = preg_match('/^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', trim($ua_border_color)) ? (trim($ua_border_color)[0] === '#' ? trim($ua_border_color) : '#'.trim($ua_border_color)) : '';
if ($ua_text_color === '') $ua_text_color = '#eaf0ff';
if ($ua_border_color === '') $ua_border_color = 'rgba(255,255,255,.10)';

// Theme CSS (optional) - resolved from the central theme registry.
$ua_theme_css = function_exists('ua_theme_css_path') ? ua_theme_css_path((string)$ua_theme) : '';

// Topbar statuses disabled (hidden by request)
$ua_statuses = [];

// Language
$uiLang = function_exists('current_lang') ? current_lang() : 'ar';
$htmlLang = ($uiLang === 'en') ? 'en' : 'ar';
$htmlDir  = 'rtl'; // Keep the NOC shell geometry fixed; language changes text only.

// Helper to render mega-menu dropdown pill
if (!function_exists('ua_pill_dd_clean')) {
  function ua_pill_dd_clean(string $id, string $label, string $icon, array $items): void {
    $safeId = preg_replace('/[^a-zA-Z0-9_\-]/','', $id);
    echo '<div class="ua-dd" data-dd="'.$safeId.'">';
    echo '  <button type="button" class="ua-pill" aria-haspopup="true" aria-expanded="false">';
    echo '    <span class="ua-ico"><i class="fa '.$icon.'"></i></span>';
    echo '    <span class="ua-txt">'.h($label).'</span>';
    echo '    <span class="ua-caret">▾</span>';
    echo '  </button>';
    echo '  <div class="ua-menu" role="menu">';
    foreach ($items as $it) {
      $href = $it['href'] ?? '#';
      $text = $it['text'] ?? '';
      $ic   = $it['icon'] ?? 'fa-circle-o';
      echo '    <a class="ua-item" role="menuitem" href="'.h($href).'"><i class="fa '.$ic.'"></i><span>'.h($text).'</span></a>';
    }
    echo '  </div>';
    echo '</div>';
  }
}
?><!doctype html>
<html lang="<?= $htmlLang ?>" dir="<?= $htmlDir ?>" class="<?= UA_ANDROID_APP ? 'ua-android-app ' : '' ?><?= UA_FRAME_CONTEXT ? 'ua-in-frame' : '' ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script>
    (function(){
      try {
        if (window.self !== window.top) {
          document.documentElement.classList.add('ua-in-frame');
        }
      } catch (e) {
        document.documentElement.classList.add('ua-in-frame');
      }
    })();
  </script>
  <?php if (($cur ?? '') === 'dashboard.php'): ?>
  <script>
    (function(){
      try {
        var nav = performance.getEntriesByType && performance.getEntriesByType('navigation');
        var isReload = !!(nav && nav[0] && nav[0].type === 'reload');
        if (!isReload && performance.navigation) isReload = performance.navigation.type === 1;
        var target = (sessionStorage.getItem('ua_window_last_shell_url_v1') || localStorage.getItem('ua_window_last_shell_url_v1') || '').replace(/^\.\//,'').split('?')[0].split('#')[0];
        if (isReload && target && target !== 'dashboard.php') {
          document.documentElement.classList.add('ua-restore-workspace-pending');
          setTimeout(function(){ document.documentElement.classList.remove('ua-restore-workspace-pending'); }, 6000);
        }
      } catch(e) {}
    })();
  </script>
  <?php endif; ?>
  <?php $uaHeadTitle = function_exists('t') ? t((string)($page_title ?? $companyName)) : (string)($page_title ?? $companyName); ?>
  <title><?= h($uaHeadTitle) ?></title>
  <style id="ua-theme-prepaint">
    :root{
      --ua-accent: <?= h($ua_accent_1) ?>;
      --ua-accent-2: <?= h($ua_accent_2) ?>;
      --ua-text: <?= h($ua_text_color) ?>;
      --ua-border: <?= h($ua_border_color) ?>;
      --ua-border-strong: <?= h($ua_border_color) ?>;
      --ua-theme-page-bg: <?= h($ua_body_bg) ?>;
      --ua-theme-surface: <?= h($ua_surface_color) ?>;
      --ua-theme-surface-2: <?= h($ua_surface_alt_color) ?>;
      --ua-theme-topbar: <?= h($ua_topbar_color) ?>;
      --ua-theme-windowbar: <?= h($ua_windowbar_color) ?>;
      --ua-theme-sidebar: <?= h($ua_sidebar_color) ?>;
      --ua-theme-sidebar-item: <?= h($ua_sidebar_item_color) ?>;
      --ua-theme-input: <?= h($ua_input_color) ?>;
      --ua-theme-input-text: <?= h($ua_input_text_color) ?>;
      --ua-theme-table-head: <?= h($ua_table_head_color) ?>;
      --ua-theme-table-row: <?= h($ua_table_row_color) ?>;
      --ua-theme-table-row-alt: <?= h($ua_table_row_alt_color) ?>;
      --ua-theme-menu: <?= h($ua_menu_color) ?>;
      --ua-theme-modal: <?= h($ua_modal_color) ?>;
      --ua-theme-alert: <?= h($ua_alert_color) ?>;
      --ua-theme-security-alert: <?= h($ua_security_alert_color) ?>;
      --ua-bg: <?= h($ua_body_bg) ?>;
      --ua-card: color-mix(in srgb,<?= h($ua_surface_color) ?> 82%, transparent);
      --ua-ds-text:var(--ua-text);
      --ua-ds-title:color-mix(in srgb,var(--ua-text) 92%,white 8%);
      --ua-ds-muted:color-mix(in srgb,var(--ua-text) 64%,transparent);
      --ua-ds-line:var(--ua-border);
      --ua-ds-line-strong:var(--ua-border-strong);
      --ua-ds-input:color-mix(in srgb,var(--ua-theme-input) 82%,transparent);
      --sb3-bg1:color-mix(in srgb,var(--ua-theme-sidebar) 96%,white 4%);
      --sb3-bg2:color-mix(in srgb,var(--ua-theme-sidebar) 88%,black 12%);
      --sb3-panel:color-mix(in srgb,var(--ua-theme-sidebar-item) 76%,transparent);
      --sb3-border:var(--ua-ds-line);
      --sb3-text:var(--ua-ds-title);
      --sb3-text-soft:var(--ua-ds-muted);
      --sb3-accent:var(--ua-accent);
      --sb3-cyan:var(--ua-accent-2);
    }
    html{
      background:
        radial-gradient(920px 560px at 86% 4%,color-mix(in srgb,var(--ua-accent) 13%,transparent),transparent 62%),
        radial-gradient(760px 480px at 14% 8%,color-mix(in srgb,var(--ua-accent-2) 9%,transparent),transparent 58%),
        linear-gradient(180deg,var(--ua-theme-page-bg),color-mix(in srgb,var(--ua-theme-page-bg) 78%,black 22%));
      color:var(--ua-ds-text);
    }
  </style>
  <?= ua_asset_tag_css('bootstrap_533_rtl_css') ?>
  <?= ua_asset_tag_css('fontawesome_470_css') ?>
  <?= function_exists('ua_local_css_tags') ? ua_local_css_tags('shell') : '' ?>
  <script defer src="<?= h(ua_asset_versioned_local('assets/js/ua_number_wheel.js')) ?>"></script>
  <?php if ($logged): ?>
    <script defer src="<?= h(ua_asset_versioned_local('assets/js/ua_device_disconnect_alert.js')) ?>"></script>
  <?php endif; ?>
  <?php if ($ua_link_approval_prompt_enabled): ?>
    <script defer src="<?= h(ua_asset_versioned_local('assets/js/ua_link_approval_prompt.js')) ?>"></script>
  <?php endif; ?>
  <?php /* Lean UI: old NOC/sidebar skin disabled to avoid stacked legacy frames. */ ?>

  <?php if (!empty($ua_theme_css)): ?>
    <?php $ua_v_theme = @filemtime(__DIR__ . '/' . $ua_theme_css) ?: 1; ?>
    <link id="ua-theme-css" rel="stylesheet" href="<?= h($ua_theme_css) ?>?v=<?= (int)$ua_v_theme ?>">
  <?php else: ?>
    <link id="ua-theme-css" rel="stylesheet" disabled>
  <?php endif; ?>

  <?php /* Lean UI: old fresh shell and global glass layers disabled; page/current styles are now the source of truth. */ ?>
  <?php /* page-by-page rebuild mode: old automatic page refactor stylesheet intentionally not loaded */ ?>

  <?php
    // Optional: hide in-page crumbs/titles for special pages
    $UA_HIDE_CHROME = (!empty($GLOBALS['UA_HIDE_CHROME']) || (!empty($UA_HIDE_CHROME)));
  ?>
  <style>

    /* Runtime UI variables (DB) */
    :root{
      --ua-accent: <?= h($ua_accent_1) ?>;
      --ua-accent-2: <?= h($ua_accent_2) ?>;
      --ua-radius: <?= (int)$ua_radius_i ?>px;
      --ua-font-family: <?= $ua_css_value($ua_font_family_css) ?>;
      --ua-template-font-family: <?= $ua_css_value($ua_font_family_css) ?>;
      --ua-font-size: <?= (int)$ua_font_size_i ?>px;
      --ua-template-font-size: <?= (int)$ua_font_size_i ?>px;
      --ua-font-weight: <?= h($ua_font_weight) ?>;
      --ua-template-font-weight: <?= h($ua_font_weight) ?>;
      --ua-text: <?= h($ua_text_color) ?>;
      --ua-template-text: <?= h($ua_text_color) ?>;
      --ua-border: <?= h($ua_border_color) ?>;
      --ua-border-strong: <?= h($ua_border_color) ?>;
      --ua-template-border: <?= h($ua_border_color) ?>;
      --ua-template-border-strong: <?= h($ua_border_color) ?>;
      --ua-border-style: <?= h($ua_border_style) ?>;
      --ua-border-width: <?= (int)$ua_border_width_i ?>px;
      --ua-card-shadow: <?= $ua_card_style === 'flat' ? 'none' : ($ua_card_style === 'strong' ? '0 20px 50px rgba(0,0,0,.35)' : 'var(--ua-shadow-soft)') ?>;
      --ua-ds-page-max-width: <?= h($ua_page_max_width_css) ?>;
      --ua-ds-control-h: <?= (int)$ua_control_height_i ?>px;
      --ua-ds-table-row-h: <?= (int)$ua_table_row_height_i ?>px;
      --ua-ds-surface: color-mix(in srgb,var(--ua-theme-surface) <?= (int)$ua_surface_alpha_i ?>%,transparent);
      --ua-ds-surface-2: color-mix(in srgb,var(--ua-theme-surface-2) <?= (int)max(30, $ua_surface_alpha_i - 8) ?>%,transparent);
      --ua-ds-menu: color-mix(in srgb,var(--ua-theme-menu) <?= (int)$ua_menu_alpha_i ?>%,transparent);
      --ua-theme-page-bg: <?= h($ua_body_bg) ?>;
      --ua-theme-surface: <?= h($ua_surface_color) ?>;
      --ua-theme-surface-2: <?= h($ua_surface_alt_color) ?>;
      --ua-theme-topbar: <?= h($ua_topbar_color) ?>;
      --ua-theme-windowbar: <?= h($ua_windowbar_color) ?>;
      --ua-theme-sidebar: <?= h($ua_sidebar_color) ?>;
      --ua-theme-sidebar-item: <?= h($ua_sidebar_item_color) ?>;
      --ua-theme-input: <?= h($ua_input_color) ?>;
      --ua-theme-input-text: <?= h($ua_input_text_color) ?>;
      --ua-theme-table-head: <?= h($ua_table_head_color) ?>;
      --ua-theme-table-row: <?= h($ua_table_row_color) ?>;
      --ua-theme-table-row-alt: <?= h($ua_table_row_alt_color) ?>;
      --ua-theme-menu: <?= h($ua_menu_color) ?>;
      --ua-theme-modal: <?= h($ua_modal_color) ?>;
      --ua-theme-alert: <?= h($ua_alert_color) ?>;
      --ua-theme-security-alert: <?= h($ua_security_alert_color) ?>;
      --ua-title-font-size: <?= (int)$ua_title_font_size_i ?>px;
      --ua-bar-font-size: <?= (int)$ua_bar_font_size_i ?>px;
      --ua-input-font-size: <?= (int)$ua_input_font_size_i ?>px;
      --ua-table-font-size: <?= (int)$ua_table_font_size_i ?>px;
      --ua-menu-font-size: <?= (int)$ua_menu_font_size_i ?>px;
      --ua-modal-font-size: <?= (int)$ua_modal_font_size_i ?>px;
      --ua-bg: <?= h($ua_body_bg) ?>;
      --ua-card: color-mix(in srgb,<?= h($ua_surface_color) ?> 82%, transparent);
      --ua-text-soft: color-mix(in srgb,var(--ua-text) 70%, transparent);
      --sb3-bg1: color-mix(in srgb,<?= h($ua_sidebar_color) ?> 96%, white 4%);
      --sb3-bg2: color-mix(in srgb,<?= h($ua_sidebar_color) ?> 88%, black 12%);
      --sb3-panel: color-mix(in srgb,<?= h($ua_sidebar_item_color) ?> 76%, transparent);
      --sb3-accent: var(--ua-accent);
      --sb3-cyan: var(--ua-accent-2);
    }
  </style>

  <?php /* Structural/page styles load first. The theme contract below is the final desktop authority. */ ?>
  <?php $ua_v_extracted_pages_css = @filemtime(__DIR__ . '/assets/css/ua_extracted_pages.css') ?: 1; ?>
  <link rel="stylesheet" href="assets/css/ua_extracted_pages.css?v=<?= (int)$ua_v_extracted_pages_css ?>">
  <?php if (!empty($UA_PAGE_CSS) && is_array($UA_PAGE_CSS)): ?>
    <?php foreach ($UA_PAGE_CSS as $uaPageCss): ?>
      <?php $uaPageCss = is_scalar($uaPageCss) ? ltrim((string)$uaPageCss, '/') : ''; ?>
      <?php if ($uaPageCss !== '' && strpos($uaPageCss, '..') === false && is_file(__DIR__ . '/' . $uaPageCss)): ?>
        <link rel="stylesheet" href="<?= h(ua_asset_versioned_local($uaPageCss)) ?>">
      <?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
  <?php if ($logged): ?>
    <link rel="stylesheet" href="<?= h(ua_asset_versioned_local('assets/css/ua_device_disconnect_alert.css')) ?>">
    <link rel="stylesheet" href="<?= h(ua_asset_versioned_local('assets/css/subscriber_id_scanner.css')) ?>">
  <?php endif; ?>
  <?php if ($ua_link_approval_prompt_enabled): ?>
    <link rel="stylesheet" href="<?= h(ua_asset_versioned_local('assets/css/ua_link_approval_prompt.css')) ?>">
  <?php endif; ?>
  <?php if ($cur === 'index.php'): ?>
    <?= function_exists('ua_local_css_tags') ? ua_local_css_tags('login') : '' ?>
  <?php endif; ?>
  <?php if ($logged && UA_SHELL_CHROME): ?>
    <link rel="stylesheet" href="<?= h(ua_asset_versioned_local('assets/css/ua_live_stats_bar.css')) ?>">
  <?php endif; ?>
  <?php /* One canonical theme authority: page CSS may define layout, but cannot restore an old palette. */ ?>
  <?php $ua_v_program_unified_css = @filemtime(__DIR__ . '/assets/css/ua_program_unified.css') ?: 1; ?>
  <link rel="stylesheet" href="assets/css/ua_program_unified.css?v=<?= (int)$ua_v_program_unified_css ?>">
  <?php $ua_v_footer_guards_css = @filemtime(__DIR__ . '/assets/css/ua_footer_guards.css') ?: 1; ?>
  <link rel="stylesheet" href="assets/css/ua_footer_guards.css?v=<?= (int)$ua_v_footer_guards_css ?>">
  <?php if (UA_ANDROID_APP): ?>
    <?php /* Platform layout intentionally follows the desktop theme contract. */ ?>
    <?php $ua_v_android_app_css = @filemtime(__DIR__ . '/assets/css/ua_android_app.css') ?: 1; ?>
    <link rel="stylesheet" href="assets/css/ua_android_app.css?v=<?= (int)$ua_v_android_app_css ?>">
  <?php endif; ?>
</head>

<?php
  $ua_page_slug = preg_replace('/[^a-z0-9]+/', '-', strtolower(pathinfo($cur, PATHINFO_FILENAME)));
  $ua_section_slug = '';
  if (UA_SHELL_CHROME && $logged && !$UA_IS_DASHBOARD) {
    try {
      if (!function_exists('ua_section_map')) require_once __DIR__ . '/section_map.php';
      $uaSectionMap = function_exists('ua_section_map') ? ua_section_map() : [];
      $uaSectionRaw = (string)($uaSectionMap['page_to_section'][$cur] ?? '');
      $ua_section_slug = preg_replace('/[^a-z0-9_\-]+/i', '-', strtolower($uaSectionRaw));
    } catch (Throwable $e) {
      $ua_section_slug = '';
    }
  }
?>
<body data-ua-shell-contract="locked" data-ua-shell-context="<?= UA_FRAME_CONTEXT ? 'frame' : (UA_SHELL_CHROME ? 'chrome' : 'plain') ?>" data-ua-page="<?= h($cur) ?>" data-ua-device-disconnect-alert="<?= $ua_device_disconnect_alert_enabled ? '1' : '0' ?>" data-ua-link-approval-prompt="<?= $ua_link_approval_prompt_enabled ? '1' : '0' ?>" class="<?= $logged ? 'ua-authed' : 'ua-guest' ?> <?= UA_SHELL_CHROME ? 'ua-shell-chrome' : 'ua-shell-plain' ?> <?= $UA_IS_DASHBOARD ? 'ua-page-dashboard' : '' ?> <?= UA_FRAME_CONTEXT ? 'ua-frame-context ua-tab-iframe-body' : '' ?> <?= $ua_section_slug !== '' ? 'ua-sec-'.h($ua_section_slug) : '' ?> <?= !empty($ua_subscriber_modal_embed) ? 'ua-subscriber-modal-embed' : '' ?> <?= !empty($UA_HIDE_CHROME) ? 'ua-hide-chrome' : '' ?> ua-p-<?= h($ua_page_slug ?: 'page') ?> ua-theme-<?= h(preg_replace('/[^a-z0-9_-]+/i', '-', (string)$ua_theme)) ?> ua-lang-<?= h($htmlLang) ?> ua-density-<?= h($ua_density) ?> ua-sb-<?= h($ua_sidebar) ?> ua-card-<?= h($ua_card_style) ?> <?= function_exists('ua_design_mode_class') ? h(ua_design_mode_class($ua_effective_design_mode)) : ($ua_effective_design_mode === 'v2' ? 'ua-design-v2' : 'ua-design-legacy') ?> <?= $ua_force_design_v2 ? 'ua-design-forced-v2' : '' ?> ua-spacing-<?= h($ua_spacing_scale) ?>">
<div class="ua-shell <?= UA_FRAME_CONTEXT ? 'ua-embed' : '' ?>" id="uaShellRoot" data-ua-shell-region="root">

<?php if (UA_SHELL_CHROME && $logged): ?>
  <div class="ua-sb-backdrop" aria-hidden="true"></div>
  <button type="button" class="ua-mobile-menu-button" data-ua-mobile-menu
          aria-controls="uaSb3" aria-label="فتح قائمة البرنامج">
    <i class="fa fa-bars" aria-hidden="true"></i>
    <span>القائمة</span>
  </button>
<?php endif; ?>

<?php
  if (UA_SHELL_CHROME && $logged && (!$UA_IS_DASHBOARD || UA_ANDROID_APP)) {
    require_once __DIR__ . '/sidebar.php';
  }
  $uaPageTitle = trim((string)($page_title ?? $companyName ?? ''));
  if ($uaPageTitle === '') $uaPageTitle = 'لوحة التحكم';
  $uaAdminInitial = function_exists('mb_substr') ? mb_substr((string)$adminDisplay, 0, 1, 'UTF-8') : substr((string)$adminDisplay, 0, 1);
  if ($uaAdminInitial === '') $uaAdminInitial = 'A';
?>
<?php if ($UA_RENDER_GLOBAL_SHELL): ?>
  <?php
    $ua_live_stats_context = 'shell';
    $ua_live_stats_company = $companyName;
    $ua_live_stats_user_name = $adminDisplay;
    $ua_live_stats_user_avatar = $adminAvatar;
    $ua_live_stats_user_initial = $uaAdminInitial;
    $ua_live_stats_show_counts = true;
    $ua_live_stats_show_alerts = true;
    require __DIR__ . '/partials/live_stats_bar.php';
    unset($ua_live_stats_context, $ua_live_stats_company, $ua_live_stats_user_name, $ua_live_stats_user_avatar, $ua_live_stats_user_initial, $ua_live_stats_show_counts, $ua_live_stats_show_alerts);
  ?>
  <div class="ua-unified-shell-block ua-shell-gold-line" id="uaShellGoldLine" data-ua-shell-region="gold-line" aria-hidden="true"></div>
  <header class="ua-unified-shell-block ua-page-windowbar" id="uaShellWindowBar" data-ua-shell-region="windowbar" aria-label="شريط نوافذ الصفحات">
    <div class="ua-page-windowbar__title"><i class="fa fa-bars" aria-hidden="true"></i><span id="uaCurrentPageTitle"><?= h($uaPageTitle) ?></span></div>
    <nav class="ua-page-windowbar__pages" id="uaOpenPagesStrip" aria-label="الصفحات المفتوحة"></nav>
    <div class="ua-page-windowbar__controls" aria-label="أزرار النافذة">
      <button type="button" class="ua-page-winbtn ua-page-winbtn--close" data-ua-window-close title="إغلاق" aria-label="إغلاق"><i class="fa fa-times"></i></button>
      <button type="button" class="ua-page-winbtn ua-page-winbtn--max" data-ua-window-max title="تكبير" aria-label="تكبير"><i class="fa fa-square-o"></i></button>
      <button type="button" class="ua-page-winbtn ua-page-winbtn--min" data-ua-window-min title="تصغير" aria-label="تصغير"><i class="fa fa-minus"></i></button>
    </div>
  </header>
  <div class="ua-shell-scroll-nav nocx-gold-scrollbar" id="uaShellScrollNav" data-legacy-id="nocxGoldScrollbar" aria-label="شريط تمرير الصفحة" role="scrollbar" aria-orientation="vertical" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" tabindex="0">
    <div class="ua-shell-scroll-thumb nocx-gold-scrollbar__thumb" id="uaShellScrollThumb" data-legacy-id="nocxGoldScrollbarThumb" aria-hidden="true"></div>
  </div>
<?php endif; ?>

<main class="ua-main" id="uaShellMain" data-ua-shell-region="main">
  <div class="ua-page" id="uaWorkspaceHost" data-ua-shell-region="workspace" data-ua-workspace-host="1">
<?php if (($UA_RENDER_GLOBAL_SHELL && !$UA_IS_DASHBOARD) || (UA_FRAME_CONTEXT && $logged && !$UA_IS_DASHBOARD)): ?>
  <?php include __DIR__ . '/partials/section_nav.php'; ?>
<?php endif; ?>
<?php
// admin/helpers.php

if (!function_exists('ua_subscriber_stats')) {
  function ua_subscriber_stats(mysqli $conn): array {
    mysqli_report(MYSQLI_REPORT_OFF);

    // تأكد أن جدول subscribers موجود
    $t = 'subscribers';
    $r = @$conn->query("SHOW TABLES LIKE '$t'");
    if (!$r || $r->num_rows === 0) {
      return ['total'=>0,'active'=>0,'stopped'=>0];
    }

    // هل يوجد is_deleted؟
    $hasIsDeleted = false;
    $c = @$conn->query("SHOW COLUMNS FROM `$t` LIKE 'is_deleted'");
    if ($c && $c->num_rows > 0) $hasIsDeleted = true;

    // هل يوجد status؟
    $hasStatus = false;
    $c = @$conn->query("SHOW COLUMNS FROM `$t` LIKE 'status'");
    if ($c && $c->num_rows > 0) $hasStatus = true;

    // شرط الاستبعاد (Soft delete)
    $where = $hasIsDeleted ? "WHERE `is_deleted`=0" : "";

    // إذا ما في status: اعتبر الكل نشط
    if (!$hasStatus) {
      $q = @$conn->query("SELECT COUNT(*) AS total FROM `$t` $where");
      $total = $q ? (int)($q->fetch_assoc()['total'] ?? 0) : 0;
      return ['total'=>$total,'active'=>$total,'stopped'=>0];
    }

    // منطق موحّد:
    // - active: status بعد TRIM يساوي "نشط" أو "فعال" أو "active" أو "on"
    // - stopped: كل الباقي (حتى لو قيمة غريبة) حتى ما يصير اختلاف مجموع
    $sql = "
      SELECT
        COUNT(*) AS total,
        SUM(
          CASE
            WHEN LOWER(TRIM(COALESCE(`status`, ''))) IN ('نشط','فعال','active','on')
            THEN 1 ELSE 0
          END
        ) AS active
      FROM `$t`
      $where
    ";
    $q = @$conn->query($sql);
    if (!$q) return ['total'=>0,'active'=>0,'stopped'=>0];

    $row = $q->fetch_assoc();
    $total  = (int)($row['total'] ?? 0);
    $active = (int)($row['active'] ?? 0);
    $stopped = max(0, $total - $active);

    return ['total'=>$total,'active'=>$active,'stopped'=>$stopped];
  }
}
