<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../config/logger.php';

$basePath = '..';

// Filters
$catSlug = isset($_GET['cat']) ? trim($_GET['cat']) : '';
$catIdParam = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : 0;
$selectedCatId = 0;
$categories = [];

// Detect categories support
$hasCategories = false;
$tbl = fetchRow("SHOW TABLES LIKE 'ad_categories'");
if ($tbl) {
    $hasCategories = true;
    $categories = fetchRows("SELECT c.id, c.name, c.slug, COUNT(a.id) AS cnt
                              FROM ad_categories c
                              LEFT JOIN ads a ON a.category_id=c.id AND a.status='approved' AND (a.starts_at IS NULL OR a.starts_at <= NOW()) AND (a.ends_at IS NULL OR a.ends_at >= NOW())
                              GROUP BY c.id, c.name, c.slug
                              ORDER BY c.name");
    if ($catIdParam > 0) {
        $catRow = fetchRow("SELECT id, name, slug FROM ad_categories WHERE id=?", [$catIdParam]);
        if ($catRow) { $selectedCatId = (int)$catRow['id']; }
    } elseif ($catSlug !== '') {
        $catRow = fetchRow("SELECT id, name, slug FROM ad_categories WHERE slug=?", [$catSlug]);
        if ($catRow) { $selectedCatId = (int)$catRow['id']; }
    }
}

// Mark expired approved ads
$col = fetchRow("SHOW COLUMNS FROM ads LIKE 'workflow_state'");
if ($col) {
    executeQuery("UPDATE ads SET workflow_state='expired' WHERE workflow_state <> 'expired' AND status='approved' AND ends_at IS NOT NULL AND ends_at < NOW()");
}

// Pagination
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 12;
$offset = ($page - 1) * $limit;

// Count total approved and active ads (with optional category)
$where = "status='approved' AND (starts_at IS NULL OR starts_at <= NOW()) AND (ends_at IS NULL OR ends_at >= NOW())";
if ($hasCategories && $selectedCatId > 0) {
    $totalRow = fetchRow("SELECT COUNT(*) AS cnt FROM ads WHERE $where AND category_id=" . (int)$selectedCatId);
} else {
    $totalRow = fetchRow("SELECT COUNT(*) AS cnt FROM ads WHERE $where");
}
$total = (int)($totalRow['cnt'] ?? 0);
$pages = max(1, (int)ceil($total / $limit));
if ($page > $pages) { $page = $pages; $offset = ($page - 1) * $limit; }

// Fetch page (with optional category)
if ($hasCategories && $selectedCatId > 0) {
    $ads = fetchRows(
        "SELECT * FROM ads WHERE $where AND category_id=" . (int)$selectedCatId . " ORDER BY created_at DESC LIMIT $limit OFFSET $offset"
    );
} else {
    $ads = fetchRows(
        "SELECT * FROM ads WHERE $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset"
    );
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Member Adverts - GHAMECC</title>
    <?php include '../includes/favicon.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container">
    <a class="navbar-brand" href="<?php echo $basePath; ?>/index.php">GHAMECC</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="mainNav">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item"><a class="nav-link" href="<?php echo $basePath; ?>/index.php">Home</a></li>
        <li class="nav-item"><a class="nav-link" href="<?php echo $basePath; ?>/jobs/">Jobs</a></li>
      </ul>
      <div class="d-flex gap-2">
        <?php if (isLoggedIn()): ?>
          <a href="<?php echo $basePath; ?>/index.php" class="btn btn-sm btn-light text-primary"><i class="fas fa-gauge me-1"></i> Dashboard</a>
        <?php else: ?>
          <a href="<?php echo $basePath; ?>/login.php" class="btn btn-sm btn-light text-primary"><i class="fas fa-sign-in-alt me-1"></i> Login</a>
        <?php endif; ?>
        <a href="<?php echo $basePath; ?>/ads/submit.php" class="btn btn-sm btn-warning text-dark">
          <i class="fas fa-bullhorn me-1"></i> Advertise with us
        </a>
      </div>
    </div>
  </div>
 </nav>

<section class="py-4">
  <div class="container">
    <h1 class="h3 mb-3">Member Adverts</h1>

    <div class="row g-4">
      <aside class="col-lg-3">
        <?php if ($hasCategories): ?>
        <div class="card">
          <div class="card-header">Categories</div>
          <div class="list-group list-group-flush">
            <a href="list.php" class="list-group-item list-group-item-action <?php echo $selectedCatId===0 ? 'active' : ''; ?>">All</a>
            <?php foreach ($categories as $cat): ?>
              <a href="list.php?cat=<?php echo urlencode($cat['slug']); ?>" class="list-group-item list-group-item-action <?php echo ($selectedCatId===(int)$cat['id']) ? 'active' : ''; ?>">
                <?php echo htmlspecialchars($cat['name']); ?>
                <span class="badge bg-light text-muted float-end"><?php echo (int)($cat['cnt'] ?? 0); ?></span>
              </a>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>
      </aside>

      <div class="col-lg-9">
        <?php if (empty($ads)): ?>
          <div class="alert alert-info">No adverts available.</div>
        <?php else: ?>
          <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-3 g-3">
            <?php foreach ($ads as $ad): ?>
          <?php 
            $descText = isset($ad['description']) ? strip_tags($ad['description']) : '';
            $short = strlen($descText) > 110 ? substr($descText, 0, 110) . '...' : $descText;
          ?>
          <div class="col">
            <a href="view.php?id=<?php echo (int)$ad['id']; ?>" class="text-decoration-none text-reset">
              <div class="card h-100 shadow-sm">
                <div class="ratio ratio-4x3">
                  <img src="<?php echo $basePath; ?>/uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" class="card-img-top" style="object-fit:cover;" onerror="this.onerror=null;this.src='https://via.placeholder.com/800x600?text=Advert';">
                </div>
                <div class="card-body">
                  <?php if ((float)$ad['price'] > 0): ?>
                    <div class="text-success fw-bold mb-1">GHS <?php echo number_format((float)$ad['price'], 2); ?></div>
                  <?php endif; ?>
                  <h6 class="card-title mb-1"><?php echo htmlspecialchars($ad['title']); ?></h6>
                  <?php if ($short): ?><p class="card-text text-muted small mb-0"><?php echo htmlspecialchars($short); ?></p><?php endif; ?>
                </div>
              </div>
            </a>
          </div>
            <?php endforeach; ?>
          </div>

          <?php if ($pages > 1): ?>
          <nav class="mt-4" aria-label="Adverts pagination">
            <ul class="pagination justify-content-center">
              <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                <a class="page-link" href="?<?php echo $selectedCatId>0?('cat_id='.$selectedCatId.'&'):''; ?>page=<?php echo $page - 1; ?>" aria-label="Previous">&laquo;</a>
              </li>
              <?php for ($p = 1; $p <= $pages; $p++): ?>
                <li class="page-item <?php echo $p === $page ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo $selectedCatId>0?('cat_id='.$selectedCatId.'&'):''; ?>page=<?php echo $p; ?>"><?php echo $p; ?></a></li>
              <?php endfor; ?>
              <li class="page-item <?php echo $page >= $pages ? 'disabled' : ''; ?>">
                <a class="page-link" href="?<?php echo $selectedCatId>0?('cat_id='.$selectedCatId.'&'):''; ?>page=<?php echo $page + 1; ?>" aria-label="Next">&raquo;</a>
              </li>
            </ul>
          </nav>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
</section>

<footer class="py-4 bg-light border-top">
  <div class="container text-center small text-muted">&copy; <?php echo date('Y'); ?> GHAMECC</div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
