<?php
require_once __DIR__ . '/../includes/config.php';
$db = getDB();

$slug = $_GET['slug'] ?? '';
$id   = $_GET['id'] ?? '';

if (empty($slug) && empty($id)) {
    $rawUri = $_SERVER['REQUEST_URI'] ?? '';
    $path   = parse_url($rawUri, PHP_URL_PATH) ?? '';
    if (preg_match('#/(?:pages/)?article/([^/?]+)#i', $path, $m)) {
        $slug = urldecode($m[1]);
    }
}

$article = null;

if (!empty($slug)) {
    try {
        $stmt = $db->prepare("SELECT * FROM articles WHERE slug = ? AND status = 'publie'");
        $stmt->execute([$slug]);
        $article = $stmt->fetch();
        if (!$article) {
            // Try like query for minor slug mismatches
            $stmt = $db->prepare("SELECT * FROM articles WHERE slug LIKE ? AND status = 'publie'");
            $stmt->execute(['%' . $slug . '%']);
            $article = $stmt->fetch();
        }
    } catch (Exception $e) {}
} elseif (!empty($id)) {
    try {
        $stmt = $db->prepare("SELECT * FROM articles WHERE id = ? AND status = 'publie'");
        $stmt->execute([(int)$id]);
        $article = $stmt->fetch();
    } catch (Exception $e) {}
}

// Fallback demo articles if DB row missing
if (!$article) {
    $fallbackArticles = [
        'le-marche-immobilier-de-prestige-a-sidi-rahal-casablanca-en-2025' => [
            'id' => 1,
            'slug' => 'le-marche-immobilier-de-prestige-a-sidi-rahal-casablanca-en-2025',
            'title' => 'Le marché immobilier de prestige à Sidi Rahal Casablanca en 2025',
            'category' => 'Marché Immobilier',
            'excerpt' => 'Analyse approfondie des tendances, de la valorisation du littoral et des opportunités d\'investissement dans la région de Sidi Rahal Casablanca.',
            'content' => '<p class="mb-6">Le marché immobilier d\'exception à <strong>Sidi Rahal Casablanca</strong> connaît une dynamique sans précédent. Porté par le développement d\'infrastructures routières modernes et l\'attrait grandissant pour le littoral casablancais, le secteur haut de gamme attire aussi bien des acquéreurs résidents que des investisseurs internationaux.</p><p class="mb-6">Les villas pieds dans l\'eau et les résidences fermées sécurisées avec vue panoramique sur l\'Atlantique affichent une croissance constante de leur valeur patrimoniale. La demande pour des espaces généreux, alliant élégance architecturale et prestations de standing (piscines privatives, domotique, jardins paysagers), n\'a jamais été aussi soutenue.</p><h3 class="font-serif text-2xl font-light text-black mt-8 mb-4">Pourquoi investir à Sidi Rahal Casablanca ?</h3><p class="mb-6">Située à proximité immédiate du cœur économique de Casablanca, la frange maritime de Sidi Rahal offre un cadre de vie idéal entre sérénité marine et accessibilité urbaine. La rareté du foncier d\'exception garantit une appréciation pérenne sur le long terme.</p>',
            'image_path' => 'assets/img/project-1.jpg',
            'author' => 'Imad Ajouamai',
            'created_at' => '2025-05-15'
        ]
    ];
    $article = $fallbackArticles[$slug] ?? reset($fallbackArticles);
}

// Fetch related articles
try {
    $stmtRelated = $db->prepare("SELECT * FROM articles WHERE slug != ? AND status = 'publie' ORDER BY RAND() LIMIT 3");
    $stmtRelated->execute([$article['slug']]);
    $relatedArticles = $stmtRelated->fetchAll();
} catch (Exception $e) {
    $relatedArticles = [];
}

$headerStyle = 'solid';
$currentPage = 'articles';
?>
<!DOCTYPE html>
<html lang="fr" class="scroll-smooth">
<head>
  <?= renderHead(htmlspecialchars($article['title']) . ' — AJOUAMAI IMMO-BUSINESS', htmlspecialchars($article['excerpt'] ?? '')) ?>
</head>
<body class="bg-offwhite text-dark font-sans">
<?php include __DIR__ . '/../components/header.php'; ?>

<!-- BIG TITLE HEADER SECTION FIRST -->
<section class="pt-32 pb-12 bg-white border-b border-gray-200/70">
  <div class="max-w-4xl mx-auto px-6 text-center reveal-scale">
    <div class="flex items-center justify-center gap-3 mb-4">
      <span class="bg-gold text-white text-[10px] tracking-[0.25em] uppercase font-sans px-3 py-1 font-semibold">
        <?= htmlspecialchars($article['category'] ?? $article['cat'] ?? 'Actualité') ?>
      </span>
      <span class="text-xs text-gray-400 font-sans tracking-widest uppercase">
        <?= date('d/m/Y', strtotime($article['created_at'] ?? 'now')) ?>
      </span>
    </div>
    
    <h1 class="font-serif text-3xl sm:text-5xl md:text-6xl font-light text-black tracking-tight leading-tight mb-6">
      <?= htmlspecialchars($article['title']) ?>
    </h1>

    <div class="flex items-center justify-center gap-4 text-xs font-sans text-gray-500 uppercase tracking-widest">
      <span>Par <strong class="text-black font-medium"><?= htmlspecialchars($article['author'] ?? 'Équipe AJOUAMAI') ?></strong></span>
      <span>•</span>
      <span>Sidi Rahal Casablanca</span>
    </div>
  </div>
</section>

<!-- AUTOMATIC HERO SLIDER / MAIN IMAGE SECTION (AFTER BIG TITLE) -->
<section class="py-10 max-w-5xl mx-auto px-6">
  <div class="w-full h-[45vh] sm:h-[60vh] overflow-hidden relative rounded-xs shadow-xl group">
    <img src="<?= htmlspecialchars(resolveAssetUrl($article['image_path'] ?? $article['img'] ?? 'assets/img/project-1.jpg')) ?>" class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-102" alt="<?= htmlspecialchars($article['title']) ?>" />
    <div class="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"></div>
    <div class="absolute bottom-6 left-6 right-6 text-white text-xs font-sans font-light tracking-wide bg-black/60 backdrop-blur-md p-4 border border-white/10 max-w-xl">
      <?= htmlspecialchars($article['excerpt'] ?? '') ?>
    </div>
  </div>
</section>

<!-- ARTICLE ARTICLE BODY & CONTENT -->
<section class="py-12 bg-white border-b border-gray-100">
  <div class="max-w-3xl mx-auto px-6">
    <!-- Excerpt Lead -->
    <?php if(!empty($article['excerpt'])): ?>
      <div class="text-lg font-serif italic text-gray-700 border-l-2 border-gold pl-6 py-2 mb-10 leading-relaxed bg-offwhite/50">
        <?= htmlspecialchars($article['excerpt']) ?>
      </div>
    <?php endif; ?>

    <!-- Main Content -->
    <div class="prose-editorial font-sans text-gray-800 leading-relaxed text-base sm:text-lg mb-16">
      <?= $article['content'] ?? nl2br(htmlspecialchars($article['excerpt'])) ?>
    </div>

    <!-- Author Bio Signature Card -->
    <div class="p-8 bg-offwhite border border-gray-200/80 rounded-xs flex flex-col sm:flex-row items-center gap-6 mb-16 shadow-xs">
      <div class="w-16 h-16 rounded-full bg-gold text-white font-serif text-2xl flex items-center justify-center flex-shrink-0 uppercase font-light">
        <?= substr($article['author'] ?? 'A', 0, 1) ?>
      </div>
      <div class="text-center sm:text-left">
        <p class="text-[10px] tracking-[0.25em] uppercase font-sans text-gold font-semibold mb-1">RÉDACTION ÉDITORIALE</p>
        <h4 class="font-serif text-xl font-light text-black mb-1"><?= htmlspecialchars($article['author'] ?? 'Équipe AJOUAMAI') ?></h4>
        <p class="text-xs text-gray-500 font-sans font-light">Conseiller Spécialiste de l'Immobilier de Prestige à Sidi Rahal Casablanca.</p>
      </div>
    </div>

    <!-- Back to Articles Button -->
    <div class="text-center">
      <a href="<?= SITE_URL ?>/pages/articles.php" class="btn-lemonde-consultation inline-flex">
        <span>← Retour au Journal Immobilier</span>
      </a>
    </div>
  </div>
</section>

<!-- RELATED ARTICLES -->
<?php if (!empty($relatedArticles)): ?>
<section class="py-20 bg-offwhite">
  <div class="max-w-7xl mx-auto px-6">
    <div class="flex items-center justify-between mb-12 border-b border-gray-200 pb-4">
      <h3 class="font-serif text-2xl sm:text-3xl font-light text-black">À lire également</h3>
      <a href="<?= SITE_URL ?>/pages/articles.php" class="text-xs text-gold uppercase tracking-widest hover:text-black transition-colors font-sans">Voir tous les articles →</a>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
      <?php foreach($relatedArticles as $rel): ?>
        <a href="<?= SITE_URL ?>/pages/article.php?slug=<?= htmlspecialchars($rel['slug']) ?>" class="group bg-white border border-gray-200 p-6 hover:border-gold transition-all duration-300 shadow-xs flex flex-col justify-between">
          <div>
            <span class="text-[9px] tracking-[0.2em] uppercase font-sans text-gold font-semibold block mb-2"><?= htmlspecialchars($rel['category']) ?></span>
            <h4 class="font-serif text-xl font-light text-black group-hover:text-gold transition-colors mb-3 line-clamp-2"><?= htmlspecialchars($rel['title']) ?></h4>
            <p class="text-xs text-gray-500 font-sans font-light line-clamp-2 mb-4"><?= htmlspecialchars($rel['excerpt']) ?></p>
          </div>
          <span class="text-[10px] tracking-[0.2em] uppercase font-sans text-black group-hover:text-gold font-medium">Lire l'article →</span>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<?php include __DIR__ . '/../components/footer.php'; ?>
<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
</body>
</html>
