<?php
$pageTitle = 'Player Market | F76.WORLD Trading Post';
$metaDescription = 'Join the F76.WORLD Trading Post to trade plans, caps, and god-rolls. A secure peer-to-peer bartering system for all Fallout 76 wastelanders.';
$page = 'market';
$canonical_url = 'https://f76.world/market';
$base_path = '/';
require_once __DIR__ . '/api/auth/auth_lib.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
        'cookie_samesite' => 'Strict',
    ]);
}
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$user = auth_get_current_user();

$marketItems = [];
try {
    $db = getDb();
    $stmt = $db->query('SELECT id, title, category, stars, price, currency, username, user_id, created_at FROM market_items ORDER BY created_at DESC');
    $marketItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Database missing or empty
}

include '_includes/header.php';
?>

<div class="w-full max-w-7xl mx-auto pt-24 md:pt-32 px-4 sm:px-6 lg:px-8 pb-12 relative z-10 min-w-0 max-w-full break-words">
  <!-- ─── Hero ─── -->
  <div class="market-hero mb-12 min-w-0 max-w-full" >
    <div class="relative z-10">
      <div class="coming-soon-badge">
        <span class="status-dot" ></span>
        <span data-i18n="market_badge_under_construction">Under Construction</span>
      </div>
      <h1 class="font-hero text-2xl sm:text-4xl lg:text-5xl text-amber-500 uppercase tracking-widest mb-2 break-words" data-i18n="market_hero_title">
        Player<br><span class="text-hub-gold">Market</span>
      </h1>
      <p class="text-gray-300 font-mono text-xs sm:text-sm max-w-xl mx-auto mb-6 leading-relaxed break-words" data-i18n="market_hero_desc">
        A community-powered trading hub for Fallout 76 players. Post your vendor listings, find legendary gear, and connect with buyers across all platforms.
      </p>
      <div class="flex justify-center gap-3 sm:gap-4 flex-wrap">
        <button class="btn btn-gold" onclick="showModal('Wishlist','Enter your email to be notified when Market launches.')" data-i18n="market_btn_notify">
          <i class="fa-regular fa-bell mr-1"></i> Get Notified
        </button>
        <a href="#roadmap" class="btn btn-outline" data-i18n="market_btn_roadmap">
          <i class="fa-solid fa-map-location-dot mr-1"></i> See Roadmap
        </a>
      </div>
    </div>
  </div>

  <!-- ─── Preview UI (non-functional, design-only) ─── -->
  <div class="mb-12 min-w-0 max-w-full">
    <div class="section-label" data-i18n="market_section_label">Market</div>
    <h2 class="font-hero text-2xl sm:text-3xl text-amber-500 mb-4 uppercase break-words" data-i18n="market_section_listings">Current Listings</h2>

    <?php if ($user): ?>
    <div class="panel mb-8 p-4 sm:p-6 min-w-0 max-w-full" style="border: 1px solid var(--hub-gold); background: rgba(255, 176, 0, 0.05);">
        <h3 class="font-ui mb-4 text-hub-gold text-lg uppercase font-bold"><i class="fa-solid fa-plus"></i> Add New Listing</h3>
        <form id="add-listing-form" hx-post="<?= $base_path ?>api/market/add_item.php" hx-target="#market-add-status" hx-swap="innerHTML" hx-indicator="#market-add-spinner" hx-on::after-request="if(event.detail.successful && event.detail.xhr.responseText.includes('success')) setTimeout(() => window.location.reload(), 400);" class="flex flex-wrap gap-3 sm:gap-4 items-end min-w-0 max-w-full">
            <div class="flex-1 min-w-[200px] max-w-full">
                <label for="add-title" class="text-xs text-gray-300 block mb-1 font-mono uppercase">Item Name</label>
                <input type="text" id="add-title" name="title" placeholder="e.g. Quad Explosive LMG" required aria-required="true" class="w-full bg-black border border-gray-700 rounded px-3 py-2 text-white">
            </div>
            <div class="w-full sm:w-36 min-w-[120px]">
                <label for="add-category" class="text-xs text-gray-300 block mb-1 font-mono uppercase">Category</label>
                <select id="add-category" name="category" aria-label="Category" class="w-full bg-black border border-gray-700 rounded px-3 py-2 text-white">
                    <option value="Weapon">Weapon</option>
                    <option value="Armor">Armor</option>
                    <option value="Plan">Plan</option>
                    <option value="Ammo">Ammo</option>
                    <option value="Aid">Aid</option>
                    <option value="Food">Food</option>
                    <option value="Drink">Drink</option>
                    <option value="Companion">Companion</option>
                    <option value="Vehicle">Vehicle</option>
                </select>
            </div>
            <div class="w-full sm:w-28 min-w-[90px]">
                <label for="add-stars" class="text-xs text-gray-300 block mb-1 font-mono uppercase">Stars</label>
                <select id="add-stars" name="stars" aria-label="Stars" class="w-full bg-black border border-gray-700 rounded px-3 py-2 text-white">
                    <option value="—">—</option>
                    <option value="⭐">⭐</option>
                    <option value="⭐⭐">⭐⭐</option>
                    <option value="⭐⭐⭐">⭐⭐⭐</option>
                </select>
            </div>
            <div class="w-full sm:w-36 min-w-[120px]">
                <label for="add-price" class="text-xs text-gray-300 block mb-1 font-mono uppercase">Price</label>
                <input type="text" id="add-price" name="price" placeholder="Caps or trade" required aria-required="true" class="w-full bg-black border border-gray-700 rounded px-3 py-2 text-white">
            </div>
            <div class="w-full sm:w-36 min-w-[120px]">
                <label for="add-currency" class="text-xs text-gray-300 block mb-1 font-mono uppercase">Currency</label>
                <select id="add-currency" name="currency" aria-label="Currency" class="w-full bg-black border border-gray-700 rounded px-3 py-2 text-white">
                    <option value="Caps">Caps</option>
                    <option value="Leaders">Leaders</option>
                    <option value="LL3">LL3</option>
                    <option value="BW6">BW6</option>
                </select>
            </div>
            <div class="w-full sm:w-auto">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <button type="submit" class="btn btn-gold py-2 px-6 flex items-center justify-center gap-2 font-bold w-full sm:w-auto">
                    <span id="market-add-spinner" class="htmx-indicator"><i class="fa-solid fa-spinner fa-spin"></i></span>
                    <i class="fa-solid fa-check htmx-indicator-hide" aria-hidden="true"></i> Post
                </button>
            </div>
            <div id="market-add-status" class="w-full mt-2 font-mono text-xs text-center"></div>
        </form>
    </div>
    <?php endif; ?>

    <!-- Search Bar (decorative) -->
    <div class="panel" >
      <i class="fa-solid fa-magnifying-glass" ></i>
      <input type="text" aria-label="Search items" placeholder='Search items, e.g. "Quad Explosive LMG"...'
        >
      <button class="btn btn-gold btn-sm">Search</button>
      <button class="btn btn-outline btn-sm"><i class="fa-solid fa-sliders"></i> Filter</button>
    </div>

    <!-- Filter pills (decorative) -->
    <div >
      <span class="pill pill-gold">All Items</span>
      <span class="pill pill-gray">Weapons</span>
      <span class="pill pill-gray">Armor</span>
      <span class="pill pill-gray">Plans</span>
      <span class="pill pill-gray">Ammo</span>
      <span class="pill pill-gray">Food &amp; Aid</span>
      <span class="pill pill-gray">Legendary ⭐⭐⭐</span>
    </div>

    <!-- Real listings -->
    <div >
      <?php if (empty($marketItems)): ?>
          <p class="text-gray-300 text-center py-8">No items listed yet. Be the first!</p>
      <?php else: ?>
          <?php foreach ($marketItems as $item): ?>
          <div class="market-feature-card relative group" >
            <div >
              <span class="pill pill-gray" ><?= htmlspecialchars($item['category']) ?></span>
              <span ><?= htmlspecialchars($item['stars']) ?></span>
            </div>
            <div class="font-ui" ><?= htmlspecialchars($item['title']) ?></div>
            <div                <span class="font-mono"><?= htmlspecialchars($item['price']) ?> <span class="text-xs text-gray-300">(<?= htmlspecialchars($item['currency']) ?>)</span></span>
                <span class="font-mono text-hub-gold"><i class="fa-solid fa-user text-xs"></i> <?= htmlspecialchars($item['username']) ?><?php if ($user) { echo ' <a class="ml-2 btn btn-sm btn-outline" href="/chat?user=' . urlencode($item['username']) . '">Message</a>'; } ?></span>
            </div>
            <?php if ($user && ($user['role'] === 'admin' || $user['user_id'] == $item['user_id'])): ?>
            <button hx-post="<?= $base_path ?>api/market/delete_item.php" hx-vals='{"id": <?= $item['id'] ?>}' hx-target="this" hx-swap="none" hx-confirm="Are you sure you want to delete this listing from the market?" hx-indicator="#del-spin-<?= $item['id'] ?>" hx-on::after-request="if(event.detail.successful) window.location.reload();" class="absolute top-2 right-2 text-red-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition" aria-label="Delete Listing" title="Delete Listing">
                <span id="del-spin-<?= $item['id'] ?>" class="htmx-indicator mr-1"><i class="fa-solid fa-spinner fa-spin text-xs"></i></span>
                <i class="fa-solid fa-trash htmx-indicator-hide" aria-hidden="true"></i>
            </button>
            <?php endif; ?>
          </div>
          <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <div >
      <span class="pill pill-gold">
        <i class="fa-solid fa-check" ></i>&nbsp; Live Market Phase 1 Active
      </span>
    </div>
  </div>

  <!-- ─── Planned Features ─── -->
  <div id="roadmap" class="mb-12">
    <div class="section-label">Roadmap</div>
    <h2 class="font-hero text-amber-500" >Planned Features</h2>

    <div >
      <?php
      $features = [
        ['fa-search', 'Smart Search', 'Full-text search with legendary mod filtering — find that Quad Explosive in seconds.'],
        ['fa-tag', 'Item Listings', 'Post your vendor items with auto-calculated value suggestions based on community prices.'],
        ['fa-bell', 'Price Alerts', 'Get notified when an item you want drops below your target price.'],
        ['fa-star', 'Legendary Filter', 'Filter by 1★, 2★, 3★ effects. Search by specific legendary perks.'],
        ['fa-user-shield', 'Verified Sellers', 'Community reputation scores and trade history for trusted sellers.'],
        ['fa-chart-line', 'Market Trends', 'Historical pricing charts and economy stats to buy and sell smarter.'],
        ['fa-gamepad', 'Platform Support', 'PC, PlayStation, and Xbox listings with cross-platform visibility.'],
        ['fa-comments', 'Trade Chat', 'Built-in DM system for negotiating trades without leaving the site.'],
      ];
      foreach ($features as $f): ?>
      <div class="market-feature-card">
        <div class="market-feature-icon">
          <i class="fa-solid <?= $f[0] ?> text-hub-gold"></i>
        </div>
        <div class="font-ui" ><?= $f[1] ?></div>
        <p ><?= $f[2] ?></p>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ─── Progress Timeline ─── -->
  <div class="panel" >
    <div class="section-label">Build Status</div>
    <h2 class="font-hero text-amber-500" >Development Progress</h2>

    <?php
    $phases = [
      ['Design System & UI Components', 100, 'Complete', 'green'],
      ['Page Layout & Navigation',       100, 'Complete', 'green'],
      ['Mock/Preview UI',                100, 'Complete', 'green'],
      ['Backend API (PHP)',               35, 'In Progress', 'gold'],
      ['User Authentication',             10, 'Planned', 'gray'],
      ['Listing CRUD & Search',            5, 'Planned', 'gray'],
      ['Community Rating System',          0, 'Planned', 'gray'],
    ];
    foreach ($phases as $phase): ?>
    <div >
      <div >
        <span class="font-ui" ><?= $phase[0] ?></span>
        <span class="pill pill-<?= $phase[3] ?>" ><?= $phase[2] ?></span>
      </div>
      <div >
        <div ></div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ─── Contribute CTA ─── -->
  <div class="panel-gold" >
    <div >🤝</div>
    <h3 class="font-hero text-amber-500" >Help Build This</h3>
    <p >
      F76.WORLD is a community project. If you're a developer, designer, or Fallout 76 enthusiast who wants to contribute to the Market feature, get in touch.
    </p>
    <div >
      <button class="btn btn-gold" onclick="showModal('Contribute','Contact us via Discord. Community contributors welcome!')">
        <i class="fa-brands fa-discord"></i> Join Development
      </button>
      <a href="/" class="btn btn-outline">Back to Hub</a>
    </div>
  </div>
</div>

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