<?php
/**
 * GET /api/vendors/get.php?id=123
 * Public vendor storefront info - name, type, location (no phone/email,
 * same privacy rule as products/get.php: contact details only reveal
 * after a purchase, via orders/get.php).
 */

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

$id = (int) ($_GET['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid vendor id is required.', 422);
}

$pdo = Database::connect();
$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,
           COALESCE(bp.latitude, pp.latitude) AS latitude,
           COALESCE(bp.longitude, pp.longitude) AS longitude,
           u.created_at AS member_since
    FROM users u
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    WHERE u.id = ? AND u.account_type IN ("business", "personal")
    LIMIT 1
');
$stmt->execute([$id]);
$vendor = $stmt->fetch();

if (!$vendor) {
    send_error('Vendor not found.', 404);
}

$vendor['is_featured_vendor'] = (bool) $vendor['is_featured_vendor'];
$vendor['logo_url'] = $vendor['logo_path'] ? UPLOAD_URL . $vendor['logo_path'] : null;
unset($vendor['logo_path']);

$stmt = $pdo->prepare('
    SELECT AVG(pr.rating) AS avg_rating, COUNT(*) AS review_count
    FROM product_reviews pr JOIN products p ON p.id = pr.product_id
    WHERE p.owner_id = ?
');
$stmt->execute([$id]);
$ratingRow = $stmt->fetch();
$vendor['average_rating'] = $ratingRow['avg_rating'] ? round((float) $ratingRow['avg_rating'], 1) : 0;
$vendor['review_count'] = (int) $ratingRow['review_count'];

send_json(true, 'OK', ['vendor' => $vendor]);
