<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/seo.php';

$slug = $_GET['slug'] ?? '';
$stmt = db()->prepare('SELECT * FROM properties WHERE slug = ? LIMIT 1');
$stmt->execute([$slug]);
$property = $stmt->fetch();

if (!$property) {
    http_response_code(404);
    include __DIR__ . '/../404.php';
    exit;
}

$property = get_property_full($property);
$images = $property['images'];
$category = $property['category'];
$district = $property['district'];
$agent = $property['agent'];
$isLand = in_array($category['slug'] ?? '', ['residential-land', 'development-land', 'agricultural-land'], true);
$similar = get_similar_properties($property, 3);

$seo = [
    'title' => ($property['meta_title'] ?: $property['title']) . ' | ' . SITE_NAME,
    'description' => $property['meta_description'] ?: $property['short_description'],
    'path' => '/properties/' . $property['slug'],
    'image' => !empty($images) ? rtrim(SITE_URL, '/') . '/' . $images[0]['image_path'] : null,
    'type' => 'article',
];
$extraSchema = schema_property($property) . schema_breadcrumb([
    ['name' => 'Properties', 'url' => '/properties'],
    ['name' => $property['title'], 'url' => '/properties/' . $property['slug']],
]);

include __DIR__ . '/../includes/header.php';
$whatsappMsg = 'Hello! I am interested in "' . $property['title'] . '" (' . rtrim(SITE_URL, '/') . '/properties/' . $property['slug'] . '). Could you share more details?';
?>
<section class="section-pad-sm">
  <div class="container">
    <?= breadcrumb_html([
        ['name' => 'Properties', 'url' => '/properties'],
        ['name' => $property['title'], 'url' => '/properties/' . $property['slug']],
    ]) ?>

    <div class="flex items-center gap-3 mb-3">
      <span class="badge <?= $property['status'] === 'rent' ? 'badge-rent' : 'badge-sale' ?>"><?= $property['status'] === 'rent' ? 'For Rent' : 'For Sale' ?></span>
      <?php if ($property['is_featured']): ?><span class="badge badge-featured">Featured</span><?php endif; ?>
      <span class="badge badge-outline"><?= e($category['name'] ?? '') ?></span>
    </div>
    <h1 style="font-size:var(--fs-2xl);margin-bottom:var(--space-2);"><?= e($property['title']) ?></h1>
    <div class="loc text-muted mb-6"><?= icon('map-pin', 16) ?> <?= e($property['address']) ?></div>

    <div class="gallery-grid" data-gallery>
      <?php foreach (array_slice($images, 0, 5) as $i => $img): ?>
        <a href="#" data-full="/<?= e($img['image_path']) ?>">
          <div class="media-frame"><img src="/<?= e($img['image_path']) ?>" alt="<?= e($img['alt_text']) ?>" loading="<?= $i === 0 ? 'eager' : 'lazy' ?>" width="600" height="450"></div>
        </a>
      <?php endforeach; ?>
      <?php if (count($images) > 5): ?>
        <button class="btn btn-primary btn-sm view-all" onclick="document.querySelector('[data-gallery] a').click()"><?= icon('expand', 14) ?> View all <?= count($images) ?> photos</button>
      <?php endif; ?>
    </div>

    <div style="display:grid;grid-template-columns:1fr 380px;gap:var(--space-9);align-items:start;margin-top:var(--space-9);">
      <div>
        <div class="tabs-nav" data-tabs-group>
          <button class="active" data-tab="tab-overview">Overview</button>
          <button data-tab="tab-features">Features &amp; Amenities</button>
          <button data-tab="tab-location">Location &amp; Map</button>
          <?php if (!$isLand): ?><button data-tab="tab-calculators">Calculators</button><?php endif; ?>
        </div>

        <div id="tab-overview" class="tab-panel active">
          <div class="grid grid-4 mb-6" style="gap:var(--space-4);">
            <?php if (!$isLand): ?>
            <div class="text-center"><?= icon('bed', 22) ?><div class="fw-semibold mt-2"><?= (int)$property['bedrooms'] ?></div><div class="text-xs text-muted">Bedrooms</div></div>
            <div class="text-center"><?= icon('bath', 22) ?><div class="fw-semibold mt-2"><?= (int)$property['bathrooms'] ?></div><div class="text-xs text-muted">Bathrooms</div></div>
            <?php endif; ?>
            <?php if ($property['land_size_sqm']): ?>
            <div class="text-center"><?= icon('land', 22) ?><div class="fw-semibold mt-2"><?= (int)$property['land_size_sqm'] ?> m²</div><div class="text-xs text-muted">Land Size</div></div>
            <?php endif; ?>
            <?php if ($property['building_size_sqm']): ?>
            <div class="text-center"><?= icon('area', 22) ?><div class="fw-semibold mt-2"><?= (int)$property['building_size_sqm'] ?> m²</div><div class="text-xs text-muted">Building Size</div></div>
            <?php endif; ?>
          </div>
          <h3>Description</h3>
          <div class="article-body"><p><?= nl2br(e($property['description'])) ?></p></div>

          <?php if (!empty($property['video_url'])): ?>
            <h3 class="mt-6">Video Walkthrough</h3>
            <div class="media-frame aspect-video rounded-lg"><iframe src="<?= e($property['video_url']) ?>" title="Property video walkthrough" allowfullscreen loading="lazy"></iframe></div>
          <?php endif; ?>

          <h3 class="mt-6">Investment Score</h3>
          <div class="flex items-center gap-5">
            <div class="score-ring">
              <svg width="84" height="84" viewBox="0 0 84 84">
                <circle class="track" cx="42" cy="42" r="36" stroke-width="7"/>
                <circle class="value" cx="42" cy="42" r="36" stroke-width="7" stroke-dasharray="226" stroke-dashoffset="<?= 226 - (226 * $property['investment_score'] / 100) ?>"/>
              </svg>
              <span class="num"><?= (int)$property['investment_score'] ?></span>
            </div>
            <p class="text-muted" style="max-width:40ch;margin:0;">Our score blends location growth trends, rental yield potential, infrastructure proximity and title documentation quality.</p>
          </div>
        </div>

        <div id="tab-features" class="tab-panel">
          <h3>Features</h3>
          <ul class="feature-grid mb-6">
            <?php foreach ($property['features'] as $f): ?><li><?= icon('check', 16) ?> <?= e($f) ?></li><?php endforeach; ?>
          </ul>
          <h3>Amenities &amp; Security</h3>
          <ul class="feature-grid">
            <?php foreach ($property['amenities'] as $a): ?><li><?= icon('shield', 16) ?> <?= e($a) ?></li><?php endforeach; ?>
          </ul>
        </div>

        <div id="tab-location" class="tab-panel">
          <h3>Location</h3>
          <p class="text-muted mb-4"><?= e($property['address']) ?> — <?= e($district['name'] ?? '') ?> district. <?= e($district['summary'] ?? '') ?></p>
          <div class="map-frame">
            <?php if (GOOGLE_MAPS_API_KEY): ?>
              <iframe src="https://www.google.com/maps/embed/v1/view?key=<?= e(GOOGLE_MAPS_API_KEY) ?>&center=<?= $property['lat'] ?>,<?= $property['lng'] ?>&zoom=15" loading="lazy" allowfullscreen title="Property location map"></iframe>
            <?php else: ?>
              <iframe src="https://maps.google.com/maps?q=<?= $property['lat'] ?>,<?= $property['lng'] ?>&z=15&output=embed" loading="lazy" title="Property location map"></iframe>
            <?php endif; ?>
          </div>
          <h4 class="mt-6">Nearby</h4>
          <ul class="feature-grid">
            <li><?= icon('building', 16) ?> Schools &amp; nurseries within 10 minutes</li>
            <li><?= icon('building', 16) ?> Shopping &amp; supermarkets nearby</li>
            <li><?= icon('building', 16) ?> Hospitals &amp; clinics within reach</li>
            <li><?= icon('building', 16) ?> Main road access</li>
          </ul>
        </div>

        <?php if (!$isLand): ?>
        <div id="tab-calculators" class="tab-panel">
          <div class="grid grid-2">
            <div class="calc-card" data-mortgage-calc data-price="<?= (float)$property['price'] ?>">
              <h4><?= icon('calculator', 18) ?> Mortgage Calculator</h4>
              <div class="field mt-4">
                <div class="slider-row"><span>Down Payment</span><span data-out="down_payment_pct">20%</span></div>
                <input type="range" name="down_payment_pct" min="10" max="50" value="20" step="5">
              </div>
              <div class="field">
                <div class="slider-row"><span>Interest Rate</span><span data-out="interest_rate">16%</span></div>
                <input type="range" name="interest_rate" min="10" max="22" value="16" step="0.5">
              </div>
              <div class="field">
                <div class="slider-row"><span>Loan Term</span><span data-out="loan_term">15 yrs</span></div>
                <input type="range" name="loan_term" min="5" max="20" value="15" step="1">
              </div>
              <div class="calc-result">
                <div class="text-xs" style="color:var(--color-fog);">Estimated Monthly Payment</div>
                <div class="amount" data-result="monthly">RWF 0</div>
                <div class="text-xs mt-2" style="color:var(--color-fog);">Loan principal: <span data-result="principal">RWF 0</span></div>
              </div>
              <p class="text-xs text-muted mt-3">Estimate only — actual rates depend on your bank's underwriting. See our <a href="/blog/mortgage-financing-guide-rwanda">mortgage financing guide</a>.</p>
            </div>

            <div class="calc-card" data-roi-calc data-price="<?= (float)$property['price'] ?>">
              <h4><?= icon('trending-up', 18) ?> ROI Calculator</h4>
              <div class="field mt-4">
                <label>Expected Monthly Rent (RWF)</label>
                <input type="number" name="monthly_rent" value="<?= (int)($property['estimated_rent'] ?: round($property['price'] * 0.005)) ?>">
              </div>
              <div class="field">
                <label>Annual Expenses (% of rent)</label>
                <input type="number" name="annual_expense_pct" value="15">
              </div>
              <div class="calc-result">
                <div class="text-xs" style="color:var(--color-fog);">Estimated Gross Rental Yield</div>
                <div class="amount" data-result="yield">0%</div>
                <div class="text-xs mt-2" style="color:var(--color-fog);">Net annual income: <span data-result="net_annual">RWF 0</span></div>
              </div>
            </div>
          </div>
        </div>
        <?php endif; ?>
      </div>

      <aside class="sticky-cta reveal">
        <div class="price-block">
          <div class="price" style="font-size:var(--fs-xl);"><?= format_price((float)$property['price'], $property['currency'], $property['price_period']) ?></div>
          <div class="text-muted text-sm mt-1"><?= e($category['name'] ?? '') ?> · <?= e($district['name'] ?? '') ?></div>
        </div>
        <?php if ($agent): ?>
        <div class="agent-mini">
          <?= avatar_html($agent['name'], 'md', $agent['photo']) ?>
          <div>
            <div class="fw-semibold"><?= e($agent['name']) ?></div>
            <div class="text-xs text-muted"><?= e($agent['title']) ?></div>
          </div>
        </div>
        <?php endif; ?>
        <div class="cta-stack">
          <a href="<?= e(whatsapp_link($whatsappMsg)) ?>" class="btn btn-whatsapp btn-block" target="_blank" rel="noopener"><?= icon('whatsapp', 16) ?> WhatsApp Us</a>
          <a href="<?= e(tel_link()) ?>" class="btn btn-primary btn-block"><?= icon('phone', 16) ?> Call Now</a>
          <a href="/schedule-tour?property=<?= (int)$property['id'] ?>" class="btn btn-accent btn-block"><?= icon('calendar', 16) ?> Schedule a Tour</a>
          <a href="/contact?property=<?= (int)$property['id'] ?>" class="btn btn-outline btn-block">Contact Agent</a>
          <button class="btn btn-ghost compare-toggle" data-id="<?= (int)$property['id'] ?>">Add to Compare</button>
        </div>
      </aside>
    </div>

    <?php if (!empty($similar)): ?>
    <div class="section-pad">
      <h2>Similar Properties</h2>
      <div class="grid grid-3">
        <?php foreach ($similar as $p): ?>
          <?php include __DIR__ . '/../includes/partials/property-card.php'; ?>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
</section>

<div class="lightbox">
  <button class="lb-close" aria-label="Close gallery"><?= icon('close', 20) ?></button>
  <button class="lb-prev" aria-label="Previous photo"><?= icon('chevron-right', 20) ?></button>
  <img src="" alt="Property photo">
  <button class="lb-next" aria-label="Next photo"><?= icon('chevron-right', 20) ?></button>
  <div class="lb-counter"></div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
