<?php
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/media_assets_lib.php';
require_once __DIR__ . '/db_bootstrap.php';
// admin/index.php (Compact EXE-style login window)
ua_session_start();

if (function_exists('ensure_db')) {
  ensure_db(true);
}

$conn = $GLOBALS['conn'] ?? ($conn ?? null);
if ($conn instanceof mysqli) {
  try {
    $hasAdmins = false;
    $table = $conn->query("SHOW TABLES LIKE 'admin_users'");
    if ($table && $table->num_rows) {
      $admins = $conn->query("SELECT id FROM admin_users LIMIT 1");
      $hasAdmins = (bool)($admins && $admins->num_rows);
    }
    if (!$hasAdmins) {
      header("Location: setup_first_admin.php");
      exit;
    }
  } catch (Throwable $e) {}
}

$logged = !empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']);
if ($logged) {
  if (function_exists('ua_install_link_required') && ua_install_link_required() && function_exists('ua_install_link_approved') && !ua_install_link_approved()) {
    header("Location: install_link.php");
    exit;
  }
  $home = function_exists('ua_install_home_page') ? ua_install_home_page() : 'dashboard.php';
  header("Location: " . $home);
  exit;
}

$page_title = 'تسجيل الدخول';
$defaultNext = function_exists('ua_install_home_page') ? ua_install_home_page() : 'dashboard.php';
$next = $_GET['next'] ?? $defaultNext;
if ($next === '' || strpos($next, '://') !== false) $next = $defaultNext;
if (function_exists('ua_is_agent_install') && ua_is_agent_install() && basename((string)$next) === 'dashboard.php') $next = $defaultNext;

$login_err = $_SESSION['ua_login_err'] ?? '';
unset($_SESSION['ua_login_err']);

include __DIR__ . '/header.php';

$exaProgramName = '';
if (defined('APP_NAME') && trim((string)APP_NAME) !== '') {
  $exaProgramName = trim((string)APP_NAME);
} elseif (function_exists('app_version_info')) {
  $exaInfo = app_version_info();
  $exaProgramName = trim((string)($exaInfo['name'] ?? ''));
}
$exaProgramName = 'إدارة الشبكة والعملاء';

$exaProgramVersion = function_exists('app_version') ? trim((string)app_version()) : '';

$exaCompanyFooterName = '';
if (($conn ?? null) instanceof mysqli) {
  try {
    if (function_exists('table_exists') && table_exists($conn, 'company_info')) {
      $r = $conn->query("SELECT * FROM company_info ORDER BY id ASC LIMIT 1");
      if ($r && $r->num_rows) {
        $row = $r->fetch_assoc();
        $exaCompanyFooterName = trim((string)($row['company_name'] ?? ($row['name'] ?? ($row['title'] ?? ''))));
      }
    }
  } catch (Throwable $e) {}
  if ($exaCompanyFooterName === '') {
    try {
      if (function_exists('table_exists') && table_exists($conn, 'system_settings')) {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='company_name' AND COALESCE(setting_value,'')<>'' LIMIT 1");
        if ($r && $r->num_rows) $exaCompanyFooterName = trim((string)($r->fetch_assoc()['setting_value'] ?? ''));
      }
    } catch (Throwable $e) {}
  }
}

if (in_array($exaCompanyFooterName, ['اسم الشركة','Company Name','company name','اسم المنشأة'], true)) {
  $exaCompanyFooterName = '';
}

$exaFooterBrand = ($exaCompanyFooterName !== '') ? $exaCompanyFooterName : $exaProgramName;
$exaTitlebarVersion = $exaProgramVersion !== '' ? ('v' . $exaProgramVersion) : '';
$exaProgramLogo = function_exists('ua_media_url') ? ua_media_url('sidebar_program_logo', 'assets/img/sidebar_program_logo.png') : 'assets/img/sidebar_program_logo.png';
$exaLoginVisual = 'assets/img/login_network_light_bg.png';
?>
<section class="exa-login-page ua-public-entry-page" aria-label="واجهة تسجيل الدخول">
  <div class="exa-login-window" role="group" aria-labelledby="exaLoginTitle">
    <div class="exa-login-shell">
      <aside class="exa-login-visual exa-login-visual-full" aria-label="خلفية إدارة الشبكة">
        <img class="exa-visual-image" src="<?= h($exaLoginVisual) ?>" alt="" aria-hidden="true">
        <div class="exa-visual-video-overlay" aria-hidden="true"></div>
        <div class="exa-visual-lock" aria-hidden="true">
          <span class="exa-lock-ring exa-lock-ring-1"></span>
          <span class="exa-lock-ring exa-lock-ring-2"></span>
          <span class="exa-lock-spark exa-lock-spark-1"></span>
          <span class="exa-lock-spark exa-lock-spark-2"></span>
          <span class="exa-lock-shackle"></span>
          <span class="exa-lock-body"><i></i></span>
        </div>
      </aside>

      <section class="exa-login-panel" aria-label="نموذج تسجيل الدخول">
        <div class="exa-login-panel-inner">
          <div class="exa-login-copy">
            <h2 id="exaLoginTitle" class="exa-login-title">تسجيل الدخول</h2>
            <p class="exa-login-subtitle">أدخل بياناتك للوصول إلى لوحة الإدارة</p>
          </div>

          <?php if ($login_err): ?>
            <div class="exa-login-alert" role="alert">
              <i class="fa fa-exclamation-circle" aria-hidden="true"></i>
              <span><?= h($login_err) ?></span>
            </div>
          <?php endif; ?>

          <form method="post" action="login.php" class="exa-login-form" autocomplete="on">
            <input type="hidden" name="next" value="<?= h($next) ?>">
            <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>

            <div class="exa-field-group">
              <label for="exaUser" class="exa-field-label">اسم المستخدم</label>
              <div class="exa-field-shell">
                <input id="exaUser" name="user" type="text" class="exa-field-input" placeholder="أدخل اسم المستخدم" autocomplete="username" autofocus required>
                <span class="exa-field-icon exa-field-icon-end" aria-hidden="true"><i class="fa fa-user-o"></i></span>
              </div>
            </div>

            <div class="exa-field-group">
              <label for="exaPass" class="exa-field-label">كلمة المرور</label>
              <div class="exa-field-shell">
                <button type="button" class="exa-field-toggle" id="exaTogglePass" aria-label="إظهار أو إخفاء كلمة المرور">
                  <i class="fa fa-eye"></i>
                </button>
                <input id="exaPass" name="pass" type="password" class="exa-field-input exa-field-input-pass" placeholder="أدخل كلمة المرور" autocomplete="current-password" required>
                <span class="exa-field-icon exa-field-icon-end" aria-hidden="true"><i class="fa fa-lock"></i></span>
              </div>
            </div>

            <div class="exa-login-actions">
              <button class="exa-btn exa-btn-primary" type="submit">دخول</button>
              <button class="exa-btn exa-btn-secondary" type="button" onclick="window.location.href='index.php'">إلغاء</button>
            </div>
          </form>
        </div>
      </section>
    </div>
  </div>
</section>

<script>
(function(){
  var btn = document.getElementById('exaTogglePass');
  var input = document.getElementById('exaPass');
  if (btn && input) {
    btn.addEventListener('click', function(){
      var isPass = input.getAttribute('type') === 'password';
      input.setAttribute('type', isPass ? 'text' : 'password');
      var icon = btn.querySelector('i');
      if (icon) {
        icon.className = isPass ? 'fa fa-eye-slash' : 'fa fa-eye';
      }
    });
  }
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>
