<?php
declare(strict_types=1);

$db = new SQLite3(__DIR__ . '/../data/pages.sqlite', SQLITE3_OPEN_READONLY);
$db->busyTimeout(3000);
$page = $db->querySingle("SELECT * FROM pages WHERE slug='" . SQLite3::escapeString($slug) . "'", true);
$db->close();

if (!$page) {
    http_response_code(404);
    $page_title = '404: Page Not Found | Floor It Hardwood Floors';
    $page_meta  = '';
    require __DIR__ . '/../components/_header.php';
    echo '<section class="section section--light"><div class="container"><h1>Page Not Found</h1><p><a href="/">Return home</a></p></div></section>';
    require __DIR__ . '/../components/_footer.php';
    exit;
}

$page_title = $page['title'];
$page_meta  = $page['meta_description'];
$sections   = json_decode($page['sections_json'], true) ?? [];

$schema_json = json_encode([
    '@context' => 'https://schema.org',
    '@type'    => 'HomeAndConstructionBusiness',
    'name'     => 'Floor It Hardwood Floors',
    'url'      => 'https://floorithardwoodfloors.com',
    'telephone'=> '+17166021429',
    'address'  => [
        '@type'           => 'PostalAddress',
        'addressLocality' => 'Buffalo',
        'addressRegion'   => 'NY',
        'addressCountry'  => 'US',
    ],
    'areaServed'  => ['Buffalo','Amherst','Williamsville','Clarence','East Amherst','Lancaster'],
    'description' => $page['meta_description'],
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

require __DIR__ . '/../components/_header.php';

foreach ($sections as $s) {
    $t = $s['type'] ?? '';
    switch ($t) {

        case 'hero_video':
            $stats = $s['stats'] ?? [];
            ?>
            <section class="hero" aria-label="Hero">
              <div class="hero-video-wrap">
                <video autoplay muted loop playsinline poster="<?= htmlspecialchars($s['poster'] ?? '', ENT_QUOTES) ?>" aria-hidden="true">
                  <source src="<?= htmlspecialchars($s['video_webm'] ?? '', ENT_QUOTES) ?>" type="video/webm">
                  <source src="<?= htmlspecialchars($s['video_mp4'] ?? '', ENT_QUOTES) ?>" type="video/mp4">
                </video>
                <div class="hero-overlay"></div>
              </div>
              <div class="container">
                <div class="hero-content">
                  <div class="hero-eyebrow">
                    <div class="hero-eyebrow-line"></div>
                    <span><?= htmlspecialchars($s['eyebrow'] ?? '', ENT_QUOTES) ?></span>
                  </div>
                  <h1><?= htmlspecialchars($s['h1'] ?? '', ENT_QUOTES) ?></h1>
                  <p class="hero-sub"><?= htmlspecialchars($s['lead'] ?? '', ENT_QUOTES) ?></p>
                  <div class="hero-actions">
                    <a href="<?= htmlspecialchars($s['cta_primary_href'] ?? '/contact/', ENT_QUOTES) ?>" class="btn btn--primary btn--lg"><?= htmlspecialchars($s['cta_primary'] ?? 'Get Estimate', ENT_QUOTES) ?></a>
                    <?php if (!empty($s['cta_secondary'])): ?>
                    <a href="<?= htmlspecialchars($s['cta_secondary_href'] ?? '#', ENT_QUOTES) ?>" class="btn btn--ghost btn--lg"><?= htmlspecialchars($s['cta_secondary'], ENT_QUOTES) ?></a>
                    <?php endif; ?>
                  </div>
                  <?php if ($stats): ?>
                  <div class="hero-trust">
                    <?php foreach ($stats as $stat): ?>
                    <div class="hero-trust-stat">
                      <strong><?= htmlspecialchars($stat['num'] ?? '', ENT_QUOTES) ?></strong>
                      <span><?= htmlspecialchars($stat['label'] ?? '', ENT_QUOTES) ?></span>
                    </div>
                    <?php endforeach; ?>
                  </div>
                  <?php endif; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'hero_simple':
            ?>
            <section class="page-hero section section--dark">
              <div class="container">
                <div class="page-hero-content">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h1><?= htmlspecialchars($s['h1'] ?? '', ENT_QUOTES) ?></h1>
                  <?php if (!empty($s['lead'])): ?><p class="lead"><?= htmlspecialchars($s['lead'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'services_grid':
            $sdb = new SQLite3(__DIR__ . '/../data/services.sqlite', SQLITE3_OPEN_READONLY);
            $svc_result = $sdb->query("SELECT slug, service_name, hero_eyebrow, hero_lead, hero_image FROM services ORDER BY id");
            $services = [];
            while ($row = $svc_result->fetchArray(SQLITE3_ASSOC)) { $services[] = $row; }
            $sdb->close();
            $svc_images = [
                'floor-refinishing'  => '/assets/images/project-1-after.webp',
                'floor-restoration'  => '/assets/images/project-2-before.webp',
                'floor-sanding'      => '/assets/images/project-3-before.webp',
                'floor-installation' => '/assets/images/project-1-before.webp',
            ];
            ?>
            <section class="section section--light" id="services">
              <div class="container">
                <div class="section-header">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <?php if (!empty($s['h2'])): ?><h2><?= htmlspecialchars($s['h2'], ENT_QUOTES) ?></h2><?php endif; ?>
                  <?php if (!empty($s['lead'])): ?><p class="lead"><?= htmlspecialchars($s['lead'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
                <div class="grid grid--4col services-grid">
                  <?php foreach ($services as $svc): ?>
                  <a href="/services/<?= htmlspecialchars($svc['slug'], ENT_QUOTES) ?>/" class="card card--service">
                    <?php $img = $svc_images[$svc['slug']] ?? '/assets/images/project-1-after.webp'; ?>
                    <div class="card-img-wrap"><img src="<?= $img ?>" alt="<?= htmlspecialchars($svc['service_name'], ENT_QUOTES) ?>" loading="lazy"></div>
                    <div class="card-body">
                      <h3><?= htmlspecialchars($svc['service_name'], ENT_QUOTES) ?></h3>
                      <p><?= htmlspecialchars($svc['hero_lead'], ENT_QUOTES) ?></p>
                      <span class="card-link">Learn more &rarr;</span>
                    </div>
                  </a>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'process_steps':
            $steps = $s['steps'] ?? [];
            ?>
            <section class="section section--dark" id="process">
              <div class="container">
                <div class="section-header section-header--center">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                </div>
                <div class="grid grid--3col process-grid">
                  <?php foreach ($steps as $step): ?>
                  <div class="process-step">
                    <div class="process-num"><?= htmlspecialchars($step['num'] ?? '', ENT_QUOTES) ?></div>
                    <h3><?= htmlspecialchars($step['title'] ?? '', ENT_QUOTES) ?></h3>
                    <p><?= htmlspecialchars($step['body'] ?? '', ENT_QUOTES) ?></p>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'about_preview':
            ?>
            <section class="section section--alt" id="about-preview">
              <div class="container about-preview-inner">
                <div class="about-preview-text">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                  <div class="divider"></div>
                  <?php if (!empty($s['lead'])): ?><p class="lead"><?= htmlspecialchars($s['lead'], ENT_QUOTES) ?></p><?php endif; ?>
                  <?php if (!empty($s['body'])): ?><p style="margin-top:1.25rem;color:var(--smoke);"><?= htmlspecialchars($s['body'], ENT_QUOTES) ?></p><?php endif; ?>
                  <?php if (!empty($s['cta'])): ?>
                  <div class="cta-group mt-8">
                    <a href="<?= htmlspecialchars($s['cta_href'] ?? '/about/', ENT_QUOTES) ?>" class="btn btn--primary"><?= htmlspecialchars($s['cta'], ENT_QUOTES) ?></a>
                  </div>
                  <?php endif; ?>
                </div>
                <div class="about-preview-img">
                  <img src="/assets/images/project-1-after.webp" alt="Hardwood floor refinishing in Western New York" loading="lazy">
                </div>
              </div>
            </section>
            <?php
            break;

        case 'gallery':
            ?>
            <section class="section section--bark" id="gallery">
              <div class="container">
                <div class="section-header section-header--center">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                  <?php if (!empty($s['lead'])): ?><p class="lead"><?= htmlspecialchars($s['lead'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
                <div class="gallery-grid">
                  <div class="gallery-item"><img src="/assets/images/project-1-before.webp" alt="Before refinishing" loading="lazy"><span class="gallery-item-label">Before</span></div>
                  <div class="gallery-item"><img src="/assets/images/project-1-after.webp" alt="After refinishing" loading="lazy"><span class="gallery-item-label gallery-item-label--after">After</span></div>
                  <div class="gallery-item"><img src="/assets/images/project-2-before.webp" alt="Before restoration" loading="lazy"><span class="gallery-item-label">Before</span></div>
                  <div class="gallery-item"><img src="/assets/images/project-3-before.webp" alt="Refinishing in progress" loading="lazy"><span class="gallery-item-label">In Progress</span></div>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'cta_banner':
            ?>
            <section class="section section--amber cta-section">
              <div class="container cta-section-inner">
                <div class="cta-section-text">
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                  <?php if (!empty($s['body'])): ?><p><?= htmlspecialchars($s['body'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
                <a href="<?= htmlspecialchars($s['cta_href'] ?? '/contact/', ENT_QUOTES) ?>" class="btn btn--primary btn--lg"><?= htmlspecialchars($s['cta'] ?? 'Get Estimate', ENT_QUOTES) ?></a>
              </div>
            </section>
            <?php
            break;

        case 'contact_form':
            ?>
            <section class="section section--light" id="contact">
              <div class="container contact-layout">
                <div class="contact-info">
                  <h2><?= htmlspecialchars($s['h2'] ?? 'Send Us a Message', ENT_QUOTES) ?></h2>
                  <div class="contact-detail"><strong>Phone</strong><a href="tel:+17166021429"><?= htmlspecialchars($s['phone'] ?? '(716) 602-1429', ENT_QUOTES) ?></a></div>
                  <div class="contact-detail"><strong>Email</strong><a href="mailto:<?= htmlspecialchars($s['email'] ?? '', ENT_QUOTES) ?>"><?= htmlspecialchars($s['email'] ?? '', ENT_QUOTES) ?></a></div>
                  <div class="contact-detail"><strong>Response Time</strong><span>Within 24 hours</span></div>
                  <div class="contact-detail"><strong>Service Area</strong><span>Buffalo and Erie County, NY</span></div>
                </div>
                <form class="contact-form" id="contactForm" action="/contact/" method="POST" novalidate>
                  <div class="form-group">
                    <label for="name">Full Name <span aria-hidden="true">*</span></label>
                    <input type="text" id="name" name="name" required autocomplete="name" placeholder="Your name">
                  </div>
                  <div class="form-group">
                    <label for="email">Email Address <span aria-hidden="true">*</span></label>
                    <input type="email" id="email" name="email" required autocomplete="email" placeholder="your@email.com">
                  </div>
                  <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone" autocomplete="tel" placeholder="(716) 555-0000">
                  </div>
                  <div class="form-group">
                    <label for="message">Message <span aria-hidden="true">*</span></label>
                    <textarea id="message" name="message" required rows="5" placeholder="Tell us about your floors and what you need..."></textarea>
                  </div>
                  <input type="text" name="website" style="display:none;" tabindex="-1" autocomplete="off">
                  <input type="hidden" name="form_loaded_at" id="form_loaded_at">
                  <div id="altcha-widget"></div>
                  <button type="submit" id="contactFormSubmit" class="btn btn--primary btn--full">Send Message</button>
                  <div id="formStatus" role="status" aria-live="polite"></div>
                </form>
              </div>
            </section>
            <script src="/assets/js/altcha.min.js"></script>
            <script src="/assets/js/form.js"></script>
            <?php
            break;

        case 'story':
            ?>
            <section class="section section--light">
              <div class="container about-story">
                <div class="about-story-text">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                  <div class="divider"></div>
                  <?php if (!empty($s['lead'])): ?><p class="lead"><?= htmlspecialchars($s['lead'], ENT_QUOTES) ?></p><?php endif; ?>
                  <?php if (!empty($s['body'])): ?><p style="margin-top:1.25rem;color:var(--smoke);"><?= htmlspecialchars($s['body'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
                <div class="about-story-img">
                  <img src="/assets/images/refinishing-machine.webp" alt="Floor It refinishing equipment" loading="lazy">
                </div>
              </div>
            </section>
            <?php
            break;

        case 'credentials':
            ?>
            <section class="section section--dark">
              <div class="container">
                <div class="section-header section-header--center">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                </div>
                <div class="grid grid--4col credentials-grid">
                  <div class="credential-item"><strong>30+</strong><span>Years in Business</span></div>
                  <div class="credential-item"><strong>75+</strong><span>Years Combined Experience</span></div>
                  <div class="credential-item"><strong>500+</strong><span>Projects Completed</span></div>
                  <div class="credential-item"><strong>4.9/5</strong><span>Google Rating</span></div>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'service_areas':
            $ldb = new SQLite3(__DIR__ . '/../data/locations.sqlite', SQLITE3_OPEN_READONLY);
            $loc_result = $ldb->query("SELECT slug, city FROM locations ORDER BY id");
            $locations = [];
            while ($row = $loc_result->fetchArray(SQLITE3_ASSOC)) { $locations[] = $row; }
            $ldb->close();
            ?>
            <section class="section section--light">
              <div class="container">
                <div class="section-header section-header--center">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                  <?php if (!empty($s['body'])): ?><p class="lead"><?= htmlspecialchars($s['body'], ENT_QUOTES) ?></p><?php endif; ?>
                </div>
                <div class="locations-pill-list">
                  <?php foreach ($locations as $loc): ?>
                  <a href="/locations/<?= htmlspecialchars($loc['slug'], ENT_QUOTES) ?>/" class="location-pill"><?= htmlspecialchars($loc['city'], ENT_QUOTES) ?>, NY</a>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'testimonials_grid':
        case 'testimonials_preview':
            $tdb = new SQLite3(__DIR__ . '/../data/testimonials.sqlite', SQLITE3_OPEN_READONLY);
            $limit = ($t === 'testimonials_preview') ? 3 : 20;
            $featured = ($t === 'testimonials_preview') ? 'WHERE featured=1' : '';
            $t_result = $tdb->query("SELECT * FROM testimonials {$featured} ORDER BY id LIMIT {$limit}");
            $testimonials = [];
            while ($row = $t_result->fetchArray(SQLITE3_ASSOC)) { $testimonials[] = $row; }
            $tdb->close();
            ?>
            <section class="section section--alt" id="reviews">
              <div class="container">
                <div class="section-header section-header--center">
                  <?php if (!empty($s['eyebrow'])): ?><span class="eyebrow"><?= htmlspecialchars($s['eyebrow'], ENT_QUOTES) ?></span><?php endif; ?>
                  <h2><?= htmlspecialchars($s['h2'] ?? '', ENT_QUOTES) ?></h2>
                </div>
                <div class="grid grid--3col testimonials-grid">
                  <?php foreach ($testimonials as $review): ?>
                  <div class="testimonial">
                    <div class="testimonial-stars"><span>&#9733;</span><span>&#9733;</span><span>&#9733;</span><span>&#9733;</span><span>&#9733;</span></div>
                    <p class="testimonial-text">"<?= htmlspecialchars($review['quote'], ENT_QUOTES) ?>"</p>
                    <div class="testimonial-author">
                      <strong><?= htmlspecialchars($review['author'], ENT_QUOTES) ?></strong>
                      <span><?= htmlspecialchars($review['location'] ?? '', ENT_QUOTES) ?></span>
                    </div>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'blog_listing':
            $bdb = new SQLite3(__DIR__ . '/../data/blog.sqlite', SQLITE3_OPEN_READONLY);
            $b_result = $bdb->query("SELECT slug, title, excerpt, created_at FROM posts WHERE published=1 ORDER BY created_at DESC");
            $posts = [];
            while ($row = $b_result->fetchArray(SQLITE3_ASSOC)) { $posts[] = $row; }
            $bdb->close();
            ?>
            <section class="section section--light">
              <div class="container">
                <div class="grid grid--3col blog-grid">
                  <?php foreach ($posts as $post): ?>
                  <article class="card card--blog">
                    <div class="card-body">
                      <h2><a href="/blog/<?= htmlspecialchars($post['slug'], ENT_QUOTES) ?>/"><?= htmlspecialchars($post['title'], ENT_QUOTES) ?></a></h2>
                      <p><?= htmlspecialchars($post['excerpt'] ?? '', ENT_QUOTES) ?></p>
                      <a href="/blog/<?= htmlspecialchars($post['slug'], ENT_QUOTES) ?>/" class="card-link">Read more &rarr;</a>
                    </div>
                  </article>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;

        case 'locations_grid':
            $ldb2 = new SQLite3(__DIR__ . '/../data/locations.sqlite', SQLITE3_OPEN_READONLY);
            $loc2_result = $ldb2->query("SELECT slug, city, hero_lead FROM locations ORDER BY id");
            $locs = [];
            while ($row = $loc2_result->fetchArray(SQLITE3_ASSOC)) { $locs[] = $row; }
            $ldb2->close();
            ?>
            <section class="section section--light">
              <div class="container">
                <div class="grid grid--3col locations-grid">
                  <?php foreach ($locs as $loc): ?>
                  <a href="/locations/<?= htmlspecialchars($loc['slug'], ENT_QUOTES) ?>/" class="card card--location">
                    <div class="card-body">
                      <h3><?= htmlspecialchars($loc['city'], ENT_QUOTES) ?>, NY</h3>
                      <p><?= htmlspecialchars(substr($loc['hero_lead'] ?? '', 0, 120), ENT_QUOTES) ?>...</p>
                      <span class="card-link">View service area &rarr;</span>
                    </div>
                  </a>
                  <?php endforeach; ?>
                </div>
              </div>
            </section>
            <?php
            break;
    }
}

require __DIR__ . '/../components/_footer.php';
