<?php
// admin/app_access.php
// Installation-mode access guard. Server/branch stay full; agent is intentionally narrow.

require_once __DIR__ . '/app_runtime.php';

if (!function_exists('ua_request_is_api')) {
  function ua_request_is_api(): bool {
    $script = str_replace('\\', '/', (string)($_SERVER['PHP_SELF'] ?? ''));
    if (strpos($script, '/api/') !== false) return true;
    $xrw = strtolower((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? ''));
    if ($xrw === 'xmlhttprequest') return true;
    $accept = strtolower((string)($_SERVER['HTTP_ACCEPT'] ?? ''));
    return strpos($accept, 'application/json') !== false;
  }
}

if (!function_exists('ua_current_script_name')) {
  function ua_current_script_name(): string {
    return basename(parse_url((string)($_SERVER['SCRIPT_NAME'] ?? ($_SERVER['PHP_SELF'] ?? '')), PHP_URL_PATH) ?: '');
  }
}

if (!function_exists('ua_agent_allowed_pages')) {
  function ua_agent_allowed_pages(): array {
    return [
      'index.php',
      'login.php',
      'logout.php',
      'setup_first_admin.php',
      'install_link.php',
      'agent_portal.php',
      'agent_profile.php',
      'agent_output_devices.php',
      'agent_subscriber_add.php',
      'agent_subscriber_status.php',
      'agent_contract_download.php',
      'subscriber_info_print.php',
      'agent_pos.php',
      'agent_transactions.php',
      'subscriber_router_setup.php',
      'android_router_setup.php',
      'install_setup.php',
      'about.php',
      'support.php',
    ];
  }
}

if (!function_exists('ua_install_page_allowed')) {
  function ua_install_page_allowed(?string $page = null): bool {
    $mode = function_exists('ua_install_type') ? ua_install_type() : 'server';
    if ($mode === 'server' || $mode === 'branch') {
      return true;
    }

    $page = $page !== null ? basename($page) : ua_current_script_name();
    if ($page === '') return true;

    if ($mode === 'agent') {
      return in_array($page, ua_agent_allowed_pages(), true);
    }

    return true;
  }
}

if (!function_exists('ua_install_link_public_pages')) {
  function ua_install_link_public_pages(): array {
    return [
      'index.php',
      'login.php',
      'logout.php',
      'setup_first_admin.php',
      'install_setup.php',
      'install_link.php',
    ];
  }
}

if (!function_exists('ua_install_link_gate_needed')) {
  function ua_install_link_gate_needed(?string $page = null): bool {
    if (!function_exists('ua_install_link_required') || !ua_install_link_required()) return false;
    if (function_exists('ua_install_link_approved') && ua_install_link_approved()) return false;

    $page = $page !== null ? basename($page) : ua_current_script_name();
    if ($page === '') return false;
    if (in_array($page, ua_install_link_public_pages(), true)) return false;
    return true;
  }
}

if (!function_exists('ua_install_access_denied')) {
  function ua_install_access_denied(): void {
    if (!headers_sent()) {
      http_response_code(403);
    }

    if (ua_request_is_api()) {
      if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8');
      }
      echo json_encode([
        'ok' => false,
        'error' => 'INSTALL_MODE_FORBIDDEN',
        'mode' => function_exists('ua_install_type') ? ua_install_type() : 'unknown',
        'message' => 'This page is not available in this installation type.',
      ], ua_json_flags());
      exit;
    }

    echo '<!doctype html><html><head><meta charset="utf-8"><title>403</title></head><body style="font-family:Arial,sans-serif;direction:rtl;padding:32px">';
    echo '<h1>403</h1><p>هذه الصفحة غير متاحة في نوع هذه النسخة.</p>';
    echo '</body></html>';
    exit;
  }
}

if (!function_exists('ua_enforce_install_access')) {
  function ua_enforce_install_access(?string $page = null): void {
    if (PHP_SAPI === 'cli') return;
    if (ua_install_link_gate_needed($page)) {
      if (ua_request_is_api()) {
        ua_install_access_denied();
      }
      if (!headers_sent()) {
        header('Location: install_link.php');
        exit;
      }
    }
    if (!ua_install_page_allowed($page)) {
      $pageName = $page !== null ? basename($page) : ua_current_script_name();
      if (function_exists('ua_is_agent_install') && ua_is_agent_install() && $pageName === 'dashboard.php' && !headers_sent()) {
        header('Location: ' . (function_exists('ua_install_home_page') ? ua_install_home_page() : 'agent_pos.php'));
        exit;
      }
      ua_install_access_denied();
    }
  }
}
