<?php
/**
 * Excel Painting - Homepage
 * Tracks page views and clicks for statistics
 */
require_once __DIR__ . '/php/config/config.php';
require_once __DIR__ . '/php/config/database.php';
require_once __DIR__ . '/php/classes/Statistics.php';
require_once __DIR__ . '/php/classes/ImageUploader.php';
require_once __DIR__ . '/php/classes/ContentManager.php';
require_once __DIR__ . '/php/helpers/footer-renderer.php';
require_once __DIR__ . '/php/helpers/page-renderer.php';

// Track page view
try {
    $statistics = new Statistics();
    $statistics->trackPageView('index');
} catch (Exception $e) {
    // Fail silently - don't break page if tracking fails
    error_log('Statistics tracking error: ' . $e->getMessage());
}

// Load gallery images for preview (limit to 3-6 images)
try {
    $imageUploader = new ImageUploader();
    $galleryImages = $imageUploader->getAllImages();
    // Limit to first 6 images for homepage preview
    $galleryPreviewImages = array_slice($galleryImages, 0, 6);
} catch (Exception $e) {
    error_log('Gallery loading error: ' . $e->getMessage());
    $galleryPreviewImages = [];
}

// Load services and testimonials from database
try {
    $contentManager = new ContentManager();
    $services = $contentManager->getAllServices();
    $testimonials = $contentManager->getAllTestimonials();
    
    // Load page from database or use defaults
    $page = $contentManager->getPage('home');
    $pageId = $page ? $page['id'] : null;
    $pageHeroTitle = 'Professional Painting & Remodeling in Tomball, TX';
    $pageHeroSubtitle = 'Transform your home or business with our expert painting and remodeling services. Serving Tomball and the North Houston area with quality craftsmanship and attention to detail.';
    
    if ($page && $page['is_active']) {
        $pageHeroTitle = $page['hero_title'] ?? $pageHeroTitle;
        $pageHeroSubtitle = $page['hero_subtitle'] ?? $pageHeroSubtitle;
    }
    
    // Merge database sections with defaults
    try {
        $pageSections = mergePageSections($pageId, 'home');
    } catch (Exception $e) {
        error_log('Error loading page sections: ' . $e->getMessage());
        // Fallback to defaults only
        require_once __DIR__ . '/php/helpers/default-sections.php';
        $pageSections = getDefaultSections('home');
    }
} catch (Exception $e) {
    error_log('Content loading error: ' . $e->getMessage());
    $services = [];
    $testimonials = [];
    $pageHeroTitle = 'Professional Painting & Remodeling in Tomball, TX';
    $pageHeroSubtitle = 'Transform your home or business with our expert painting and remodeling services. Serving Tomball and the North Houston area with quality craftsmanship and attention to detail.';
    $pageSections = [];
}

// Load footer data
$footerData = renderFooter();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Excel Painting - Professional painting and remodeling services in Tomball, TX and North Houston. Interior & exterior painting, drywall repair, power washing, flooring, and more. Free estimates!">
    <meta name="keywords" content="painting Tomball TX, house painting North Houston, interior painting, exterior painting, remodeling Tomball, drywall repair, power washing, flooring installation">
    <meta name="author" content="Excel Painting">
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://excelpainting.us/">
    <meta property="og:title" content="Excel Painting - Professional Painting Services in Tomball, TX">
    <meta property="og:description" content="Top-quality painting and remodeling services in Tomball, TX and North Houston area. Fully insured, free estimates. Call today!">
    <meta property="og:image" content="https://excelpainting.us/images/hero/paint-brush.jpg">
    
    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" content="https://excelpainting.us/">
    <meta property="twitter:title" content="Excel Painting - Professional Painting Services in Tomball, TX">
    <meta property="twitter:description" content="Top-quality painting and remodeling services in Tomball, TX and North Houston area. Fully insured, free estimates.">
    <meta property="twitter:image" content="https://excelpainting.us/images/hero/paint-brush.jpg">
    
    <title>Excel Painting - Professional Painting Services in Tomball, TX | North Houston</title>
    <?php echo getFaviconLinks(); ?>
    <link rel="stylesheet" href="/css/style.css">
    
    <!-- Structured Data (JSON-LD) -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "LocalBusiness",
        "name": "Excel Painting",
        "image": "https://excelpainting.us/images/hero/paint-brush.jpg",
        "@id": "https://excelpainting.us",
        "url": "https://excelpainting.us",
        "telephone": "+1-281-682-3030",
        "priceRange": "$$",
        "address": {
            "@type": "PostalAddress",
            "addressLocality": "Tomball",
            "addressRegion": "TX",
            "addressCountry": "US"
        },
        "geo": {
            "@type": "GeoCoordinates",
            "latitude": 30.0952,
            "longitude": -95.6161
        },
        "openingHoursSpecification": {
            "@type": "OpeningHoursSpecification",
            "dayOfWeek": [
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday"
            ],
            "opens": "08:00",
            "closes": "18:00"
        },
        "sameAs": [],
        "areaServed": {
            "@type": "City",
            "name": "Tomball, TX"
        },
        "serviceArea": {
            "@type": "GeoCircle",
            "geoMidpoint": {
                "@type": "GeoCoordinates",
                "latitude": 30.0952,
                "longitude": -95.6161
            },
            "geoRadius": {
                "@type": "Distance",
                "value": "50",
                "unitCode": "mi"
            }
        },
        "hasOfferCatalog": {
            "@type": "OfferCatalog",
            "name": "Painting and Remodeling Services",
            "itemListElement": [
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "Interior Painting",
                        "description": "Professional interior painting services"
                    }
                },
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "Exterior Painting",
                        "description": "Professional exterior painting services"
                    }
                },
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "Drywall Repair",
                        "description": "Drywall installation and repair services"
                    }
                },
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "Power Washing",
                        "description": "Professional power washing services"
                    }
                },
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "Flooring",
                        "description": "Flooring installation and repair"
                    }
                },
                {
                    "@type": "Offer",
                    "itemOffered": {
                        "@type": "Service",
                        "name": "General Remodeling",
                        "description": "General remodeling and renovation services"
                    }
                }
            ]
        }
    }
    </script>
</head>
<body>
    <header>
        <nav>
            <a href="/" class="logo">
                <?php
                require_once __DIR__ . '/php/helpers/logo-renderer.php';
                echo renderLogo();
                ?>
            </a>
            <button class="mobile-menu-toggle" aria-label="Toggle menu">☰</button>
            <ul class="nav-links">
                <li><a href="/">Home</a></li>
                <li><a href="/services.php">Services</a></li>
                <li><a href="/about.php">About</a></li>
                <li><a href="/gallery.php">Gallery</a></li>
                <li><a href="/contact.php">Contact</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <section class="hero">
            <div class="hero-content">
                <h1><?php echo htmlspecialchars($pageHeroTitle); ?></h1>
                <p><?php echo htmlspecialchars($pageHeroSubtitle); ?></p>
                <a href="/contact.php" class="cta-button">Get Free Estimate</a>
            </div>
        </section>

        <?php
        // Render sections from database/merged defaults
        foreach ($pageSections as $section) {
            // Skip inactive sections
            if (isset($section['is_active']) && !$section['is_active']) {
                continue;
            }
            
            $sectionKey = $section['section_key'] ?? '';
            $sectionType = $section['section_type'] ?? 'html';
            $sectionContent = $section['section_content'] ?? '';
            $sectionTitle = $section['section_title'] ?? '';
            
            // Skip hero section (handled separately above)
            if ($sectionKey === 'hero') {
                continue;
            }
            
            // Render intro sections before dynamic content
            if ($sectionKey === 'services_intro') {
                echo '<section id="services">';
                if (!empty($sectionTitle)) {
                    echo '<h2 class="section-title">' . htmlspecialchars($sectionTitle) . '</h2>';
                }
                if ($sectionType === 'html') {
                    echo $sectionContent;
                } else {
                    echo '<p class="text-center" style="font-size: 1.1rem; line-height: 1.8; margin-bottom: 2rem;">' . nl2br(htmlspecialchars($sectionContent)) . '</p>';
                }
            } elseif ($sectionKey === 'testimonials_intro') {
                // Skip testimonials_intro here - will render before testimonials section
                continue;
            } else {
                // Render other sections normally
                echo '<section>';
                if (!empty($sectionTitle)) {
                    echo '<h2 class="section-title">' . htmlspecialchars($sectionTitle) . '</h2>';
                }
                echo '<div style="max-width: 900px; margin: 0 auto; padding: 2rem;">';
                if ($sectionType === 'html') {
                    echo $sectionContent;
                } else {
                    echo '<p style="font-size: 1.1rem; line-height: 1.8;">' . nl2br(htmlspecialchars($sectionContent)) . '</p>';
                }
                echo '</div>';
                echo '</section>';
            }
        }
        ?>

        <section id="services">
            <?php if (empty($pageSections) || !array_search('services_intro', array_column($pageSections, 'section_key'))): ?>
                <h2 class="section-title">Our Services</h2>
            <?php endif; ?>
            <div class="services-grid">
                <?php if (empty($services)): ?>
                    <div style="grid-column: 1 / -1; text-align: center; padding: 2rem;">
                        <p style="font-size: 1.1rem; color: var(--text-light);">Services coming soon!</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($services as $service): ?>
                        <div class="service-card">
                            <div class="service-icon"><?php echo htmlspecialchars($service['service_icon'] ?? '🎨'); ?></div>
                            <h3><?php echo htmlspecialchars($service['service_name']); ?></h3>
                            <p><?php echo htmlspecialchars($service['service_description'] ?? ''); ?></p>
                            <?php if (!empty($service['service_details'])): 
                                $details = is_string($service['service_details']) ? json_decode($service['service_details'], true) : $service['service_details'];
                                if (is_array($details) && !empty($details)): ?>
                                    <ul style="text-align: left; margin-top: 1rem; padding-left: 1.5rem;">
                                        <?php foreach ($details as $detail): ?>
                                            <li><?php echo htmlspecialchars($detail); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>

        <section id="gallery-preview">
            <h2 class="section-title">Our Work</h2>
            <p class="text-center" style="margin-bottom: 2rem;">See the transformation we've created for our clients in Tomball and the North Houston area.</p>
            <div class="gallery-grid">
                <?php if (empty($galleryPreviewImages)): ?>
                    <div style="grid-column: 1 / -1; text-align: center; padding: 2rem;">
                        <p style="font-size: 1.1rem; color: var(--text-light);">Gallery images coming soon!</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($galleryPreviewImages as $image): ?>
                        <div class="gallery-item" data-category="<?php echo htmlspecialchars($image['category'] ?? 'all'); ?>">
                            <img src="<?php echo htmlspecialchars($image['image_path']); ?>" 
                                 alt="<?php echo htmlspecialchars($image['image_alt'] ?? $image['image_title'] ?? 'Gallery image'); ?>"
                                 loading="lazy">
                            <div class="gallery-overlay">
                                <h4><?php echo htmlspecialchars($image['image_title'] ?? 'Our Work'); ?></h4>
                                <?php if (!empty($image['image_description'])): ?>
                                    <p><?php echo htmlspecialchars($image['image_description']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <div class="text-center mt-2">
                <a href="/gallery.php" class="cta-button">View Full Gallery</a>
            </div>
        </section>

        <section class="testimonials">
            <?php 
            // Find and render testimonials_intro section if it exists
            $testimonialsIntro = null;
            foreach ($pageSections as $s) {
                if (($s['section_key'] ?? '') === 'testimonials_intro') {
                    $testimonialsIntro = $s;
                    break;
                }
            }
            
            if ($testimonialsIntro):
                // Render testimonials intro section
                $sectionTitle = $testimonialsIntro['section_title'] ?? '';
                $sectionType = $testimonialsIntro['section_type'] ?? 'html';
                $sectionContent = $testimonialsIntro['section_content'] ?? '';
                
                if (!empty($sectionTitle)) {
                    echo '<h2 class="section-title">' . htmlspecialchars($sectionTitle) . '</h2>';
                }
                if ($sectionType === 'html') {
                    echo $sectionContent;
                } else {
                    echo '<p class="text-center" style="font-size: 1.1rem; line-height: 1.8; margin-bottom: 2rem;">' . nl2br(htmlspecialchars($sectionContent)) . '</p>';
                }
            else: ?>
                <h2 class="section-title">What Our Clients Say</h2>
            <?php endif; ?>
            <div class="testimonials-grid">
                <?php if (empty($testimonials)): ?>
                    <div style="grid-column: 1 / -1; text-align: center; padding: 2rem;">
                        <p style="font-size: 1.1rem; color: var(--text-light);">Testimonials coming soon!</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($testimonials as $testimonial): ?>
                        <div class="testimonial-card">
                            <p class="testimonial-text"><?php echo htmlspecialchars($testimonial['testimonial_text']); ?></p>
                            <p class="testimonial-author">- <?php echo htmlspecialchars($testimonial['author_name']); ?><?php echo !empty($testimonial['author_location']) ? ', ' . htmlspecialchars($testimonial['author_location']) : ''; ?></p>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>

        <section id="cta-section" style="background: linear-gradient(135deg, var(--primary-green) 0%, var(--dark-green) 100%); color: white; text-align: center; padding: 4rem 2rem;">
            <h2 style="color: white; margin-bottom: 1rem;">Ready to Transform Your Space?</h2>
            <p style="font-size: 1.2rem; margin-bottom: 2rem; opacity: 0.95;">Contact us today for a free estimate. We serve Tomball, TX and the entire North Houston area.</p>
            <a href="/contact.php" class="cta-button" style="background-color: white; color: var(--primary-green);">Get Your Free Estimate</a>
        </section>
    </main>

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

    <!-- Lightbox -->
    <div id="lightbox" class="lightbox">
        <button class="lightbox-close">&times;</button>
        <button class="lightbox-nav lightbox-prev">&#8249;</button>
        <button class="lightbox-nav lightbox-next">&#8250;</button>
        <div class="lightbox-content">
            <img id="lightbox-img" src="" alt="">
        </div>
    </div>

    <script src="/js/main.js"></script>
    <?php
    // Add click tracking JavaScript
    require_once __DIR__ . '/php/helpers/statistics-tracker.php';
    echo getStatisticsTrackingScript('index');
    ?>
</body>
</html>

