<?php
require_once "config.php";

if(!isset($_GET['id']) || empty($_GET['id'])){
    header("Location: index.php");
    exit;
}

$id = intval($_GET['id']);

// Fetch property and agent info
$res = $conn->query("
    SELECT p.*, 
    (SELECT GROUP_CONCAT(image_path SEPARATOR ',') FROM property_images WHERE property_id = p.id) AS images,
    u.first_name, u.last_name, u.phone
    FROM properties p
    LEFT JOIN users u ON p.user_id = u.id
    WHERE p.id = $id
");

if($res->num_rows === 0){
    echo "<p class='text-center mt-5'>Property not found.</p>";
    exit;
}

$prop = $res->fetch_assoc();
$images = explode(',', $prop['images']);
$badge = $prop['type'] === 'sale' ? 'Sale' : 'Rental';

// Fetch active adverts for property_details
$adverts_res = $conn->query("
    SELECT * FROM adverts
    WHERE status='active'
      AND location='property_details'
    ORDER BY created_at DESC
");
$adverts = [];
if($adverts_res && $adverts_res->num_rows > 0){
    while($adv = $adverts_res->fetch_assoc()){
        $adverts[] = $adv;
    }
}
?>

<!-- Bootstrap CSS & Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">


<?php if(!empty($adverts)): ?>
<section class="container py-5">
  <h4 class="mb-4 text-center">Sponsored Adverts</h4>

  <div id="advertsCarousel" class="carousel slide" data-bs-ride="carousel">
    <div class="carousel-inner">
      <?php foreach($adverts as $index => $adv): 
        $adv_res = $conn->query("SELECT * FROM properties WHERE id={$adv['property_id']}");
        $adv_prop = $adv_res->fetch_assoc();
        $img_res = $conn->query("SELECT image_path FROM property_images WHERE property_id={$adv['property_id']} LIMIT 1");
        $img = ($img_res && $img_res->num_rows > 0) ? $img_res->fetch_assoc()['image_path'] : 'placeholder.jpg';
        $adv_type = ucfirst($adv_prop['type']);
        $adv_price = $adv_prop['type']==='rent' ? $adv_prop['total_package'] : $adv_prop['price'];
        $adv_desc = substr($adv_prop['description'],0,60).'...';
        $adv_location = $adv_prop['location'];
        $badge = $adv_prop['type'] === 'sale' ? 'Sale' : 'Rental';
      ?>
        <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>">
          <div class="card shadow-sm mx-auto position-relative" style="max-width: 350px;">
            <span class="badge bg-success position-absolute top-0 start-0 m-3 px-3 py-2 fs-6"><?= $badge ?></span>
            <img src="<?= htmlspecialchars($img) ?>" class="card-img-top" style="height:200px; object-fit:cover;" alt="Advert">
            <div class="card-body d-flex flex-column justify-content-between">
              <div>
                <h6 class="card-title"><?= htmlspecialchars($adv_type) ?></h6>
                <p class="mb-1"><strong>Price:</strong> ₦<?= number_format($adv_price) ?></p>
                <p class="card-text"><?= htmlspecialchars($adv_desc) ?></p>
                <p class="mb-2"><strong>Location:</strong> <?= htmlspecialchars($adv_location) ?></p>
              </div>
              <a href="view_details.php?id=<?= $adv_prop['id'] ?>" class="btn btn-primary mt-2">View Details</a>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <?php if(count($adverts) > 1): ?>
      <button class="carousel-control-prev" type="button" data-bs-target="#advertsCarousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon bg-dark rounded-circle p-3"></span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#advertsCarousel" data-bs-slide="next">
        <span class="carousel-control-next-icon bg-dark rounded-circle p-3"></span>
      </button>
    <?php endif; ?>
  </div>
</section>

<script>
// Initialize adverts carousel once
new bootstrap.Carousel(document.querySelector('#advertsCarousel'), {
  interval: 4000, // 4 seconds
  ride: 'carousel',
  pause: 'hover'
});
</script>
<?php endif; ?>

<section class="container py-5">
  <a href="index.php" class="btn btn-outline-secondary mb-4"><i class="bi bi-arrow-left"></i> Back to Listings</a>

  <div class="card shadow-lg rounded-4 overflow-hidden border-0 property-card">
    <!-- Property Carousel -->
    <div class="position-relative">
      <div id="propertyCarousel" class="carousel slide" data-bs-ride="carousel">
        <div class="carousel-inner">
          <?php foreach($images as $i => $img): ?>
            <div class="carousel-item <?= $i===0?'active':'' ?>">
              <img src="<?= htmlspecialchars($img) ?>" class="d-block w-100 carousel-img" alt="Property Image">
            </div>
          <?php endforeach; ?>
        </div>
        <?php if(count($images) > 1): ?>
          <button class="carousel-control-prev" type="button" data-bs-target="#propertyCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
          </button>
          <button class="carousel-control-next" type="button" data-bs-target="#propertyCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
          </button>
        <?php endif; ?>
      </div>

      <!-- Badge -->
      <span class="badge <?= $prop['type']==='sale'?'bg-success':'bg-info' ?> property-badge">
        <?= ucfirst($prop['type']) ?>
      </span>
    </div>

    <!-- Property Details -->
    <div class="card-body p-4">
      <h2 class="card-title fw-bold mb-3"><?= htmlspecialchars($prop['title']) ?></h2>
      <p class="card-text mb-4"><?= nl2br(htmlspecialchars($prop['description'])) ?></p>

      <div class="row mb-4">
        <?php if($prop['type']==='sale'): ?>
          <div class="col-md-4 col-sm-6 mb-2"><strong>Price:</strong> ₦<?= number_format($prop['price']) ?></div>
        <?php else: ?>
          <?php if(!empty($prop['monthly_fee'])): ?>
            <div class="col-md-4 col-sm-6 mb-2"><strong>Monthly Fee:</strong> ₦<?= number_format($prop['monthly_fee']) ?></div>
          <?php endif; ?>
          <?php if(!empty($prop['yearly_fee'])): ?>
            <div class="col-md-4 col-sm-6 mb-2"><strong>Yearly Fee:</strong> ₦<?= number_format($prop['yearly_fee']) ?></div>
          <?php endif; ?>
          <?php $agency_total = ($prop['agency_fee'] ?? 0) + ($prop['other_fees'] ?? 0); ?>
          <?php if($agency_total > 0): ?>
            <div class="col-md-4 col-sm-6 mb-2"><strong>Agency/Other Fees:</strong> ₦<?= number_format($agency_total) ?></div>
          <?php endif; ?>
          <?php if(!empty($prop['total_package'])): ?>
            <div class="col-md-4 col-sm-6 mb-2"><strong>Total Package:</strong> ₦<?= number_format($prop['total_package']) ?></div>
          <?php endif; ?>
        <?php endif; ?>
        <div class="col-md-4 col-sm-6 mb-2"><strong>Location:</strong> <?= htmlspecialchars($prop['location']) ?></div>
        <div class="col-md-4 col-sm-6 mb-2"><strong>Type:</strong> <?= ucfirst($prop['type']) ?></div>
      </div>

      <!-- Contact Seller -->
      <div class="text-center">
        <button id="contactSellerBtn" class="btn btn-primary btn-lg contact-btn">
          <i class="bi bi-telephone-fill"></i> Contact Seller
        </button>
        <p id="sellerPhone" class="mt-3 fs-5 seller-phone" style="display:none;">
          <strong>Phone:</strong> <?= htmlspecialchars($prop['phone']) ?>
        </p>
      </div>
    </div>
  </div>
</section>

<style>
.property-card {
  transition: transform 0.3s, box-shadow 0.3s;
}
.property-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0,0,0,0.2);
}

.carousel-img {
  height: 400px;
  object-fit: cover;
  border-bottom: 2px solid #f1f1f1;
}

.property-badge {
  position: absolute;
  top: 15px;
  right: 15px;
  padding: 0.5rem 1rem;
  font-size: 1rem;
  font-weight: 600;
  text-transform: uppercase;
  box-shadow: 0 3px 8px rgba(0,0,0,0.2);
}

.contact-btn {
  padding: 0.75rem 2rem;
  font-size: 1.2rem;
  transition: transform 0.3s, box-shadow 0.3s;
}
.contact-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 20px rgba(0,0,0,0.3);
}

.seller-phone {
  color: #0d6efd;
  font-weight: 600;
}
</style>

<script>
document.getElementById('contactSellerBtn').addEventListener('click', () => {
  const phoneEl = document.getElementById('sellerPhone');
  phoneEl.style.display = phoneEl.style.display === 'none' ? 'block' : 'none';
});
</script>


<script>
// Show seller phone on button click
document.getElementById('contactSellerBtn').addEventListener('click', function(){
    document.getElementById('sellerPhone').style.display = 'block';
    this.style.display = 'none';
});
</script>





<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
