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

// 獲取員工、判工及地盤資料
$employees = $pdo->query("SELECT id, name FROM employees ORDER BY name ASC")->fetchAll();
$subcontractors = $pdo->query("SELECT id, name FROM subcontractors ORDER BY name ASC")->fetchAll();
$sites = $pdo->query("SELECT id, location, unit FROM sites WHERE status = 'active' ORDER BY location ASC")->fetchAll();

$emp_list = '';
foreach ($employees as $e) $emp_list .= "- {$e['name']} (ID:{$e['id']})\n";
$sub_list = '';
foreach ($subcontractors as $s) $sub_list .= "- {$s['name']} (ID:{$s['id']})\n";
$site_list = '';
foreach ($sites as $s) $site_list .= "- {$s['location']}" . ($s['unit'] ? " {$s['unit']}" : '') . " (ID:{$s['id']})\n";

// 試用日期：如果輸入有日期就使用該日期，否則用今天
$today = date('Y-m-d');

$system_prompt = "你是一個香港裝修地盤的開工登記助理。你的工作是分析用戶輸入的開工資訊，將其轉換為結構化的登記資料。

今天是 {$today}。

以下是系統中的員工列表：
{$emp_list}

以下是系統中的判工列表：
{$sub_list}

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

用戶可能一次輸入多個人的開工資訊，例如「今日天晉3座18樓B室，泥水師傅阿強同阿明一齊開工，做咗8個鐘，之後油漆嘅大文都嚟咗」或者「聽日將軍澳廣場清拆，陳師傅同李師傅兩個開工，做執漏」。

請嚴格按照以下 JSON 格式回覆（只回覆 JSON，不用 Markdown）：
{
  \"entries\": [
    {
      \"worker_type\": \"employee\" 或 \"subcontractor\",
      \"worker_id\": 匹配到的ID（數字，若找不到則為 null）,
      \"worker_name\": \"工人名稱\",
      \"site_id\": 匹配到的地盤ID,
      \"site_name\": \"地盤名稱\",
      \"work_date\": \"YYYY-MM-DD\",
      \"work_type\": \"工種（如泥水、油漆等）\"
    }
  ],
  \"unmatched_workers\": [\"找不到的工人名稱1\", \"找不到的工人名稱2\"],
  \"summary\": \"給用戶看的簡短總結\"
}

要求：
1. 如果用戶提到日期（今日、聽日、後日、日期），請正確轉換為 YYYY-MM-DD
2. 工人名稱要盡量匹配系統中的員工或判工，模糊匹配也可
3. 如果匹配不到工人，把名字放在 unmatched_workers 列表
4. 工種要根據上下文推斷
5. 回覆必須是繁體中文";

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

$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 || !isset($parsed['entries'])) {
    echo json_encode(['success' => false, 'error' => 'AI 回覆格式錯誤，請重試', 'raw' => $ai_content]);
    exit;
}

// 如果要求直接登記開工
$do_register = ($_POST['register'] ?? '') === '1';
$registered_count = 0;
$register_errors = [];

if ($do_register) {
    $unmatched = $parsed['unmatched_workers'] ?? [];
    if (!empty($unmatched)) {
        echo json_encode([
            'success' => false,
            'error' => '有 ' . count($unmatched) . ' 名工人找不到匹配，請先到員工管理或判工管理新增：' . implode('、', $unmatched),
            'entries' => $parsed['entries'],
            'unmatched_workers' => $unmatched,
            'summary' => $parsed['summary'] ?? ''
        ]);
        exit;
    }
    
    $stmt = $pdo->prepare("INSERT INTO work_entries (worker_type, worker_id, site_id, work_date, work_type) VALUES (?, ?, ?, ?, ?)");
    foreach ($parsed['entries'] as $entry) {
        if (!empty($entry['worker_id']) && !empty($entry['site_id'])) {
            try {
                $stmt->execute([
                    $entry['worker_type'] ?? 'employee',
                    $entry['worker_id'],
                    $entry['site_id'],
                    $entry['work_date'] ?? date('Y-m-d'),
                    $entry['work_type'] ?? ''
                ]);
                $registered_count++;
            } catch (Exception $e) {
                $register_errors[] = $entry['worker_name'] . '：' . $e->getMessage();
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'registered' => true,
        'registered_count' => $registered_count,
        'entries' => $parsed['entries'],
        'unmatched_workers' => $parsed['unmatched_workers'] ?? [],
        'summary' => $parsed['summary'] ?? '',
        'message' => '成功登記 ' . $registered_count . ' 名工人開工'
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'entries' => $parsed['entries'],
    'unmatched_workers' => $parsed['unmatched_workers'] ?? [],
    'summary' => $parsed['summary'] ?? ''
]);
exit;
