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

// Lightweight visit counter for the admin dashboard "Website Visits" card
try {
    $db = Database::getConnection();
    $ipHash = hash('sha256', ($_SERVER['REMOTE_ADDR'] ?? '') . date('Y-m-d'));
    $stmt = $db->prepare('INSERT IGNORE INTO site_visits (visited_at, ip_hash) VALUES (CURDATE(), ?)');
    $stmt->execute([$ipHash]);
} catch (Throwable $e) {
    error_log('Visit counter failed: ' . $e->getMessage());
}

$settings = get_settings();
$services = json_decode($settings['services'] ?? '[]', true) ?: [];
$pageTitle = $settings['site_name'] ?? APP_NAME;

$processSteps = $db->query('SELECT * FROM process_steps WHERE is_active = 1 ORDER BY display_order ASC')->fetchAll();
$benefits     = $db->query('SELECT * FROM benefits WHERE is_active = 1 ORDER BY display_order ASC')->fetchAll();
$testimonials = $db->query('SELECT * FROM testimonials WHERE is_active = 1 ORDER BY display_order ASC')->fetchAll();
$locations    = $db->query('SELECT * FROM locations WHERE is_active = 1 ORDER BY display_order ASC')->fetchAll();

$blocksStmt = $db->query('SELECT * FROM homepage_blocks WHERE is_active = 1 ORDER BY position ASC, display_order ASC');
$allBlocks = $blocksStmt->fetchAll();
$blocksByZone = ['top' => [], 'middle' => [], 'bottom' => []];
foreach ($allBlocks as $block) {
    $blocksByZone[$block['position']][] = $block;
}

function render_homepage_blocks(array $blocks): void
{
    foreach ($blocks as $block) {
        echo '<div class="container py-4">';
        if (!empty($block['title'])) {
            echo '<h2 class="h4 text-center mb-3 font-serif">' . e($block['title']) . '</h2>';
        }
        if ($block['block_type'] === 'image' && !empty($block['image'])) {
            echo '<div class="text-center"><img src="/uploads/logos/' . e($block['image']) . '" alt="' . e($block['image_alt'] ?? '') . '" class="img-fluid rounded"></div>';
        } elseif ($block['block_type'] === 'text' && !empty($block['body'])) {
            echo '<p class="col-lg-8 mx-auto text-center">' . nl2br(e($block['body'])) . '</p>';
        }
        echo '</div>';
    }
}

require __DIR__ . '/includes/header.php';
?>

<!-- HERO -->
<section class="hero-navy py-5" style="<?= !empty($settings['hero_image']) ? 'background-image:linear-gradient(rgba(10,26,51,.75),rgba(10,26,51,.75)), url(/uploads/logos/' . e($settings['hero_image']) . ');' : '' ?>">
  <div class="container text-center py-5">
    <p class="eyebrow">The Security Standard</p>
    <h1 class="display-4 font-serif fw-bold text-white"><?= e($settings['hero_title'] ?? 'Welcome') ?></h1>
    <p class="lead col-lg-8 mx-auto text-white-50"><?= e($settings['hero_description'] ?? '') ?></p>
    <?php if (!empty($settings['hero_button_text'])): ?>
      <a href="<?= e($settings['hero_button_link'] ?? '#') ?>" class="btn btn-light btn-lg mt-3 fw-semibold"><?= e($settings['hero_button_text']) ?> &rarr;</a>
    <?php endif; ?>
  </div>
</section>

<?php render_homepage_blocks($blocksByZone['top']); ?>

<!-- SERVICES -->
<section id="services" class="py-5">
  <div class="container">
    <p class="eyebrow text-center">What We Offer</p>
    <h2 class="text-center font-serif mb-5">Our Services</h2>
    <div class="row g-4">
      <?php foreach ($services as $service): ?>
        <div class="col-md-4">
          <div class="card h-100 border-0 shadow-sm">
            <div class="card-body">
              <h5 class="card-title font-serif"><?= e($service['title'] ?? '') ?></h5>
              <p class="card-text text-muted"><?= e($service['description'] ?? '') ?></p>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
      <?php if (empty($services)): ?>
        <p class="text-center text-muted">Services will appear here once configured in the admin panel.</p>
      <?php endif; ?>
    </div>
  </div>
</section>

<!-- HOW IT WORKS -->
<?php if ($processSteps): ?>
<section class="py-5 bg-navy text-white">
  <div class="container">
    <p class="eyebrow text-center">Methodology</p>
    <h2 class="text-center font-serif mb-5">How It Works</h2>
    <div class="row g-4">
      <?php foreach ($processSteps as $i => $step): ?>
        <div class="col-md-3">
          <div class="step-number"><?= str_pad((string) ($i + 1), 2, '0', STR_PAD_LEFT) ?></div>
          <h5 class="font-serif"><?= e($step['title']) ?></h5>
          <p class="text-white-50 small"><?= e((string) $step['description']) ?></p>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<?php render_homepage_blocks($blocksByZone['middle']); ?>

<!-- ABOUT -->
<section class="py-5">
  <div class="container">
    <div class="row align-items-center g-5">
      <div class="col-lg-6">
        <p class="eyebrow">About Us</p>
        <h2 class="font-serif mb-3">The Architecture of Protection</h2>
        <p class="text-muted"><?= nl2br(e($settings['about_content'] ?? '')) ?></p>
      </div>
    </div>
  </div>
</section>

<!-- WHY CHOOSE US -->
<?php if ($benefits): ?>
<section class="py-5 bg-light">
  <div class="container">
    <p class="eyebrow text-center">Why Choose Us</p>
    <h2 class="text-center font-serif mb-5">Engineered for Absolute Defense</h2>
    <div class="row g-4">
      <?php foreach ($benefits as $benefit): ?>
        <div class="col-md-6 col-lg-3">
          <div class="card h-100 border-0 shadow-sm">
            <div class="card-body">
              <div class="benefit-icon"><i class="bi <?= e($benefit['icon'] ?: 'bi-check-circle') ?>"></i></div>
              <h5 class="font-serif mt-3"><?= e($benefit['title']) ?></h5>
              <p class="text-muted small"><?= e((string) $benefit['description']) ?></p>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<!-- TESTIMONIALS -->
<?php if ($testimonials): ?>
<section class="py-5">
  <div class="container">
    <p class="eyebrow text-center">Client Assurance</p>
    <h2 class="text-center font-serif mb-5">Trusted by Institutions and Individuals</h2>
    <div class="row g-4">
      <?php foreach ($testimonials as $t): ?>
        <div class="col-md-6 col-lg-4">
          <div class="card h-100 border-0 shadow-sm">
            <div class="card-body">
              <p class="fst-italic">"<?= e($t['quote']) ?>"</p>
              <hr>
              <div class="d-flex align-items-center gap-2">
                <?php if ($t['photo']): ?><img src="/uploads/profiles/<?= e($t['photo']) ?>" class="rounded-circle" width="44" height="44" style="object-fit:cover;"><?php endif; ?>
                <div>
                  <strong class="d-block"><?= e($t['author_name']) ?></strong>
                  <span class="text-muted small"><?= e((string) $t['author_company']) ?></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<!-- LOCATIONS -->
<?php if ($locations): ?>
<section class="py-5 bg-light">
  <div class="container">
    <p class="eyebrow text-center">Where We Operate</p>
    <h2 class="text-center font-serif mb-5">Locations Served</h2>
    <div class="row g-4">
      <?php foreach ($locations as $loc): ?>
        <div class="col-md-6 col-lg-4">
          <div class="card h-100 border-0 shadow-sm">
            <div class="card-body">
              <?php if ($loc['flag_emoji']): ?><div class="fs-2 mb-2"><?= e($loc['flag_emoji']) ?></div><?php endif; ?>
              <h5 class="font-serif"><?= e($loc['region_name']) ?></h5>
              <?php if ($loc['address']): ?><p class="text-muted small mb-1"><i class="bi bi-geo-alt"></i> <?= nl2br(e($loc['address'])) ?></p><?php endif; ?>
              <?php if ($loc['phone']): ?><p class="text-muted small mb-0"><i class="bi bi-telephone"></i> <?= e($loc['phone']) ?></p><?php endif; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<?php render_homepage_blocks($blocksByZone['bottom']); ?>

<!-- CALL TO ACTION -->
<?php if (!empty($settings['cta_title'])): ?>
<section class="py-5 bg-navy text-white text-center">
  <div class="container">
    <h2 class="font-serif mb-3"><?= e($settings['cta_title']) ?></h2>
    <p class="col-lg-7 mx-auto text-white-50"><?= e($settings['cta_description'] ?? '') ?></p>
    <?php if (!empty($settings['cta_button_text'])): ?>
      <a href="<?= e($settings['cta_button_link'] ?? '/contact.php') ?>" class="btn btn-light btn-lg mt-3 fw-semibold"><?= e($settings['cta_button_text']) ?></a>
    <?php endif; ?>
  </div>
</section>
<?php endif; ?>

<!-- CONTACT PREVIEW -->
<section class="py-5">
  <div class="container">
    <p class="eyebrow text-center">Get In Touch</p>
    <h2 class="text-center font-serif mb-5">Contact Us</h2>
    <div class="row justify-content-center text-center g-4">
      <div class="col-md-4">
        <i class="bi bi-geo-alt fs-3 text-navy"></i>
        <p class="mt-2 text-muted"><?= e($settings['contact_address'] ?? 'Address coming soon') ?></p>
      </div>
      <div class="col-md-4">
        <i class="bi bi-telephone fs-3 text-navy"></i>
        <p class="mt-2 text-muted"><?= e($settings['contact_phone'] ?? '') ?></p>
      </div>
      <div class="col-md-4">
        <i class="bi bi-envelope fs-3 text-navy"></i>
        <p class="mt-2 text-muted"><?= e($settings['contact_email'] ?? '') ?></p>
      </div>
    </div>
    <div class="text-center mt-4">
      <a href="/contact.php" class="btn btn-outline-dark">Send Us a Message</a>
    </div>
  </div>
</section>

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

<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'ea47bde0692e0665c4dd809e5baa7c9178dcfcae';
window.smartsupp||(function(d) {
  var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
  s=d.getElementsByTagName('script')[0];c=d.createElement('script');
  c.type='text/javascript';c.charset='utf-8';c.async=true;
  c.src='https://www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
<noscript>Powered by <a href="https://www.smartsupp.com" target="_blank">Smartsupp</a></noscript>

