<?php
// Simple smoke test for Dashboard page via HTTP GET
// Usage: php scripts/smoke_dashboard.php [baseUrl]

function fetch_url($url) {
  // Prefer curl when available; fallback to file_get_contents
  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $body = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code > 0) return [$code, $body, $err];
  }
  // Fallback
  $ctx = stream_context_create([
    'http' => [ 'timeout' => 10, 'ignore_errors' => true ]
  ]);
  $body = @file_get_contents($url, false, $ctx);
  $code = 0;
  if (isset($http_response_header) && is_array($http_response_header)) {
    foreach ($http_response_header as $h) {
      if (preg_match('/^HTTP\/\d\.\d\s+(\d+)/', $h, $m)) { $code = (int)$m[1]; break; }
    }
  }
  return [$code, $body, ''];
}

$base = $argv[1] ?? getenv('BASE_URL') ?? 'http://localhost:8000';
$url = rtrim($base, '/') . '/dashboard';
[$code, $body, $err] = fetch_url($url);

$fails = [];
if ($err) $fails[] = "curl error: $err";
if ($code !== 200) $fails[] = "HTTP code $code != 200";
if (!is_string($body) || strlen($body) < 100) $fails[] = "Response body too small";

// Basic content assertions
$asserts = [
  'Dashboard header' => '/<h1>\s*Dashboard\s*<\/h1>/i',
  'Tab navigation' => '/class="tab-nav"/i',
  'KPIs section' => '/id="kpiFatTotal"/i',
  'Finance payables' => '/id="financePayables"/i',
  'Finance receivables' => '/id="financeReceivables"/i',
  'Realtime list' => '/id="rtList"/i',
  'Seller report' => '/id="sellerReport"/i',
];

foreach ($asserts as $label => $regex) {
  if (!preg_match($regex, $body)) {
    $fails[] = "Missing: $label";
  }
}

if ($fails) {
  echo "Dashboard smoke test: FAIL\n";
  foreach ($fails as $f) echo " - $f\n";
  exit(1);
} else {
  echo "Dashboard smoke test: PASS\n";
  exit(0);
}