<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
include BASE_PATH . '/include/header.php';

// Fetch services for the home page services section
$conn = get_db_connection();
$specified_services = ["Chimney Inspection Level 1", "Chimney Sweep", "Chimney Repair", "Chimney Cap Installation"];
$services_in = "'" . implode("','", $specified_services) . "'";
$home_services_result = $conn->query("SELECT * FROM services WHERE name IN ($services_in) ORDER BY FIELD(name, $services_in)");
$home_services = [];
if ($home_services_result) {
    while ($row = $home_services_result->fetch_assoc()) {
        $home_services[] = $row;
    }
}

// Fetch additional settings for YouTube and Popup
$settings_query = $conn->query("SELECT setting_key, setting_value FROM website_settings WHERE setting_key IN ('youtube_testimonial_1', 'youtube_testimonial_2', 'popup_title', 'popup_content')");
$home_settings = [];
if ($settings_query) {
    while ($row = $settings_query->fetch_assoc()) {
        $home_settings[$row['setting_key']] = $row['setting_value'];
    }
}

// Fetch reviews for the testimonials section
$reviews_result = $conn->query("SELECT * FROM reviews ORDER BY display_order ASC, created_at DESC LIMIT 6");
$home_reviews = [];
if ($reviews_result) {
    while ($row = $reviews_result->fetch_assoc()) {
        $home_reviews[] = $row;
    }
}

$yt_testimonial_1 = $home_settings['youtube_testimonial_1'] ?? '';
$yt_testimonial_2 = $home_settings['youtube_testimonial_2'] ?? '';
$popup_title = $home_settings['popup_title'] ?? '';
$popup_content = $home_settings['popup_content'] ?? '';

// Helper function to convert YouTube URL to embed URL
function get_yt_embed_url($url)
{
    if (strpos($url, 'youtu.be/') !== false) {
        return str_replace('youtu.be/', 'www.youtube.com/embed/', $url);
    }
    if (strpos($url, 'watch?v=') !== false) {
        return str_replace('watch?v=', 'embed/', $url);
    }
    return $url;
}

$yt_embed_1 = get_yt_embed_url($yt_testimonial_1);
$yt_embed_2 = get_yt_embed_url($yt_testimonial_2);

// Fetch services for the "Service Need" dropdown in the appointment form (use all service names)
$appointment_services = [];
if ($conn && !$conn->connect_error) {
    $appointment_result = $conn->query("SELECT name FROM services ORDER BY name ASC");
    if ($appointment_result) {
        while ($row = $appointment_result->fetch_assoc()) {
            if (!empty($row['name'])) {
                $appointment_services[] = $row['name'];
            }
        }
        $appointment_result->free();
    }
}

// hex2rgb is now in config.php

$site_color = get_site_color();
$button_bg_color = get_button_bg_color();
list($r, $g, $b) = hex2rgb($site_color);
?>

<?php
// Pre-calculate colors for CSS variables
$button_rgb = hex2rgb($button_bg_color);
$button_rgb_str = implode(',', $button_rgb);
$site_rgb_str = "$r, $g, $b";
?>
<style>
@media (max-width: 767px) {
  .submit-btn {
    width: 100%;
    white-space: normal;        /* allows text to wrap */
    text-align: center;
    padding: 14px 16px;
    line-height: 1.3;
    font-size: 16px;
    box-sizing: border-box;
  }

  .process-section {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
  }

  .d-md-none {
    margin-bottom: 2px !important;
    padding: 0 !important;
  }

  .why-choose-us {
    padding-top: 0 !important;
    margin-top: -12px !important; /* 👈 pulls it closer */
  }
}






    :root {
        --button-shadow-color: rgba(<?php echo $button_rgb_str; ?>, 0.2);
        --button-shadow-hover-color: rgba(<?php echo $button_rgb_str; ?>, 0.3);
        --button-shadow-color-light: rgba(<?php echo $button_rgb_str; ?>, 0.1);
        --button-shadow-hover-color-light: rgba(<?php echo $button_rgb_str; ?>, 0.15);
        --primary-shadow-color: rgba(<?php echo $site_rgb_str; ?>, 0.2);
        --site-icon-bg-color: rgba(<?php echo $site_rgb_str; ?>, 0.1);
        --appointment-gradient-color: rgba(<?php echo $site_rgb_str; ?>, 0.15);
        --form-focus-shadow-color: rgba(<?php echo $site_rgb_str; ?>, 0.1);
        --modal-badge-bg-color: rgba(<?php echo $site_rgb_str; ?>, 0.1);
    }
</style>
<link rel="stylesheet" href="/css/home.css">

<main>
    <!-- Hero Section -->
    <section class="hero-section">
        <div class="hero-video-container">
            <video autoplay muted loop playsinline>
                <source src="/v.mp4" type="video/mp4">
            </video>
        </div>
        <div class="hero-overlay"></div>
        <div class="hero-content">
            <h1 class="animated fadeInUp">C<span>rest</span> Chimney Services</h1>
            <p class="animated fadeInUp" style="animation-delay: 0.2s;">Reliable Chimney & Fireplace Service Solutions.
                Trusted by homeowners for expert cleaning, repair, and maintenance.</p>
            <a href="https://online-booking.workiz.com/?ac=9abb19f6ca1c78f131c81ac77142b344ec334504f2abae7e09d468bea9ea621f" class="hero-btn animated fadeInUp"
                style="animation-delay: 0.4s;">Book Online</a>
        </div>
    </section>

    <!-- Trust Bar -->
    <div class="container">
        <div class="trust-bar row g-0">
            <div class="col-6 col-md-3 trust-item">
                <i class="fas fa-certificate"></i>
                <span>CSIA Certified</span>
            </div>
            <div class="col-6 col-md-3 trust-item">
                <i class="fas fa-shield-alt"></i>
                <span>Licensed & Bonded</span>
            </div>
            <div class="col-6 col-md-3 trust-item">
                <i class="fas fa-star"></i>
                <span>5-Star Rated</span>
            </div>
            <div class="col-6 col-md-3 trust-item">
                <i class="fas fa-calendar-check"></i>
                <span>On-Time Service</span>
            </div>
        </div>
    </div>

    <!-- Services Section -->
    <section class="services-section">
        <div class="container">
            <div class="section-header">
                <h2>Our Professional <span>Services</span></h2>
                <p>We provide comprehensive solutions for all your chimney and fireplace needs, ensuring safety and
                    efficiency.</p>
            </div>
            <div class="row g-4">
                <?php if (!empty($home_services)): ?>
                    <?php foreach ($home_services as $service):
                        $service_link = '/service.php?slug=' . urlencode($service['slug']);
                        $service_image = !empty($service['image']) ? htmlspecialchars($service['image']) : '/wp-content/uploads/2022/08/chimney-construction.jpg';
                        $service_name = htmlspecialchars($service['name']);
                        $service_description = !empty($service['description']) ? htmlspecialchars(substr(strip_tags($service['description']), 0, 120)) : '';
                        ?>
                        <div class="col-md-6 col-lg-3">
                            <div class="service-card">
                                <div class="service-image">
                                    <img src="<?php echo $service_image; ?>" alt="<?php echo $service_name; ?>">
                                </div>
                                <div class="service-content">
                                    <h3><?php echo $service_name; ?></h3>
                                    <p><?php echo $service_description; ?>...</p>
                                    <a href="<?php echo $service_link; ?>" class="service-link">Learn More <i
                                            class="fas fa-arrow-right"></i></a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <!-- Process Section -->
    <section class="process-section">
        <div class="container">
            <div class="section-header">
                <h2>Our Simple <span>Process</span></h2>
                <p>Getting your chimney serviced has never been easier. We follow a proven 4-step process to ensure
                    quality.</p>
            </div>
            <div class="row">
                <div class="col-lg-3 col-md-6">
                    <div class="process-step">
                        <div class="step-number">01</div>
                        <h4>Schedule</h4>
                        <p>Book your appointment online or call our friendly team to set a time.</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="process-step">
                        <div class="step-number">02</div>
                        <h4>Inspection</h4>
                        <p>Our certified technicians perform a thorough multi-point safety inspection.</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="process-step">
                        <div class="step-number">03</div>
                        <h4>Service</h4>
                        <p>We perform the necessary cleaning or repairs using modern equipment.</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="process-step">
                        <div class="step-number">04</div>
                        <h4>Safety Check</h4>
                        <p>A final safety check is performed to ensure your system is ready for use.</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Mobile-Only Logo -->
    <div class="d-md-none text-center p-0">
        <img src="<?php echo get_logo(); ?>" alt="<?php echo get_website_name(); ?>"
            style="max-height: 200px; width: auto;">
    </div>

    <!-- Why Choose Us -->
    <section class="why-choose-us">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 mb-5 mb-lg-0">
                    <div class="section-header text-start">
                        <h2>Why <span>Choose</span> Crest Chimney?</h2>
                        <p class="ms-0">We take pride in our work and ensure every customer receives top-tier service
                            and professional advice.</p>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon"><i class="fas fa-user-tie"></i></div>
                        <div class="feature-text">
                            <h4>Owner on Every Job</h4>
                            <p>You deal directly with the person who cares most about the quality of your project.</p>
                        </div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon"><i class="fas fa-clock"></i></div>
                        <div class="feature-text">
                            <h4>Reliable & On-Time</h4>
                            <p>We value your time and schedule specific appointments so you're never left waiting.</p>
                        </div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon"><i class="fas fa-tools"></i></div>
                        <div class="feature-text">
                            <h4>Modern Approaches</h4>
                            <p>We use the latest tools and technology to ensure your systems operate at optimal levels.
                            </p>
                        </div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon"><i class="fas fa-handshake"></i></div>
                        <div class="feature-text">
                            <h4>Old-Time Service</h4>
                            <p>We take the time to listen to your concerns and provide honest, practical solutions.</p>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="position-relative">
                        <div
                            class="rounded-4 overflow-hidden shadow-2xl transform hover:scale-105 transition-transform duration-500">
                            <img src="/wp-content/uploads/2022/08/chimney-construction.jpg" alt="Chimney Work"
                                class="img-fluid">
                        </div>
                        <div class="position-absolute bottom-0 end-0 bg-white p-4 rounded-4 shadow-lg m-4 d-none d-md-block"
                            style="max-width: 200px;">
                            <div class="text-primary h2 fw-bold mb-0">15+</div>
                            <div class="text-muted small fw-bold uppercase tracking-wider">Years of Excellence</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- About Section -->
    <section class="about-section py-5">
        <div class="container py-5">
            <div class="row align-items-center">
                <div class="col-lg-6 order-lg-2">
                    <div class="section-header text-start">
                        <h2>About <span>Crest Chimney</span></h2>
                        <p class="ms-0">Quality Work, Done by Quality People.</p>
                    </div>
                    <p>An attractive brick fireplace can set your home apart and add to its curb appeal and family feel.
                        It may serve as the focus of the house, both inside and out, and it is an important feature that
                        can add to, or detract from, your home’s beauty and value.</p>
                    <p>Family-owned and operated, Crest Chimney is a home-grown business with years of experience.
                        Whether your chimney needs repair or a complete restoration, we provide prompt, expert service
                        at affordable prices.</p>
                    <div class="mt-4">
                        <a href="tel:<?php echo get_phone_number_tel(); ?>"
                            class="btn btn-outline-primary rounded-pill px-4 py-2"
                            style="color: var(--primary-color); border-color: var(--primary-color);">Contact Us
                            Today</a>
                    </div>
                </div>
                <div class="col-lg-6 order-lg-1">
                    <div class="pe-lg-5 text-center position-relative">
                        <div class="about-img-bg"></div>
                        <img src="/wp-content/uploads/2022/09/a1-chimney-location-icon.png" alt="About Us"
                            class="img-fluid rounded-4 shadow-sm position-relative z-1" style="max-width: 350px;">
                    </div>
                </div>
            </div>
        </div>
    </section>


    <!-- Stats Section -->
    <section class="stats-section">
        <div class="container">
            <div class="row g-4">
                <div class="col-6 col-md-3 stat-item">
                    <div class="stat-number">15+</div>
                    <div class="stat-label">Years Experience</div>
                </div>
                <div class="col-6 col-md-3 stat-item">
                    <div class="stat-number">5k+</div>
                    <div class="stat-label">Happy Clients</div>
                </div>
                <div class="col-6 col-md-3 stat-item">
                    <div class="stat-number">100%</div>
                    <div class="stat-label">Safety Record</div>
                </div>
                <div class="col-6 col-md-3 stat-item">
                    <div class="stat-number">24/7</div>
                    <div class="stat-label">Support</div>
                </div>
            </div>
        </div>
    </section>

    <!-- Financing Banner -->
    <section class="financing-banner">
        <div class="container">
            <h3>Need Financing? We've Got You Covered!</h3>
            <p>We offer competitive financing options to help you get the repairs you need without the stress.</p>
            <a href="tel:<?php echo get_phone_number_tel(); ?>" class="financing-btn">Learn More About Financing</a>
        </div>
    </section>

    <!-- Testimonials Section -->
    <section class="testimonials-section">
        <div class="container">
            <div class="section-header">
                <h2>What Our <span>Customers</span> Say</h2>
                <p>Real stories from homeowners who trusted us with their chimney and fireplace needs.</p>
            </div>
            <?php if (!empty($yt_testimonial_1) || !empty($yt_testimonial_2)): ?>
                <div class="row g-4 mb-5">
                    <?php if (!empty($yt_testimonial_1)): ?>
                        <div class="<?php echo empty($yt_testimonial_2) ? 'col-md-12' : 'col-md-6'; ?>">
                            <div class="testimonial-video-card">
                                <div class="video-wrapper">
                                    <iframe width="100%" height="315" src="<?php echo $yt_embed_1; ?>"
                                        title="YouTube video player" frameborder="0"
                                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                        allowfullscreen></iframe>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($yt_testimonial_2)): ?>
                        <div class="<?php echo empty($yt_testimonial_1) ? 'col-md-12' : 'col-md-6'; ?>">
                            <div class="testimonial-video-card">
                                <div class="video-wrapper">
                                    <iframe width="100%" height="315" src="<?php echo $yt_embed_2; ?>"
                                        title="YouTube video player" frameborder="0"
                                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                        allowfullscreen></iframe>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <div class="row g-4">
                <?php if (!empty($home_reviews)): ?>
                    <?php foreach ($home_reviews as $review): ?>
                        <div class="col-md-4">
                            <div class="contact-info-card p-4">
                                <div class="mb-3 text-warning">
                                    <?php for ($i = 0; $i < $review['rating']; $i++): ?>
                                        <i class="fas fa-star"></i>
                                    <?php endfor; ?>
                                </div>
                                <p class="mb-4">"<?php echo htmlspecialchars($review['content']); ?>"</p>
                                <h5 class="mb-0"><?php echo htmlspecialchars($review['author_name']); ?></h5>
                                <small class="text-muted"><?php echo htmlspecialchars($review['author_role']); ?></small>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- Fallback if no reviews in DB -->
                    <div class="col-md-4">
                        <div class="contact-info-card p-4">
                            <div class="mb-3 text-warning">
                                <i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i
                                    class="fas fa-star"></i><i class="fas fa-star"></i>
                            </div>
                            <p class="mb-4">"Edwin relined my chimney and did such a great job. He was so respectful and
                                worked very clean. Thanks Crest Chimney for best service."</p>
                            <h5 class="mb-0">Rafael W.</h5>
                            <small class="text-muted">Verified Customer</small>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <!-- Appointment Section -->
    <section class="appointment-section" id="appointment">
        <div class="container">
            <div class="row align-items-center g-5">
                <div class="col-lg-6">
                    <div class="appointment-info">
                        <h2>Ready to <span>Restore</span> Your Chimney?</h2>
                        <p>Book your professional inspection today and experience the Crest Chimney difference.</p>

                        <div class="contact-method">
                            <i class="fas fa-phone"></i>
                            <div>
                                <h5>Call Us Directly</h5>
                                <a
                                    href="tel:<?php echo get_phone_number_tel(); ?>"><?php echo get_phone_number(); ?></a>
                            </div>
                        </div>

                        <div class="contact-method">
                            <i class="fas fa-envelope"></i>
                            <div>
                                <h5>Email Our Team</h5>
                                <a href="mailto:<?php echo get_email(); ?>"><?php echo get_email(); ?></a>
                            </div>
                        </div>

                        <div class="contact-method">
                            <i class="fas fa-map-marker-alt"></i>
                            <div>
                                <h5>Service Area</h5>
                                <p>Serving Local Communities with Pride</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="appointment-form-card">
                        <form action="/submit-appointment.php" method="POST">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">First Name</label>
                                    <input type="text" name="fname" class="form-control-custom" placeholder="John"
                                        required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Last Name</label>
                                    <input type="text" name="lname" class="form-control-custom" placeholder="Smith"
                                        required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Phone Number</label>
                                    <input type="tel" name="phone" class="form-control-custom"
                                        placeholder="(123) 456-7890" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Email Address</label>
                                    <input type="email" name="email" class="form-control-custom"
                                        placeholder="email@example.com" required>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Service Need</label>
                                    <select name="service" class="form-control-custom" required>
                                        <option value="">- Select Service -</option>
                                        <?php if (!empty($appointment_services)): ?>
                                            <?php foreach ($appointment_services as $service_name): ?>
                                                <option value="<?php echo htmlspecialchars($service_name); ?>">
                                                    <?php echo htmlspecialchars($service_name); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Preferred Date</label>
                                    <input type="date" name="date" class="form-control-custom" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Preferred Time</label>
                                    <input type="time" name="time" class="form-control-custom" required>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Address</label>
                                    <input type="text" name="address" class="form-control-custom"
                                        placeholder="1234 Street Name" required>
                                </div>
                                <div class="col-12">
                                    <button type="submit" class="submit-btn">Book My Appointment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<?php if (!empty($popup_title) || !empty($popup_content)): ?>
    <!-- Modern Slide-in Toast -->
    <!-- <div class="custom-modal-overlay" id="promoModal">
    <div class="custom-modal">
        <div class="modal-banner"></div>
        <div class="modal-content-wrap">
            <button class="close-modal-btn" onclick="closeModal()">&times;</button>
            <div class="modal-badge">
                <i class="fas fa-bolt"></i> Special Offer
            </div>
            <h3 class="modal-title-text"><?php echo htmlspecialchars($popup_title); ?></h3>
            <div class="modal-desc-text"><?php echo $popup_content; ?></div>
            <a href="#appointment" class="modal-action-btn" onclick="closeModal()">Claim Discount</a>
        </div>
    </div>
</div> -->

    <script>
        function openModal() {
            document.getElementById('promoModal').classList.add('active');
        }

        function closeModal() {
            document.getElementById('promoModal').classList.remove('active');
        }

        // Show toast after 4 seconds
        window.onload = function () {
            setTimeout(openModal, 4000);

            // Reinforce video playback
            const heroVideo = document.querySelector('.hero-video-container video');
            if (heroVideo) {
                heroVideo.play().catch(e => console.log("Video autoplay prevented, clicking theme toggle might fix it."));
            }
        };

        // Ensure video plays when theme changes
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
                    const video = document.querySelector('.hero-video-container video');
                    if (video) video.play().catch(e => { });
                }
            });
        });
        observer.observe(document.documentElement, { attributes: true });
    </script>
<?php endif; ?>
<?php include BASE_PATH . "/include/footer.php"; ?>