<?php
/**
 * SEO Monitoring & Analytics Setup
 * Provides snippets and helpers for analytics integration
 * Place in: /config/analytics_config.php
 */

// ============================================
// GOOGLE ANALYTICS 4 SETUP
// ============================================

function getGoogleAnalyticsScript() {
    $gaId = 'G-XXXXXXXXXX'; // Replace with your GA4 ID
    
    return <<<HTML
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={$gaId}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{$gaId}', {
    'page_path': window.location.pathname,
    'page_title': document.title,
    'cookie_flags': 'SameSite=None;Secure'
  });
  
  // Track page views
  gtag('event', 'page_view');
</script>
<!-- End Google Analytics -->
HTML;
}

// ============================================
// GOOGLE SEARCH CONSOLE
// ============================================

function getGoogleSearchConsoleVerification() {
    // Get verification code from your GSC account
    $verificationCode = ''; // Add your verification code here
    
    if (!empty($verificationCode)) {
        return '<meta name="google-site-verification" content="' . htmlspecialchars($verificationCode) . '">' . "\n";
    }
    return '';
}

// ============================================
// FACEBOOK PIXEL
// ============================================

function getFacebookPixelScript() {
    $pixelId = ''; // Replace with your Facebook Pixel ID
    
    if (empty($pixelId)) {
        return '';
    }
    
    return <<<HTML
<!-- Facebook Pixel -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '{$pixelId}');
  fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id={$pixelId}&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel -->
HTML;
}

// ============================================
// HOTJAR HEATMAPS
// ============================================

function getHotjarScript() {
    $hotjarId = ''; // Replace with your Hotjar ID
    
    if (empty($hotjarId)) {
        return '';
    }
    
    return <<<HTML
<!-- Hotjar Tracking Code -->
<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:{$hotjarId},hjsv:6};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
<!-- End Hotjar Tracking Code -->
HTML;
}

// ============================================
// PERFORMANCE MONITORING
// ============================================

function getPerformanceTrackingScript() {
    return <<<HTML
<script>
// Track Core Web Vitals
if (window.web_vitals) {
    // Largest Contentful Paint
    web_vitals.getLCP(metric => {
        console.log('LCP:', metric.value);
        if (window.gtag) {
            gtag('event', 'page_view', {
                'lcp': metric.value
            });
        }
    });
    
    // First Input Delay
    web_vitals.getFID(metric => {
        console.log('FID:', metric.value);
        if (window.gtag) {
            gtag('event', 'page_view', {
                'fid': metric.value
            });
        }
    });
    
    // Cumulative Layout Shift
    web_vitals.getCLS(metric => {
        console.log('CLS:', metric.value);
        if (window.gtag) {
            gtag('event', 'page_view', {
                'cls': metric.value
            });
        }
    });
}

// Track custom events
document.addEventListener('DOMContentLoaded', function() {
    // Track product views
    if (window.gtag && document.querySelector('[data-product-id]')) {
        const productId = document.querySelector('[data-product-id]').dataset.productId;
        gtag('event', 'view_item', {
            'items': [{
                'item_id': productId,
                'item_name': document.title,
                'item_category': 'product'
            }]
        });
    }
    
    // Track searches
    if (window.gtag) {
        const searchInput = document.querySelector('input[type="search"]');
        if (searchInput) {
            searchInput.addEventListener('submit', function(e) {
                gtag('event', 'search', {
                    'search_term': this.value
                });
            });
        }
    }
});
</script>
HTML;
}

// ============================================
// STRUCTURED DATA HELPERS
// ============================================

function getContactPageSchema() {
    return [
        '@context' => 'https://schema.org',
        '@type' => 'Organization',
        'name' => 'Esa\'s Fashion',
        'url' => 'http://localhost/ecoms',
        'email' => 'contact@esasfashion.com',
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => 'Your Street Address',
            'addressLocality' => 'City',
            'addressRegion' => 'State',
            'postalCode' => 'ZIP',
            'addressCountry' => 'US'
        ],
        'contact' => [
            '@type' => 'ContactPoint',
            'contactType' => 'Customer Service',
            'telephone' => '+1-XXX-XXX-XXXX',
            'email' => 'contact@esasfashion.com'
        ]
    ];
}

function getLocalBusinessSchema() {
    return [
        '@context' => 'https://schema.org',
        '@type' => 'LocalBusiness',
        'name' => 'Esa\'s Fashion',
        'image' => 'http://localhost/ecoms/pics_ecom/logo.png',
        'description' => 'Premium fashion products for women',
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => 'Your Street Address',
            'addressLocality' => 'City',
            'addressRegion' => 'State',
            'postalCode' => 'ZIP',
            'addressCountry' => 'US'
        ],
        'telephone' => '+1-XXX-XXX-XXXX',
        'email' => 'contact@esasfashion.com',
        'url' => 'http://localhost/ecoms',
        'priceRange' => '$$'
    ];
}

// ============================================
// CUSTOM EVENT TRACKING HELPERS
// ============================================

/**
 * Track add to cart event
 */
function trackAddToCart($productId, $productName, $price, $currency = 'USD') {
    return <<<JS
<script>
if (window.gtag) {
    gtag('event', 'add_to_cart', {
        'items': [{
            'item_id': '$productId',
            'item_name': '$productName',
            'item_category': 'product',
            'price': $price,
            'currency': '$currency',
            'quantity': 1
        }]
    });
}
</script>
JS;
}

/**
 * Track purchase event
 */
function trackPurchase($transactionId, $value, $currency = 'USD', $items = []) {
    $itemsJson = json_encode($items);
    return <<<JS
<script>
if (window.gtag) {
    gtag('event', 'purchase', {
        'transaction_id': '$transactionId',
        'value': $value,
        'currency': '$currency',
        'items': $itemsJson
    });
}
</script>
JS;
}

/**
 * Track page scroll depth
 */
function getScrollDepthTracker() {
    return <<<JS
<script>
let maxScroll = 0;
document.addEventListener('scroll', function() {
    const scrollPercentage = (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100;
    if (scrollPercentage > maxScroll) {
        maxScroll = scrollPercentage;
    }
    
    // Track milestones
    [25, 50, 75, 100].forEach(threshold => {
        if (scrollPercentage >= threshold && scrollPercentage - 5 < threshold) {
            if (window.gtag) {
                gtag('event', 'scroll_depth', {
                    'scroll_percentage': threshold,
                    'page_path': window.location.pathname
                });
            }
        }
    });
});
</script>
JS;
}

// ============================================
// SEARCH CONSOLE SITEMAP SUBMISSION
// ============================================

/**
 * Generate Search Console submission helper
 */
function getSearchConsoleSitemapUrl() {
    return 'https://www.google.com/webmasters/tools/sitemap-list?siteUrl=http://localhost/ecoms/';
}

/**
 * Robots.txt reference
 */
function getRobotsTxtUrl() {
    return 'http://localhost/ecoms/robots.txt';
}

/**
 * Sitemap reference
 */
function getSitemapUrl() {
    return 'http://localhost/ecoms/sitemap.php';
}

// ============================================
// MONITORING CHECKLIST
// ============================================

$MONITORING_CHECKLIST = [
    'technical_seo' => [
        '✓ XML Sitemap created and submitted to GSC' => false,
        '✓ robots.txt created and optimized' => false,
        '✓ Mobile responsiveness verified' => false,
        '✓ Page speed tested with PageSpeed Insights' => false,
        '✓ SSL/HTTPS enabled' => false,
        '✓ Core Web Vitals optimized' => false,
    ],
    'on_page_seo' => [
        '✓ Meta titles optimized (50-60 chars)' => false,
        '✓ Meta descriptions optimized (150-160 chars)' => false,
        '✓ H1-H6 headings structured properly' => false,
        '✓ Images have alt text' => false,
        '✓ Internal linking implemented' => false,
        '✓ Canonical tags added' => false,
    ],
    'content_seo' => [
        '✓ Product descriptions optimized' => false,
        '✓ Blog posts 1000+ words' => false,
        '✓ Keywords naturally integrated' => false,
        '✓ Content is unique and original' => false,
        '✓ Related content linked' => false,
    ],
    'technical_structure' => [
        '✓ Schema markup implemented (Product, Article)' => false,
        '✓ Open Graph tags added' => false,
        '✓ Twitter Cards configured' => false,
        '✓ Breadcrumb schema added' => false,
        '✓ Organization schema implemented' => false,
    ],
    'analytics' => [
        '✓ Google Analytics 4 implemented' => false,
        '✓ Google Search Console connected' => false,
        '✓ Facebook Pixel installed' => false,
        '✓ Hotjar tracking enabled' => false,
        '✓ Conversion tracking setup' => false,
    ],
];
?>
