<?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'] ?? '');
if (!$input) {
    echo json_encode(['success' => false, 'error' => '請輸入單據描述']);
    exit;
}

// 取得地盤列表
$sites = $pdo->query("SELECT id, location, unit FROM sites ORDER BY location ASC")->fetchAll();
$site_list = '';
foreach ($sites as $s) $site_list .= "- {$s['location']}" . ($s['unit'] ? " {$s['unit']}" : '') . " (ID:{$s['id']})\n";

$system_prompt = "你是一個香港裝修工程的帳單報銷助理。用戶會輸入單據的資料（或語音描述），你需要提取關鍵資訊。

以下是系統中的地盤列表：
{$site_list}

請嚴格按照以下 JSON 格式回覆（只回覆 JSON，不用 Markdown）：
{
  \"site_id\": 匹配到的地盤ID（若不明確則為 null）,
  \"amount\": 金額（數字）,
  \"description\": \"項目說明的繁體中文描述\",
  \"bill_date\": \"YYYY-MM-DD\",
  \"site_name\": \"地盤名稱\"
}

要求：
1. 金額要準確提取
2. 日期如果不確定就用今天日期 " . date('Y-m-d') . "
3. 地盤要盡量匹配系統中現有的
4. 回覆必須是繁體中文";

$messages = [
    ['role' => 'system', 'content' => $system_prompt],
    ['role' => 'user', 'content' => $input]
];

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

$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,
    'site_id' => $parsed['site_id'],
    'site_name' => $parsed['site_name'] ?? '',
    'amount' => $parsed['amount'] ?? 0,
    'description' => $parsed['description'] ?? '',
    'bill_date' => $parsed['bill_date'] ?? date('Y-m-d')
]);
