<?php
declare(strict_types=1);

/**
 * Session-based auth gate (no DB).
 * Required credentials:
 *  - username: admin
 *  - password: admin5004!
 *
 * NOTE: Password is stored as SHA-256 hash here (not plaintext).
 */

function dreamgirl_session_start(): void {
  if (session_status() === PHP_SESSION_ACTIVE) return;

  $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

  // PHP 7.3+ supports samesite via array; older versions may ignore unknown keys.
  session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'httponly' => true,
    'samesite' => 'Lax',
    'secure' => $secure,
  ]);

  session_start();
}

function dreamgirl_is_logged_in(): bool {
  dreamgirl_session_start();
  // Try NCue SSO once per session (if available)
  if (!isset($_SESSION['dreamgirl_sso_checked'])) {
    $_SESSION['dreamgirl_sso_checked'] = true;
    dreamgirl_try_ncue_sso_login();
  }
  return isset($_SESSION['dreamgirl_user']) && $_SESSION['dreamgirl_user'] === 'admin';
}

function dreamgirl_check_credentials(string $username, string $password): bool {
  if ($username !== 'admin') return false;

  // sha256("admin5004!")
  $expectedSha256 = 'adcda104b73b73f8cddf5c8047a6bc0e5e1388265ed4bf0f31f704c13cbc11b7';
  $gotSha256 = hash('sha256', $password);

  return hash_equals($expectedSha256, $gotSha256);
}

function dreamgirl_base_path(): string {
  // If deployed under /dreamgirl, SCRIPT_NAME is like /dreamgirl/index.php
  // If at web root, SCRIPT_NAME is like /index.php
  $script = isset($_SERVER['SCRIPT_NAME']) ? (string)$_SERVER['SCRIPT_NAME'] : '';
  $dir = rtrim(str_replace('\\', '/', dirname($script)), '/');
  return ($dir === '' || $dir === '.') ? '' : $dir;
}

function dreamgirl_url(string $path): string {
  $base = dreamgirl_base_path();
  $p = ltrim($path, '/');
  return $base . '/' . $p;
}

function dreamgirl_try_ncue_sso_login(): bool {
  // If already logged in, nothing to do.
  if (isset($_SESSION['dreamgirl_user']) && $_SESSION['dreamgirl_user'] === 'admin') return true;

  // Only accept SSO for the known NCue account (Google login).
  $allowedEmails = ['dosangyoon2@gmail.com'];

  // Endpoint commonly provided by NextAuth/Auth.js style setups.
  $endpointPath = '/api/auth/session';

  $host = isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '';
  if ($host === '') return false;

  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $url = $scheme . '://' . $host . $endpointPath;

  $cookieHeader = isset($_SERVER['HTTP_COOKIE']) ? (string)$_SERVER['HTTP_COOKIE'] : '';
  if ($cookieHeader === '') return false;

  $json = null;

  // Prefer cURL if available
  if (function_exists('curl_init')) {
    $ch = curl_init();
    if ($ch === false) return false;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Accept: application/json',
      'Cookie: ' . $cookieHeader,
    ]);
    // Do not follow redirects to avoid loops
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

    $resp = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($resp !== false && $code >= 200 && $code < 300) {
      $json = $resp;
    } else {
      return false;
    }
  } else {
    // Fallback using stream context
    $ctx = stream_context_create([
      'http' => [
        'method' => 'GET',
        'header' => "Accept: application/json\r\nCookie: {$cookieHeader}\r\n",
        'timeout' => 2,
        'ignore_errors' => true,
      ]
    ]);
    $resp = @file_get_contents($url, false, $ctx);
    if ($resp !== false) $json = $resp;
  }

  if ($json === null) return false;

  $data = json_decode($json, true);
  if (!is_array($data)) return false;

  // NextAuth shape: { user: { email: ... }, expires: ... }
  $email = '';
  if (isset($data['user']) && is_array($data['user']) && isset($data['user']['email'])) {
    $email = (string)$data['user']['email'];
  } elseif (isset($data['email'])) {
    // Alternate shape
    $email = (string)$data['email'];
  }

  if ($email === '' || !in_array($email, $allowedEmails, true)) return false;

  // SSO accepted: mark session as logged-in for DreamGirl.
  $_SESSION['dreamgirl_user'] = 'admin';
  $_SESSION['dreamgirl_sso_email'] = $email;
  $_SESSION['dreamgirl_sso_at'] = time();
  return true;
}

function dreamgirl_require_login_page(): void {
  if (dreamgirl_is_logged_in()) return;
  header('Location: ' . dreamgirl_url('login.php'));
  exit;
}

function dreamgirl_require_login_json(): void {
  if (dreamgirl_is_logged_in()) return;
  http_response_code(401);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(['ok' => false, 'error' => 'Unauthorized'], JSON_UNESCAPED_UNICODE);
  exit;
}

