<?php
require_once __DIR__ . '/../config/config.php';
requireLogin();
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => '僅接受 POST 請求']);
    exit;
}

if (empty(DEEPSEEK_API_KEY_DB)) {
    echo json_encode(['success' => false, 'error' => '請先在「系統設定」中設定 DeepSeek API Key']);
    exit;
}

$quote1_id = (int)($_POST['quote1_id'] ?? 0);
$quote2_id = (int)($_POST['quote2_id'] ?? 0);

if (!$quote1_id || !$quote2_id) {
    echo json_encode(['success' => false, 'error' => '請選擇兩份報價單']);
    exit;
}

// 獲取報價單資料
function getQuoteFull($pdo, $id) {
    $stmt = $pdo->prepare("
        SELECT q.*, c.name as company_name 
        FROM quotations q 
        JOIN quote_companies c ON q.company_id = c.id 
        WHERE q.id = ?
    ");
    $stmt->execute([$id]);
    $quote = $stmt->fetch();
    if (!$quote) return null;
    
    $stmt = $pdo->prepare("SELECT * FROM quotation_items WHERE quotation_id = ? ORDER BY sort_order ASC, id ASC");
    $stmt->execute([$id]);
    $quote['items'] = $stmt->fetchAll();
    return $quote;
}

$quote1 = getQuoteFull($pdo, $quote1_id);
$quote2 = getQuoteFull($pdo, $quote2_id);

if (!$quote1 || !$quote2) {
    echo json_encode(['success' => false, 'error' => '找不到報價單']);
    exit;
}

// 格式化報價單資料給 AI
function formatQuoteForAI($quote) {
    $text = "報價編號：{$quote['quote_no']}\n";
    $text .= "公司：{$quote['company_name']}\n";
    $text .= "項目名稱：{$quote['project_name']}\n";
    $text .= "客戶地址：{$quote['client_address']}\n";
    $text .= "總金額：$" . number_format($quote['total_amount'], 0) . "\n";
    $text .= "項目明細：\n";
    foreach ($quote['items'] as $item) {
        $text .= "- [{$item['category_name']}] {$item['description']} | 數量:{$item['quantity']} {$item['unit_type']} | 單價:\${$item['price']} | 小計:\${$item['subtotal']}\n";
    }
    return $text;
}

$quote1_text = formatQuoteForAI($quote1);
$quote2_text = formatQuoteForAI($quote2);

$system_prompt = "你是一個專業的裝修報價單對比分析助理。請仔細分析以下兩份報價單，找出它們的異同。

請嚴格按照以下 JSON 格式回覆（只回覆 JSON，不用 Markdown）：
{
  \"summary\": \"兩份報價單的整體比較（2-3句話）\",
  \"same_items\": [\"兩份報價單中相同或類似的項目及其價格對比\"],
  \"diff_items\": [\"價格不同的項目及其差異\"],
  \"unique_to_quote1\": [\"只在第一份報價單中出現的項目\"],
  \"unique_to_quote2\": [\"只在第二份報價單中出現的項目\"],
  \"price_comparison\": \"總價格對比分析\",
  \"recommendation\": \"如果有需要，哪一份報價更適合及原因\"
}

回覆必須是繁體中文。";

$messages = [
    ['role' => 'system', 'content' => $system_prompt],
    ['role' => 'user', 'content' => "以下是兩份報價單的詳細資料：\n\n--- 報價單 A ---\n{$quote1_text}\n\n--- 報價單 B ---\n{$quote2_text}"]
];

$payload = json_encode([
    'model' => 'deepseek-chat',
    'messages' => $messages,
    'temperature' => 0.3,
    'max_tokens' => 4096
]);

$ch = curl_init(DEEPSEEK_API_URL);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Authorization: Bearer ' . DEEPSEEK_API_KEY_DB],
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 60
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

if ($curl_error) {
    echo json_encode(['success' => false, 'error' => 'API 請求失敗：' . $curl_error]);
    exit;
}
if ($http_code !== 200) {
    echo json_encode(['success' => false, 'error' => 'API 返回錯誤 (HTTP ' . $http_code . ')']);
    exit;
}

$result = json_decode($response, true);
$ai_content = $result['choices'][0]['message']['content'] ?? '';
if (!$ai_content) {
    echo json_encode(['success' => false, 'error' => 'AI 回覆為空']);
    exit;
}

$ai_content = preg_replace('/^```(?:json)?\s*\n?|\n?```\s*$/i', '', trim($ai_content));
$parsed = json_decode($ai_content, true);

if (!$parsed) {
    echo json_encode(['success' => false, 'error' => 'AI 回覆格式錯誤', 'raw' => $ai_content]);
    exit;
}

echo json_encode([
    'success' => true,
    'quote1_name' => $quote1['project_name'] . ' (' . $quote1['quote_no'] . ')',
    'quote2_name' => $quote2['project_name'] . ' (' . $quote2['quote_no'] . ')',
    'quote1_total' => $quote1['total_amount'],
    'quote2_total' => $quote2['total_amount'],
    'summary' => $parsed['summary'] ?? '',
    'same_items' => $parsed['same_items'] ?? [],
    'diff_items' => $parsed['diff_items'] ?? [],
    'unique_to_quote1' => $parsed['unique_to_quote1'] ?? [],
    'unique_to_quote2' => $parsed['unique_to_quote2'] ?? [],
    'price_comparison' => $parsed['price_comparison'] ?? '',
    'recommendation' => $parsed['recommendation'] ?? ''
]);
