<?php
/**
 * GET /api/orders/get.php?id=123
 * Returns one order with its line items AND seller contact details, so the
 * buyer can actually arrange pickup - previously this returned product
 * info only, with no way to reach whoever they bought it from.
 * Only the buyer who placed it may view it.
 */

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

$userId = require_login();

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

$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT id, buyer_id, total_amount, status, created_at FROM orders WHERE id = ?');
$stmt->execute([$id]);
$order = $stmt->fetch();

if (!$order) {
    send_error('Order not found.', 404);
}
if ((int) $order['buyer_id'] !== $userId) {
    send_error('You can only view your own orders.', 403);
}

$stmt = $pdo->prepare('
    SELECT oi.id AS order_item_id, oi.product_id, oi.quantity, oi.unit_price, oi.status, p.name, oi.seller_id,
           (SELECT image_path FROM product_images pi WHERE pi.product_id = p.id ORDER BY sort_order ASC LIMIT 1) AS thumbnail,
           su.email AS seller_email, su.phone AS seller_phone, su.account_type AS seller_type,
           COALESCE(bp.business_name, pp.full_name) AS seller_name,
           COALESCE(bp.address, pp.address) AS seller_address,
           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 order_items oi
    JOIN products p ON p.id = oi.product_id
    JOIN users su ON su.id = oi.seller_id
    LEFT JOIN business_profiles bp ON bp.user_id = su.id
    LEFT JOIN personal_profiles pp ON pp.user_id = su.id
    WHERE oi.order_id = ?
');
$stmt->execute([$id]);
$items = $stmt->fetchAll();

$sellers = []; // deduped, one contact card per distinct seller in this order
foreach ($items as &$item) {
    $item['thumbnail_url'] = $item['thumbnail'] ? UPLOAD_URL . $item['thumbnail'] : null;
    $item['line_total'] = round((float) $item['unit_price'] * (int) $item['quantity'], 2);
    unset($item['thumbnail']);

    $sid = (int) $item['seller_id'];
    if (!isset($sellers[$sid])) {
        $sellers[$sid] = [
            'seller_id' => $sid,
            'name' => $item['seller_name'],
            'type' => $item['seller_type'],
            'email' => $item['seller_email'],
            'phone' => $item['seller_phone'],
            'address' => $item['seller_address'],
            'city' => $item['seller_city'],
            'country' => $item['seller_country'],
            'latitude' => $item['seller_latitude'],
            'longitude' => $item['seller_longitude'],
        ];
    }
    // Per-item payload stays lean - full contact details live once in `sellers` below.
    unset($item['seller_email'], $item['seller_phone'], $item['seller_type'], $item['seller_name'],
          $item['seller_address'], $item['seller_city'], $item['seller_country'],
          $item['seller_latitude'], $item['seller_longitude']);
}

$order['items'] = $items;
$order['sellers'] = array_values($sellers);

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