<?php
declare(strict_types=1);

$view   = $GLOBALS['__VIEW'] ?? 'home';
$params = $GLOBALS['__PARAMS'] ?? [];

// Ensure session
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// ---------------------------
// CSRF (site-wide, unified)
// ---------------------------
$csrfCandidates = ['csrf_token','csrf','_csrf','csrf_creator_reply','csrf_creator','csrf_brand_send','token'];

$csrfFound = '';
foreach ($csrfCandidates as $k) {
    if (!empty($_SESSION[$k]) && is_string($_SESSION[$k])) {
        $csrfFound = (string)$_SESSION[$k];
        break;
    }
}
if ($csrfFound === '') {
    $csrfFound = bin2hex(random_bytes(16));
}

// store same token in multiple keys for compatibility across views
$_SESSION['csrf_token'] = $csrfFound;
$_SESSION['csrf']       = $csrfFound;
$_SESSION['_csrf']      = $csrfFound;
$_SESSION['csrf_creator_reply'] = $csrfFound;
$_SESSION['csrf_brand_send']    = $csrfFound;

// optional global convenience
$GLOBALS['__CSRF'] = $csrfFound;

// Small safe escaper (do not rely on view helpers here)
$h = static function ($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
};

// ---------------------------
// SEO globals (set by views, e.g. profile.php)
// ---------------------------
$SITE_NAME = 'CollabMe';

$title = (string)($GLOBALS['__TITLE'] ?? $SITE_NAME);
$title = trim($title) !== '' ? $title : $SITE_NAME;

$metaDesc = (string)($GLOBALS['__META_DESCRIPTION'] ?? '');
$metaDesc = trim($metaDesc);

$robots = (string)($GLOBALS['__ROBOTS'] ?? 'index,follow');
$robots = trim($robots) !== '' ? $robots : 'index,follow';

$canonical = (string)($GLOBALS['__CANONICAL'] ?? '');
$canonical = trim($canonical);

// Build canonical fallback if not provided by the view
if ($canonical === '') {
    $proto = 'http';
    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        $proto = strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']);
    } elseif (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        $proto = 'https';
    }
    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    if ($host !== '') {
        $uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
        $canonical = $proto . '://' . $host . $uri;
        // strip query for canonical by default
        $canonical = preg_replace('~\?.*$~', '', $canonical) ?: $canonical;
    }
}

// Optional OG image if you later set $__OG_IMAGE
$ogImage = (string)($GLOBALS['__OG_IMAGE'] ?? '');
$ogImage = trim($ogImage);

// If ogImage is relative, make it absolute
if ($ogImage !== '' && !preg_match('~^https?://~i', $ogImage)) {
    $proto = 'http';
    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        $proto = strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']);
    } elseif (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        $proto = 'https';
    }
    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    if ($host !== '') {
        $ogImage = $proto . '://' . $host . '/' . ltrim($ogImage, '/');
    }
}

// ---------------------------
// Auth state (defensive)  ✅ UPDATED (normalized roles)
// ---------------------------
$logged  = function_exists('auth_is_logged_in') ? auth_is_logged_in() : !empty($_SESSION['uid']);
$roleRaw = ($logged && function_exists('auth_role')) ? (string)auth_role() : (string)($_SESSION['role'] ?? '');
$role    = strtolower(trim($roleRaw));
$uid     = ($logged && function_exists('auth_user_id')) ? (int)auth_user_id() : (int)($_SESSION['uid'] ?? 0);

$isAdmin   = in_array($role, ['admin','administrator','superadmin'], true);
$isBrand   = in_array($role, ['brand','brand_user','brandadmin','brand-admin'], true);
$isCreator = in_array($role, ['creator','creator_user'], true);

$pdo = null;
if (function_exists('db')) {
    try { $pdo = db(); } catch (Throwable $e) { $pdo = null; }
}

// Detect briefs columns once (defensive)
$briefCols = [];
if ($pdo instanceof PDO) {
    try {
        $crows = $pdo->query("SHOW COLUMNS FROM briefs")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($crows as $c) $briefCols[(string)$c['Field']] = true;
    } catch (Throwable $e) {
        // ignore
    }
}

// ---------------------------
// Unread replies badge (brand/admin) ✅ UPDATED
// ---------------------------
$unreadBrandReplies = 0;
if ($logged && $uid > 0 && ($isBrand || $isAdmin) && ($pdo instanceof PDO)) {
    try {
        if (!empty($briefCols['brand_user_id']) && !empty($briefCols['reply_message']) && !empty($briefCols['brand_read_at'])) {
            $st = $pdo->prepare("
                SELECT COUNT(*) AS c
                FROM briefs
                WHERE brand_user_id = ?
                  AND reply_message IS NOT NULL
                  AND reply_message <> ''
                  AND brand_read_at IS NULL
            ");
            $st->execute([$uid]);
            $unreadBrandReplies = (int)($st->fetch()['c'] ?? 0);
        }
    } catch (Throwable $e) {
        error_log('LAYOUT_UNREAD_BRAND_BADGE_ERROR: ' . $e->getMessage());
    }
}

// ---------------------------
// Unread briefs badge (creator/admin) ✅ UPDATED
// ---------------------------
$unreadCreatorBriefs = 0;
$creatorIdForNav = 0;

if ($logged && $uid > 0 && ($isCreator || $isAdmin) && ($pdo instanceof PDO)) {
    try {
        // find creator.id for this user
        $st = $pdo->prepare("SELECT id FROM creators WHERE user_id=? LIMIT 1");
        $st->execute([$uid]);
        $row = $st->fetch();
        if ($row) $creatorIdForNav = (int)$row['id'];

        if ($creatorIdForNav > 0) {
            if (!empty($briefCols['creator_id']) && !empty($briefCols['creator_read_at'])) {
                $st = $pdo->prepare("
                    SELECT COUNT(*) AS c
                    FROM briefs
                    WHERE creator_id = ?
                      AND creator_read_at IS NULL
                ");
                $st->execute([$creatorIdForNav]);
                $unreadCreatorBriefs = (int)($st->fetch()['c'] ?? 0);
            } elseif (!empty($briefCols['creator_id']) && !empty($briefCols['status'])) {
                // fallback if creator_read_at not present
                $st = $pdo->prepare("
                    SELECT COUNT(*) AS c
                    FROM briefs
                    WHERE creator_id = ?
                      AND (status IS NULL OR status NOT IN ('read','replied'))
                ");
                $st->execute([$creatorIdForNav]);
                $unreadCreatorBriefs = (int)($st->fetch()['c'] ?? 0);
            }
        }
    } catch (Throwable $e) {
        error_log('LAYOUT_UNREAD_CREATOR_BADGE_ERROR: ' . $e->getMessage());
    }
}

// ---------------------------
// Creator Featured status (for navbar highlight) ✅ NEW
// ---------------------------
$creatorFeaturedActive = false;
$creatorFeaturedUntil  = '';

if ($logged && $creatorIdForNav > 0 && ($isCreator || $isAdmin) && ($pdo instanceof PDO)) {
    try {
        // Check featured_until column exists (safe)
        $st = $pdo->query("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = 'creators'
              AND column_name = 'featured_until'
        ");
        $hasFeatCol = ((int)$st->fetchColumn() > 0);

        if ($hasFeatCol) {
            $st = $pdo->prepare("SELECT featured_until FROM creators WHERE id=? LIMIT 1");
            $st->execute([$creatorIdForNav]);
            $creatorFeaturedUntil = (string)($st->fetchColumn() ?: '');

            if ($creatorFeaturedUntil !== '') {
                $ts = strtotime($creatorFeaturedUntil);
                $creatorFeaturedActive = ($ts !== false && $ts > time());
            }
        }
    } catch (Throwable $e) {
        // ignore; keep inactive
    }
}

// ---------------------------
// Browse link: MUST be unfiltered
// ---------------------------
$browseHref = '/browse';

// ---------------------------
// Layout mode: make listing/browse full-width (functional-first)
// ---------------------------
$FULL_VIEWS = ['browse', 'listing']; // keep others boxed for now
$isFullWidth = in_array((string)$view, $FULL_VIEWS, true);

$navInnerStyle = $isFullWidth
    ? "width:100%;margin:0;padding:10px 16px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;"
    : "max-width:1100px;margin:0 auto;padding:10px 16px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;";

$mainStyle = $isFullWidth
    ? "width:100%;max-width:none;margin:24px 0;padding:0 16px;"
    : "max-width:1100px;margin:24px auto;padding:0 16px;";

?><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title><?= $h($title) ?></title>

  <?php if ($metaDesc !== ''): ?>
    <meta name="description" content="<?= $h($metaDesc) ?>">
  <?php endif; ?>

  <?php if ($robots !== ''): ?>
    <meta name="robots" content="<?= $h($robots) ?>">
  <?php endif; ?>

  <?php if ($canonical !== ''): ?>
    <link rel="canonical" href="<?= $h($canonical) ?>">
  <?php endif; ?>

  <!-- Open Graph -->
  <meta property="og:site_name" content="<?= $h($SITE_NAME) ?>">
  <meta property="og:title" content="<?= $h($title) ?>">
  <?php if ($metaDesc !== ''): ?>
    <meta property="og:description" content="<?= $h($metaDesc) ?>">
  <?php endif; ?>
  <?php if ($canonical !== ''): ?>
    <meta property="og:url" content="<?= $h($canonical) ?>">
  <?php endif; ?>
  <meta property="og:type" content="website">
  <?php if ($ogImage !== ''): ?>
    <meta property="og:image" content="<?= $h($ogImage) ?>">
  <?php endif; ?>

  <!-- Twitter -->
  <meta name="twitter:card" content="<?= $ogImage !== '' ? 'summary_large_image' : 'summary' ?>">
  <meta name="twitter:title" content="<?= $h($title) ?>">
  <?php if ($metaDesc !== ''): ?>
    <meta name="twitter:description" content="<?= $h($metaDesc) ?>">
  <?php endif; ?>
  <?php if ($ogImage !== ''): ?>
    <meta name="twitter:image" content="<?= $h($ogImage) ?>">
  <?php endif; ?>

  <link rel="stylesheet" href="/assets/css/app.css">
</head>
<body>

  <!-- TOP NAV (CS themed) -->
  <div style="border-bottom:1px solid var(--border);background:rgba(7,11,18,0.72);backdrop-filter:blur(10px);">
    <div style="<?= $navInnerStyle ?>">
      <a href="/" style="font-weight:800;text-decoration:none;color:var(--text);">CollabMe</a>

      <a class="badge" href="/" style="text-decoration:none;">Home</a>
      <a class="badge" href="<?= $h($browseHref) ?>" style="text-decoration:none;opacity:.95;">Browse</a>

      <span style="margin-left:auto;"></span>

      <?php if (!$logged): ?>
        <a class="badge" href="/login" style="text-decoration:none;">Login</a>
        <a class="badge" href="/register" style="text-decoration:none;">Register</a>
      <?php else: ?>

        <?php if ($isBrand || $isAdmin): ?>
          <a class="badge" href="/brand/dashboard" style="text-decoration:none;">Brand Dashboard</a>

          <a class="badge" href="/brand/inbox" style="text-decoration:none;position:relative;">
            Inbox
            <?php if ($unreadBrandReplies > 0): ?>
              <span style="display:inline-block;margin-left:6px;min-width:18px;padding:2px 7px;border-radius:999px;
                           background:var(--primary);color:#fff;font-size:12px;line-height:1.4;text-align:center;">
                <?= (int)$unreadBrandReplies ?>
              </span>
            <?php endif; ?>
          </a>
        <?php endif; ?>

        <?php if ($isCreator || $isAdmin): ?>
          <a class="badge" href="/creator/edit" style="text-decoration:none;">Creator Profile</a>
          <a class="badge" href="/creator/dashboard" style="text-decoration:none;">Creator Dashboard</a>

          <!-- Featured in creator nav -->
          <a class="badge"
             href="/creator/featured"
             style="text-decoration:none;<?= $creatorFeaturedActive ? 'border-color:#ffe1a6;background:#fff8e8;color:#111;' : '' ?>">
            Featured<?= $creatorFeaturedActive ? ' ★' : '' ?>
          </a>

          <a class="badge" href="/creator/inbox" style="text-decoration:none;position:relative;">
            Creator Inbox
            <?php if ($unreadCreatorBriefs > 0): ?>
              <span style="display:inline-block;margin-left:6px;min-width:18px;padding:2px 7px;border-radius:999px;
                           background:var(--primary);color:#fff;font-size:12px;line-height:1.4;text-align:center;">
                <?= (int)$unreadCreatorBriefs ?>
              </span>
            <?php endif; ?>
          </a>
        <?php endif; ?>

        <a class="badge" href="/logout" style="text-decoration:none;">Logout</a>

      <?php endif; ?>
    </div>
  </div>

  <main style="<?= $mainStyle ?>">
    <?php
      $viewFile = __DIR__ . '/' . $view . '.php';
      if (!is_file($viewFile)) {
          http_response_code(500);
          echo "Missing view file: " . $h((string)$view);
      } else {
          require $viewFile;
      }
    ?>
  </main>

  <script src="/assets/js/app.js"></script>
</body>
</html>