<?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;
}

$input = trim($_POST['input'] ?? '');
$quotation_id = (int)($_POST['quotation_id'] ?? 0);

if (!$input || !$quotation_id) {
    echo json_encode(['success' => false, 'error' => '請輸入內容']);
    exit;
}

// 獲取已有的類別和項目資料庫
$parent_categories = $pdo->query("SELECT category_name FROM quote_parent_categories ORDER BY category_name ASC")->fetchAll(PDO::FETCH_COLUMN);
$existing_items = $pdo->query("SELECT id, category_name, item_name, unit_price, unit_type FROM quote_categories ORDER BY category_name ASC")->fetchAll();

// 構建系統提示詞
$system_prompt = "你是一個專業的香港裝修工程報價助理。你的工作是分析用戶輸入的裝修需求，將其轉換為結構化的報價項目清單。

以下是系統已有的類別和常用項目，請盡量匹配使用：

已有的類別：" . implode('、', $parent_categories) . "

已有的常用項目：
";
foreach ($existing_items as $item) {
    $system_prompt .= "- [{$item['category_name']}] {$item['item_name']} | 單價: \${$item['unit_price']} | 單位: {$item['unit_type']}\n";
}

$system_prompt .= "\n請嚴格按照以下 JSON 格式回覆（只回覆 JSON，不用 Markdown 程式碼塊）：
{
  \"items\": [
    {
      \"category_name\": \"匹配或新增大類名稱\",
      \"description\": \"項目描述（詳細說明工作內容）\",
      \"quantity\": 數量（數字）,
      \"unit_type\": \"單位\",
      \"price\": 單價（數字，若不確定可估算合理價格）,
      \"matched_item_id\": 匹配到的現有項目ID（若無匹配則為 null）
    }
  ],
  \"new_categories\": [\"需要新增大類的名稱\"],
  \"new_items\": [
    {
      \"category_name\": \"所屬大類\",
      \"item_name\": \"項目名稱\",
      \"unit_price\": 單價,
      \"unit_type\": \"單位\"
    }
  ]
}

要求：
1. 如果用戶輸入的項目可以匹配現有常用項目，請在 matched_item_id 填入對應 ID，並使用該項目的單價
2. 如果用戶輸入的項目有新的有用項目，請在 new_items 中列出，系統會自動新增到常用項目庫
3. 如果用戶輸入的類別不在已有類別中，請在 new_categories 中列出
4. quantity（數量）如果用戶有指定就使用，否則預設為 1
5. 所有回覆必須是繁體中文";

// 準備發送給 DeepSeek
$messages = [
    ['role' => 'system', 'content' => $system_prompt],
    ['role' => 'user', 'content' => $input]
];

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

// 呼叫 DeepSeek API
$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 . ')：' . substr($response, 0, 500)]);
    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 回傳的 JSON
// 清理可能的 markdown 程式碼塊標記
$ai_content = preg_replace('/^```(?:json)?\s*\n?|\n?```\s*$/i', '', trim($ai_content));
$parsed = json_decode($ai_content, true);

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

// 自動新增類別
if (!empty($parsed['new_categories'])) {
    $stmt = $pdo->prepare("INSERT IGNORE INTO quote_parent_categories (category_name) VALUES (?)");
    foreach ($parsed['new_categories'] as $cat_name) {
        $cat_name = trim($cat_name);
        if ($cat_name) {
            $stmt->execute([$cat_name]);
        }
    }
}

// 自動新增常用項目
if (!empty($parsed['new_items'])) {
    $stmt = $pdo->prepare("INSERT IGNORE INTO quote_categories (category_name, item_name, unit_price, unit_type) VALUES (?, ?, ?, ?)");
    foreach ($parsed['new_items'] as $new_item) {
        if (!empty($new_item['item_name'])) {
            $stmt->execute([
                $new_item['category_name'] ?? '其他',
                $new_item['item_name'],
                $new_item['unit_price'] ?? 0,
                $new_item['unit_type'] ?? '一項'
            ]);
        }
    }
}

// 獲取當前最大排序值
$stmt = $pdo->prepare("SELECT MAX(sort_order) FROM quotation_items WHERE quotation_id = ?");
$stmt->execute([$quotation_id]);
$max_sort = (int)$stmt->fetchColumn();

// 插入項目到報價單
$inserted_items = [];
$stmt = $pdo->prepare("INSERT INTO quotation_items (quotation_id, category_name, description, quantity, unit_type, price, subtotal, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

foreach ($parsed['items'] as $index => $item) {
    $qty = max(1, (float)($item['quantity'] ?? 1));
    $price = max(0, (float)($item['price'] ?? 0));
    $subtotal = $qty * $price;
    $sort = $max_sort + $index + 1;

    $stmt->execute([
        $quotation_id,
        $item['category_name'] ?? '其他',
        $item['description'] ?? '',
        $qty,
        $item['unit_type'] ?? '一項',
        $price,
        $subtotal,
        $sort
    ]);

    $inserted_items[] = [
        'id' => $pdo->lastInsertId(),
        'category_name' => $item['category_name'] ?? '其他',
        'description' => $item['description'] ?? '',
        'quantity' => $qty,
        'unit_type' => $item['unit_type'] ?? '一項',
        'price' => $price,
        'subtotal' => $subtotal
    ];
}

// 更新報價單總額
$pdo->prepare("UPDATE quotations SET total_amount = (SELECT SUM(subtotal) FROM quotation_items WHERE quotation_id = ?) WHERE id = ?")
    ->execute([$quotation_id, $quotation_id]);

echo json_encode([
    'success' => true,
    'items' => $inserted_items,
    'total' => count($inserted_items),
    'message' => '成功由 AI 生成 ' . count($inserted_items) . ' 個報價項目'
]);
