<?php
/**
 * GET /api/products/get.php?id=123
 * Public - returns full product details, images, and basic seller info.
 */

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

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

$pdo = Database::connect();

$stmt = $pdo->prepare('
    SELECT p.*, c.name AS category_name,
           u.id AS seller_id, u.account_type AS seller_type,
           pp.full_name AS seller_personal_name,
           bp.business_name AS seller_business_name,
           COALESCE(bp.city, pp.city) AS seller_city,
           COALESCE(bp.country, pp.country) AS seller_country,
           COALESCE(bp.latitude, pp.latitude) AS seller_latitude,
           COALESCE(bp.longitude, pp.longitude) AS seller_longitude
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    JOIN users u ON u.id = p.owner_id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    WHERE p.id = ?
    LIMIT 1
');
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    send_error('Product not found.', 404);
}

$product['is_featured'] = (bool) $product['is_featured'];
$product['is_currently_featured'] = $product['is_featured']
    && (!$product['featured_until'] || $product['featured_until'] >= date('Y-m-d'));

$stmt = $pdo->prepare('SELECT id, image_path FROM product_images WHERE product_id = ? ORDER BY sort_order ASC');
$stmt->execute([$id]);
$imageRows = $stmt->fetchAll();

$product['images'] = array_map(fn($row) => UPLOAD_URL . $row['image_path'], $imageRows);
$product['image_ids'] = array_map(fn($row) => (int) $row['id'], $imageRows);

$stmt = $pdo->prepare('SELECT AVG(rating) AS avg_rating, COUNT(*) AS review_count FROM product_reviews WHERE product_id = ?');
$stmt->execute([$id]);
$ratingRow = $stmt->fetch();
$product['average_rating'] = $ratingRow['avg_rating'] ? round((float) $ratingRow['avg_rating'], 1) : 0;
$product['review_count'] = (int) $ratingRow['review_count'];
$product['seller_name'] = $product['seller_type'] === 'business'
    ? $product['seller_business_name']
    : $product['seller_personal_name'];
unset($product['seller_personal_name'], $product['seller_business_name']);

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