<?php
// /api/fetch_homepage_items.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/functions.php';

header('Content-Type: application/json');

if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed: ' . $conn->connect_error]);
    exit;
}

try {
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 20; // Number of items to fetch per request
    $offset = ($page - 1) * $limit;

    $promoted_ads = [];
    $latest_ads = [];

    // --- Step 1: Fetch Promoted Ads (ONLY on the first page) ---
    if ($page === 1) {
        // MODIFIED: Added the JOIN to the 'categories' table to match your working file.
        $ad_stmt = $conn->prepare("
            SELECT a.id, a.title, a.slug, a.price, a.currency, a.location, a.condition, a.description,
                   c.name as category_name, u.is_verified, TRUE as is_promoted, 'ad' as type,
                   (SELECT i.image_url FROM ad_images i WHERE i.ad_id = a.id AND i.is_thumbnail = 1 LIMIT 1) as thumbnail_url
            FROM ads a
            JOIN categories c ON a.category_id = c.id
            JOIN users u ON a.user_id = u.id
            LEFT JOIN user_subscriptions us ON a.user_subscription_id = us.id
            LEFT JOIN subscriptions s ON us.subscription_id = s.id
            WHERE a.status = 'active'
              AND a.promotion_expiry_date > NOW()
              AND s.promotion_type IN ('everywhere', 'listing')
            ORDER BY RAND()
            LIMIT 10
        ");
        if ($ad_stmt === false) {
            error_log('Promoted ads query prepare failed: ' . $conn->error);
        } else {
            $ad_stmt->execute();
            $promoted_ads = $ad_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $ad_stmt->close();
        }
    }

    // --- Step 2: Fetch Latest Ads (for ALL pages) ---
    // MODIFIED: Added the JOIN to the 'categories' table here as well.
    $latest_stmt = $conn->prepare("
        SELECT a.id, a.title, a.slug, a.price, a.currency, a.location, a.condition, a.description,
               c.name as category_name, u.is_verified, FALSE as is_promoted, 'ad' as type,
               (SELECT i.image_url FROM ad_images i WHERE i.ad_id = a.id AND i.is_thumbnail = 1 LIMIT 1) as thumbnail_url
        FROM ads a
        JOIN categories c ON a.category_id = c.id
        JOIN users u ON a.user_id = u.id
        WHERE a.status = 'active' AND (a.promotion_expiry_date IS NULL OR a.promotion_expiry_date <= NOW())
        ORDER BY a.created_at DESC
        LIMIT ? OFFSET ?
    ");
    if ($latest_stmt === false) {
        throw new Exception('Latest ads query prepare failed: ' . $conn->error);
    }
    $latest_stmt->bind_param("ii", $limit, $offset);
    $latest_stmt->execute();
    $latest_ads = $latest_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $latest_stmt->close();
    
    // --- Step 3: Combine and Return ---
    $combined_items = array_merge($promoted_ads, $latest_ads);
    
    if ($page === 1) {
        shuffle($combined_items);
    }

    $formatted_items = array_map(function($item) {
        $item['price_formatted'] = format_price($item['price'] ?? 0, $item['currency'] ?? 'NGN');
        if (empty($item['thumbnail_url'])) {
            $item['thumbnail_url'] = 'assets/images/placeholder.png';
        }
        return $item;
    }, $combined_items);

    echo json_encode([
        'items' => $formatted_items,
        'page' => $page,
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'An API error occurred: ' . $e->getMessage()]);
}