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

$basePath = '..';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    header('Location: list.php');
    exit;
}

$ad = fetchRow("SELECT * FROM ads WHERE id = ? AND status='approved' AND (starts_at IS NULL OR starts_at <= NOW()) AND (ends_at IS NULL OR ends_at >= NOW())", [$id]);

$isPreview = false;
if (!$ad) {
    if (isLoggedIn()) {
        $adCandidate = fetchRow("SELECT * FROM ads WHERE id = ?", [$id]);
        if ($adCandidate) {
            $canPreview = ($adCandidate['created_by'] == $_SESSION['user_id']) || hasRole([
                'admin',
                'diocesan_chairman','diocese_chairman',
                'diocesan_secretary','diocese_secretary',
                'diocesan_treasurer','diocese_treasurer',
                'diocesan_dom','diocese_dom',
                'diocesan_music_director','diocese_music_director'
            ]);
            if ($canPreview) {
                $ad = $adCandidate;
                $isPreview = true;
            }
        }
    }
    if (!$ad) {
        http_response_code(404);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $ad ? htmlspecialchars($ad['title']) . ' - ' : ''; ?>Member Advert - 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>
        <li class="nav-item"><a class="nav-link" href="<?php echo $basePath; ?>/ads/list.php">All adverts</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">
    <?php if (!$ad): ?>
      <div class="alert alert-warning">This advert is not available.</div>
      <a href="list.php" class="btn btn-secondary">Back to list</a>
    <?php else: ?>
      <div class="row g-4">
        <div class="col-md-7">
          <div class="card">
            <div class="ratio ratio-4x3">
              <img src="<?php echo $basePath; ?>/uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($ad['title']); ?>" style="object-fit:cover;" onerror="this.onerror=null;this.src='https://via.placeholder.com/800x600?text=Advert';">
            </div>
          </div>
        </div>
        <div class="col-md-5">
          <div class="card h-100">
            <div class="card-body">
              <?php if ($isPreview): ?>
                <div class="alert alert-info py-2">Preview – not yet public. Status: <?php echo htmlspecialchars($ad['status']); ?>.</div>
              <?php endif; ?>
              <?php if ((float)$ad['price'] > 0): ?>
                <div class="text-success fw-bold">GHS <?php echo number_format((float)$ad['price'], 2); ?></div>
              <?php endif; ?>
              <h1 class="h4 mt-2 mb-3"><?php echo htmlspecialchars($ad['title']); ?></h1>
              <?php if (!empty($ad['description'])): ?>
                <div class="mb-3" style="white-space:pre-wrap;">
                  <?php echo nl2br(htmlspecialchars($ad['description'])); ?>
                </div>
              <?php endif; ?>

              <ul class="list-unstyled small text-muted mb-3">
                <li><i class="far fa-clock me-2"></i>Posted on <?php echo date('M d, Y', strtotime($ad['created_at'])); ?></li>
              </ul>

              <?php if (!empty($ad['link_url'])): ?>
                <a href="<?php echo htmlspecialchars($ad['link_url']); ?>" target="_blank" rel="noopener" class="btn btn-primary mb-2">
                  <i class="fas fa-external-link-alt me-1"></i> Visit link
                </a>
              <?php endif; ?>

              <?php if (!empty($ad['contact_phone'])): ?>
                <div class="mt-2">
                  <i class="fas fa-phone me-2"></i>
                  <span><?php echo htmlspecialchars($ad['contact_phone']); ?></span>
                </div>
              <?php endif; ?>

              <div class="mt-3">
                <a href="list.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i> Back to list</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    <?php endif; ?>
  </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>
