<?php
// /api/fetch_products.php
require_once __DIR__ . '/../includes/functions.php';

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

try {
    // --- Get parameters ---
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 12;
    $offset = ($page - 1) * $limit;
    $search_query = trim($_GET['q'] ?? '');
    $category_slug = trim($_GET['category'] ?? ''); // Get the category slug
    $sort_by = $_GET['sort'] ?? 'newest';

    // --- Build Query ---
    $base_sql = "FROM products p 
                 JOIN partners pa ON p.partner_user_id = pa.user_id 
                 JOIN users u ON p.partner_user_id = u.id 
                 LEFT JOIN categories c ON p.category_id = c.id 
                 WHERE pa.status = 'active'";
    $params = [];
    $types = '';

    if (!empty($search_query)) {
        $base_sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
        $search_term = "%{$search_query}%";
        array_push($params, $search_term, $search_term);
        $types .= 'ss';
    }
    
    // --- CATEGORY FILTERING LOGIC ADDED ---
    if (!empty($category_slug)) {
        $base_sql .= " AND c.slug = ?";
        array_push($params, $category_slug);
        $types .= 's';
    }
    // --- END OF NEW LOGIC ---

    // --- Count Total ---
    $count_stmt = $conn->prepare("SELECT COUNT(p.id) " . $base_sql);
    if (!empty($types)) $count_stmt->bind_param($types, ...$params);
    $count_stmt->execute();
    $total_items = $count_stmt->get_result()->fetch_row()[0];
    $count_stmt->close();

    // --- Fetch Data ---
    $data_sql = "
        SELECT 
            p.id, p.name as title, p.description, p.price, p.created_at, u.username as seller_name, u.is_verified, p.condition,
            (SELECT pi.image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_thumbnail DESC, pi.id ASC LIMIT 1) as thumbnail_url
        " . $base_sql;
    
    switch ($sort_by) {
        case 'price_asc': $data_sql .= " ORDER BY p.price ASC"; break;
        case 'price_desc': $data_sql .= " ORDER BY p.price DESC"; break;
        default: $data_sql .= " ORDER BY p.created_at DESC"; break;
    }
    $data_sql .= " LIMIT ? OFFSET ?";
    array_push($params, $limit, $offset);
    $types .= 'ii';

    $stmt = $conn->prepare($data_sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $products = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // --- Format Results ---
    $formatted_items = array_map(function ($product) {
        return [
            'id' => $product['id'],
            'type' => 'product',
            'slug' => create_slug($product['title']),
            'title' => escape($product['title']),
            'price_formatted' => '₦' . number_format($product['price']),
            'thumbnail_url' => $product['thumbnail_url'] ? escape($product['thumbnail_url']) : 'assets/images/placeholder.png',
            'is_promoted' => false,
            'is_verified' => (bool)$product['is_verified'],
            'seller_name' => escape($product['seller_name']),
            'condition' => escape($product['condition']),
            'created_at' => $product['created_at'],
            'border_class' => 'border-l-4 border-green-500'
        ];
    }, $products);

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

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'An internal server error occurred.']);
}