<?php
/**
 * GET /api/vendors/list.php
 * Public. Every account (business or personal) that currently has at
 * least one active listing - a directory buyers can browse by seller
 * rather than by product. Query params: search, country, city, page.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$where = ["p.status = 'active'", '(p.expiry_date IS NULL OR p.expiry_date >= CURDATE())'];
$params = [];

if (!empty($_GET['search'])) {
    $where[] = '(bp.business_name LIKE ? OR pp.full_name LIKE ?)';
    $term = '%' . $_GET['search'] . '%';
    array_push($params, $term, $term);
}
if (!empty($_GET['country'])) {
    $where[] = 'COALESCE(bp.country, pp.country) = ?';
    $params[] = $_GET['country'];
}
if (!empty($_GET['city'])) {
    $where[] = 'COALESCE(bp.city, pp.city) = ?';
    $params[] = $_GET['city'];
}

$whereSql = implode(' AND ', $where);

// Total distinct vendors matching the filter, for pagination - counted
// separately since the main query GROUPs product rows down to one row
// per vendor, so a plain COUNT(*) would count the wrong thing.
$countStmt = $pdo->prepare("
    SELECT COUNT(DISTINCT u.id)
    FROM products p
    JOIN users u ON u.id = p.owner_id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    WHERE $whereSql
");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT u.id, u.account_type, u.is_featured_vendor,
           COALESCE(bp.business_name, pp.full_name) AS name,
           bp.category, bp.logo_path,
           COALESCE(bp.city, pp.city) AS city,
           COALESCE(bp.country, pp.country) AS country,
           COUNT(DISTINCT p.id) AS active_listing_count,
           (SELECT AVG(rating) FROM product_reviews pr JOIN products p2 ON p2.id = pr.product_id WHERE p2.owner_id = u.id) AS avg_rating,
           (SELECT COUNT(*) FROM product_reviews pr JOIN products p2 ON p2.id = pr.product_id WHERE p2.owner_id = u.id) AS review_count
    FROM products p
    JOIN users u ON u.id = p.owner_id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    WHERE $whereSql
    GROUP BY u.id
    ORDER BY u.is_featured_vendor DESC, active_listing_count DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$vendors = $stmt->fetchAll();

foreach ($vendors as &$v) {
    $v['logo_url'] = $v['logo_path'] ? UPLOAD_URL . $v['logo_path'] : null;
    unset($v['logo_path']);
    $v['avg_rating'] = $v['avg_rating'] ? round((float) $v['avg_rating'], 1) : 0;
    $v['review_count'] = (int) $v['review_count'];
    $v['active_listing_count'] = (int) $v['active_listing_count'];
    $v['is_featured_vendor'] = (bool) $v['is_featured_vendor'];
}

send_json(true, 'OK', [
    'vendors' => $vendors,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
