<?php
error_reporting( E_ALL );

ini_set( 'display_errors', 0 );
/**

 * SEO Landing Page Template
 * 

 * Displays auto-generated landing pages for popular searches

 * URL structure: /categories/[slug]/

 */

require_once __DIR__ . '/../lib/database_adapter.php';

require_once __DIR__ . '/../config/seo.php';

$db = new DatabaseAdapter();



// Get slug from URL (support both /categories/slug/ and /categories/?slug=slug formats)

$slug = '';


// Check for query parameter first (for when mod_rewrite isn't available)

if (isset($_GET['slug'])) {

    $slug = $_GET['slug'];

} else {

    // Try to extract from URL path

    $requestUri = $_SERVER['REQUEST_URI'];

    $requestUri = strtok($requestUri, '?'); // Remove query string

    

    if (preg_match('#/categories/([^/]+)/?$#', $requestUri, $matches)) {

        $slug = $matches[1];

    }

}



// If no slug or slug is "index.php", show browse page

if (empty($slug) || $slug === 'index.php' || $slug === 'index') {

    require_once __DIR__ . '/browse.php';

    exit;

}


// Get landing page from database

$page = $db->fetchAll('SELECT * FROM landing_pages WHERE slug = ? AND is_published = 1', [$slug]);



if (empty($page) || !is_array($page) || !isset($page[0])) {

    // Page not found

    header('HTTP/1.0 404 Not Found');

    require_once __DIR__ . '/../includes/header2.php';

    echo '<div class="container my-5 text-center">';

    echo '<h1>Page Not Found</h1>';

    echo '<p>The page you are looking for does not exist.</p>';

    echo '<a href="/" class="btn btn-primary">Go to Homepage</a>';

    echo '</div>';

    require_once __DIR__ . '/../includes/footer.php';

    exit;

}



$page = $page[0];

// Validate that $page is an array
if (!is_array($page)) {
    error_log('Categories page error: $page is not an array. Type: ' . gettype($page) . ', Value: ' . print_r($page, true));
    header('HTTP/1.0 500 Internal Server Error');
    require_once __DIR__ . '/../includes/header2.php';
    echo '<div class="container my-5 text-center">';
    echo '<h1>Error</h1>';
    echo '<p>There was an error loading this page. Please try again later.</p>';
    echo '<a href="/" class="btn btn-primary">Go to Homepage</a>';
    echo '</div>';
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}



// Increment view count

$db->query('UPDATE landing_pages SET view_count = view_count + 1 WHERE id = ?', [$page['id']]);



// Get FAQs for this page

$faqs = [];
if (isset($page['id'])) {
    $faqs = $db->fetchAll('SELECT * FROM landing_page_faqs WHERE landing_page_id = ? ORDER BY display_order ASC', [$page['id']]);
}



// Set SEO variables

$page_title = $page['title'];

$meta_description = $page['meta_description'];

$meta_keywords = $page['meta_keywords'];

$canonical_url = '/categories/' . $page['slug'] . '/';

// Set Open Graph data for social sharing

$og_data = [

    'title' => $page['h1_title'],

    'description' => $page['meta_description'],

    'url' => 'https://searchmusicgear.com' . $canonical_url,

    'image' => !empty($page['image_url']) ? 'https://searchmusicgear.com' . $page['image_url'] : 'https://searchmusicgear.com/assets/imgs/search-header.jpg',

    'type' => 'website'

];



// Breadcrumbs

$breadcrumbs = [

    ['title' => 'Home', 'url' => '/'],

    ['title' => 'Browse', 'url' => '/categories/'],

    ['title' => $page['h1_title'] ?? $page['title'] ?? 'Category', 'url' => '']

];



// Generate structured data

$structured_data = generateBreadcrumbSchema($breadcrumbs);



// Get search results for this query

$search_query = $page['search_query'] ?? $page['title'] ?? '';

$search_url = '/search/?q=' . urlencode($search_query); // platforms=both is default



// Fetch preview listings (6 items - 3 from each platform)

// Use caching to avoid excessive API calls

require_once __DIR__ . '/../lib/cache.php';

$cacheKey = 'category_preview_' . $page['slug'];

$preview_listings = cache_remember($cacheKey, 1800, function() use ($search_query) { // 30 min cache

    $listings = [];

    

    try {

        // Fetch from Reverb (3 items)

    $reverbUrl = 'https://reverb.com/api/listings/all?query=' . urlencode($search_query) . '&per_page=3';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $reverbUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);



    curl_close($ch);

    // Debug logging
    error_log("Reverb API Call - HTTP Code: $httpCode, Query: $search_query");
    if ($curlError) {
        error_log("Reverb API cURL Error: $curlError");
    }

    if ($response) {

        $data = json_decode($response, true);
        error_log("Reverb API Response decoded, listings count: " . count($data['listings'] ?? []));

        if (!empty($data['listings'])) {
            
            require_once __DIR__ . '/../config/affiliates.php';

            foreach ($data['listings'] as $item) {
                
                // Get URL and add affiliate tracking
                $itemUrl = $item['_links']['web']['href'] ?? '';
                $itemUrl = addReverbAffiliateTracking($itemUrl);

                $listings[] = [

                    'id' => $item['id'] ?? '',

                    'listing_id' => $item['id'] ?? '',

                    'title' => $item['title'] ?? '',

                    'price' => '$' . number_format($item['price']['amount'] ?? 0, 2),

                    'image' => $item['_links']['photo']['href'] ?? '',

                    'url' => $itemUrl,

                    'platform' => 'Reverb',

                    'condition' => $item['condition']['display_name'] ?? '',

                    'make' => $item['make'] ?? '',

                    'model' => $item['model'] ?? ''

                ];

            }

        } else {
            error_log("Reverb API: No listings found in response");
        }

    } else {
        error_log("Reverb API: No response received");
    }

    

    // Fetch from eBay (3 items)

    require_once __DIR__ . '/../api/ebay_api_client.php';

    $ebayClient = new EbayApiClient(

        EBAY_CLIENT_ID,

        EBAY_CLIENT_SECRET

    );

    $ebayResults = $ebayClient->findItems($search_query, [

        'per_page' => 3,

        'page' => 1,

        'category_id' => '619' // Musical Instruments

    ]);

    

    if (!empty($ebayResults['items'])) {

        require_once __DIR__ . '/../config/affiliates.php';

        foreach ($ebayResults['items'] as $item) {

            $itemUrl = $item['viewItemURL'] ?? '';

            $itemUrl = addAffiliateTracking($itemUrl, 'eBay');

            

            $listings[] = [

                'id' => $item['itemId'] ?? '',

                'listing_id' => $item['itemId'] ?? '',

                'title' => $item['title'] ?? '',

                'price' => '$' . number_format((float)($item['price']['amount'] ?? 0), 2),

                'image' => $item['galleryURL'] ?? '',

                'url' => $itemUrl,

                'platform' => 'eBay',

                'condition' => $item['condition'] ?? 'Used',

                'make' => '',

                'model' => ''

            ];

        }

    }

    } catch (Exception $e) {

        error_log('Landing page preview error: ' . $e->getMessage());

    }


    return $listings;

});



require_once __DIR__ . '/../includes/header2.php';

?>

        <!-- Breadcrumbs -->

    <?php echo renderBreadcrumbs($breadcrumbs); ?>

<div id="hero-outer">

<div class="container">

    <!-- Hero Section with Image -->

    <div class="row align-items-center">

        <div class="col-lg-6">

            <h1 class="mb-3"><?php echo htmlspecialchars($page['h1_title']); ?></h1>

            <div class="mb-4">

                <?php 
                // Use custom intro or auto-generate
                if (!empty($page['intro_text'])) {
                    echo $page['intro_text'];
                } else {
                    $queryText = $page['search_query'] ?? $page['title'] ?? 'items';
                    echo 'Looking for <strong>' . htmlspecialchars($queryText) . '</strong>? You\'ve come to the right place. We search both eBay and Reverb to show you all available ' . htmlspecialchars($queryText) . ' in one place. Browse listings from both platforms, filter by price and condition, and find exactly what you\'re looking for.<br><br>Browse our complete selection of musical instruments and gear from trusted sellers on eBay and Reverb.';
                }
                ?>

            </div>

            

            <!-- CTA Buttons -->

            <div class="d-flex gap-3 mb-4">

                <a href="<?php echo $search_url; ?>" class="btn btn-primary btn-lg">

                    &#128269; View All Listings

                </a>


            </div>

            

            <!-- Quick Stats -->

            <div class="d-flex gap-4 text-muted small">

                <div>

                    <i class="bi bi-clock"></i> Real-time listings

                </div>

                <div>

                    <i class="bi bi-shop"></i> eBay + Reverb

                </div>

                <div>

                    <i class="bi bi-bell"></i> Price alerts

                </div>

            </div>

        </div>

                <div class="col-lg-6 mb-4 mb-lg-0 d-none d-sm-block">

            <?php 

            // Get image (custom or default)

            $image_url = !empty($page['image_url']) ? $page['image_url'] : '/assets/images/landing-pages/default.jpg';

            ?>

            <img src="<?php echo htmlspecialchars($image_url); ?>" 

                 alt="<?php echo htmlspecialchars($page['h1_title']); ?>" 

                 class="img-fluid rounded shadow-sm"

                 style="width: 100%; height: 400px; object-fit: cover;">

        </div>

    </div>

    

    </div><!--container-->

</div><!--hero-->



<div class="container my-4">

    <?php require_once __DIR__ . '/../includes/affiliate-disclosure.php'; ?>

    <!-- Preview Listings -->

    <?php if (!empty($preview_listings)): ?>

    <div class="row mb-5">

        <div class="col-12">

            <h2 class="mb-3">Latest <?php echo htmlspecialchars(isset($page['search_query']) ? $page['search_query'] : (isset($page['title']) ? $page['title'] : 'Listings')); ?> Listings</h2>

            <p class="text-muted mb-4">Real-time listings from eBay and Reverb</p>

            

            <div class="row g-4">

                <?php foreach ($preview_listings as $item): ?>

                <div class="col-md-4 col-sm-6">

                    <div class="card h-100 hover-lift">

                        <a href="<?php echo htmlspecialchars($item['url']); ?>" target="_blank" class="text-decoration-none">

                            <?php if (!empty($item['image'])): ?>

                            <img src="<?php echo htmlspecialchars($item['image']); ?>" 

                                 class="card-img-top" 

                                 alt="<?php echo htmlspecialchars($item['title']); ?>"

                                 style="height: 200px; object-fit: cover;">

                            <?php endif; ?>

                            <div class="card-body">

                                <div class="d-flex justify-content-between align-items-start mb-2">

                                    <span class="badge bg-<?php echo $item['platform'] === 'eBay' ? 'primary' : 'success'; ?>">

                                        <?php echo htmlspecialchars($item['platform']); ?>

                                    </span>

                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($item['condition']); ?></span>

                                </div>

                                <h5 class="card-title" style="font-size: 0.95rem; line-height: 1.3;">

                                    <?php echo htmlspecialchars(substr($item['title'], 0, 80)); ?>

                                    <?php if (strlen($item['title']) > 80) echo '...'; ?>

                                </h5>

                                <p class="card-text">

                                    <strong class="text-success fs-5"><?php echo htmlspecialchars($item['price']); ?></strong>

                                </p>

                            </div>

                        </a>

                        <!-- Watchlist Button -->
                        <div class="card-footer bg-white border-top-0 pt-0 pb-2 px-3">
                            <button onclick="addToGoodBuys(<?php echo htmlspecialchars(json_encode($item)); ?>)" 
                                    class="btn btn-sm btn-success w-100" 
                                    style="font-size: 0.75rem; padding: 0.25rem 0.5rem;">
                                + Save for Later
                            </button>
                        </div>

                    </div>

                </div>

                <?php endforeach; ?>

            </div>

            

            <div class="text-center mt-4">

                <a href="<?php echo $search_url; ?>" class="btn btn-primary btn-lg">

                    View All <?php echo htmlspecialchars($page['search_query'] ?? $page['title'] ?? 'Listings'); ?> &rarr;

                </a>

            </div>

        </div>

    </div>

    <?php endif; ?>

    

    <!-- Product/Brand History Section (only if content exists) -->

    <?php if (!empty($page['history_text'])): ?>

    <div class="row mb-5">

        <div class="col-12">

            <div class="card border-0 bg-light">

                <div class="card-body p-4">

                    <h2 class="mb-3">&#128220; History &amp; Background</h2>

                    <div class="history-content">

                        <?php echo $page['history_text']; ?>

                    </div>

                </div>

            </div>

        </div>

    </div>

    <?php endif; ?>

    

    <!-- FAQ Section -->

    <?php if (!empty($faqs)): ?>

    <div class="row mb-5">

        <div class="col-12">

            <h2>Frequently Asked Questions</h2>

            <div class="accordion" id="faqAccordion">

                <?php foreach ($faqs as $index => $faq): ?>

                <div class="accordion-item">

                    <h3 class="accordion-header" id="faqHeading<?php echo $index; ?>">

                        <button class="accordion-button <?php echo $index > 0 ? 'collapsed' : ''; ?>" type="button" data-bs-toggle="collapse" data-bs-target="#faqCollapse<?php echo $index; ?>" aria-expanded="<?php echo $index === 0 ? 'true' : 'false'; ?>">

                            <?php echo htmlspecialchars($faq['question']); ?>

                        </button>

                    </h3>

                    <div id="faqCollapse<?php echo $index; ?>" class="accordion-collapse collapse <?php echo $index === 0 ? 'show' : ''; ?>" aria-labelledby="faqHeading<?php echo $index; ?>">

                        <div class="accordion-body">

                            <?php echo nl2br(htmlspecialchars($faq['answer'])); ?>

                        </div>

                    </div>

                </div>

                <?php endforeach; ?>

            </div>

        </div>

    </div>

    <?php endif; ?>

    

    <!-- Related Searches -->

    <div class="row mb-5">

        <div class="col-12">

            <h3>Related Searches</h3>

            <div class="d-flex flex-wrap gap-2">

                <?php

                // Get related searches from same category
                $related = [];
                
                // Only fetch related if we have valid category and slug
                if (isset($page['category']) && isset($page['slug']) && is_array($page)) {
                    try {
                        $related = $db->fetchAll(
                            'SELECT slug, h1_title FROM landing_pages WHERE category = ? AND slug != ? AND is_published = 1 ORDER BY view_count DESC LIMIT 10', 
                            [$page['category'], $page['slug']]
                        );
                    } catch (Exception $e) {
                        error_log('Error fetching related searches: ' . $e->getMessage());
                        $related = [];
                    }
                }

                if (!empty($related) && is_array($related)) {
                    foreach ($related as $rel) {
                        if (is_array($rel) && isset($rel['slug']) && isset($rel['h1_title'])) {
                            echo '<a href="/categories/' . htmlspecialchars($rel['slug']) . '/" class="badge bg-primary text-decoration-none fs-6">';
                            echo htmlspecialchars($rel['h1_title']);
                            echo '</a>';
                        }
                    }
                }

                ?>

            </div>

        </div>

    </div>

</div>



<!-- Include alert signup modal -->

<?php if (file_exists(__DIR__ . '/../js/alert-signup.js')): ?>

<script src="/js/alert-signup.js"></script>

<?php endif; ?>

<!-- Include common.js for watchlist functionality -->
<script src="/lib/common.js"></script>



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



