<?php
require_once 'conn.php';
checkLogin();

$product = $_GET['productId'] ?? '';
$country = $_GET['country'] ?? '';
$str = "";

$result = $conn->query("SELECT ProductName, ProductImg, unit, moq, tips FROM products WHERE id=" . (int)$product);
if ($row = $result->fetch_assoc()) {
    $productname = $row['ProductName'];
    $productImg = $row['ProductImg'];
    $unit = $row['unit'];
    $moq = $row['moq'] ?? '无数量限制';
    $tips = textUnCode($row['tips']);
    
    $str = "<td>" . htmlspecialcharsFix($productname) . "</td><td><img src=\"" . htmlspecialcharsFix($productImg) . "\"></td><td>" . htmlspecialcharsFix($moq) . "</td>";
}

// Check if product can be sold in the region
$result = $conn->query("SELECT * FROM products WHERE (nosale LIKE '" . $conn->real_escape_string($country) . "%' 
                        OR nosale LIKE '%," . $conn->real_escape_string($country) . ",%' 
                        OR nosale LIKE '%" . $conn->real_escape_string($country) . "') 
                        AND Id=" . (int)$product);

if ($row = $result->fetch_assoc()) {
    $str .= "<td class=\"nosale\">产品无法在该地区销售,请勿报价。<br>" . textUnCode($row['note']) . "</td>";
} else {
    // Get price information for the specific area
    $result = $conn->query("SELECT DISTINCT num, price FROM price 
                           WHERE productId=" . (int)$product . " AND AreaId=" . (int)$country . " 
                           ORDER BY num ASC");
    
    if ($result->num_rows > 0) {
        $str .= "<td><ul>";
        while ($row = $result->fetch_assoc()) {
            $str .= "<li>订单数量:≥" . htmlspecialcharsFix($row['num']) . 
                   "<span class=\"unit\">" . htmlspecialcharsFix($unit) . "</span>" .
                   "<span class=\"price\">" . htmlspecialcharsFix($row['price']) . "</span>RMB</li>";
        }
        $str .= "</ul></td><td>" . htmlspecialcharsFix($tips) . "</td>";
    } else {
        // Get default price information
        $result = $conn->query("SELECT DISTINCT num, price FROM price 
                               WHERE productId=" . (int)$product . " AND AreaId=0 
                               ORDER BY num ASC");
        $str .= "<td><ul>";
        while ($row = $result->fetch_assoc()) {
            $str .= "<li>订单数量:≥" . htmlspecialcharsFix($row['num']) . 
                   "<span class=\"unit\">" . htmlspecialcharsFix($unit) . "</span>" .
                   "<span class=\"price\">" . htmlspecialcharsFix($row['price']) . "</span>RMB</li>";
        }
        $str .= "</ul></td><td>" . htmlspecialcharsFix($tips) . "</td>";
    }
}

echo $str;