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

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

// 收集各項統計資料
$total_employees = $pdo->query("SELECT COUNT(*) FROM employees")->fetchColumn();
$total_subcontractors = $pdo->query("SELECT COUNT(*) FROM subcontractors")->fetchColumn();
$active_sites = $pdo->query("SELECT COUNT(*) FROM sites WHERE status = 'active'")->fetchColumn();
$total_sites = $pdo->query("SELECT COUNT(*) FROM sites")->fetchColumn();

// 本月開工統計
$month_start = date('Y-m-01');
$month_entries = $pdo->query("SELECT COUNT(*) FROM work_entries WHERE work_date >= '$month_start'")->fetchColumn();
$today_entries = $pdo->query("SELECT COUNT(*) FROM work_entries WHERE work_date = CURDATE()")->fetchColumn();

// 各工地開工次數
$site_work_counts = $pdo->query("
    SELECT s.location, s.unit, COUNT(we.id) as cnt 
    FROM work_entries we 
    JOIN sites s ON we.site_id = s.id 
    WHERE we.work_date >= '$month_start'
    GROUP BY we.site_id 
    ORDER BY cnt DESC 
    LIMIT 5
")->fetchAll();

// 報價單統計
$total_quotes = $pdo->query("SELECT COUNT(*) FROM quotations")->fetchColumn();
$total_quote_amount = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) FROM quotations")->fetchColumn();
$this_month_quotes = $pdo->query("SELECT COUNT(*) FROM quotations WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())")->fetchColumn();

// 帳單統計
$total_bills = $pdo->query("SELECT COUNT(*) FROM bills")->fetchColumn();
$total_bill_amount = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM bills")->fetchColumn();
$this_month_bills = $pdo->query("SELECT COUNT(*) FROM bills WHERE MONTH(bill_date) = MONTH(CURDATE()) AND YEAR(bill_date) = YEAR(CURDATE())")->fetchColumn();
$this_month_bill_amount = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM bills WHERE MONTH(bill_date) = MONTH(CURDATE()) AND YEAR(bill_date) = YEAR(CURDATE())")->fetchColumn();

// 發票/收據統計
$total_invoices = $pdo->query("SELECT COUNT(*) FROM invoices")->fetchColumn();
$total_receipts = $pdo->query("SELECT COUNT(*) FROM receipts")->fetchColumn();

// 近期開工紀錄
$recent_work = $pdo->query("
    SELECT we.work_date, we.work_type, s.location, 
           CASE WHEN we.worker_type = 'employee' THEN e.name ELSE sc.name END as worker_name,
           we.worker_type
    FROM work_entries we
    JOIN sites s ON we.site_id = s.id
    LEFT JOIN employees e ON we.worker_type = 'employee' AND we.worker_id = e.id
    LEFT JOIN subcontractors sc ON we.worker_type = 'subcontractor' AND we.worker_id = sc.id
    ORDER BY we.created_at DESC LIMIT 10
")->fetchAll();

$site_work_text = '';
foreach ($site_work_counts as $sw) {
    $site_work_text .= "- {$sw['location']} {$sw['unit']}: {$sw['cnt']} 次開工\n";
}

$recent_work_text = '';
foreach ($recent_work as $rw) {
    $recent_work_text .= "- {$rw['work_date']} | {$rw['location']} | {$rw['worker_name']} ({$rw['work_type']})\n";
}

$this_month_name = date('Y年n月');

$system_prompt = "你是一個香港裝修工程管理系統的AI工程總結助理。以下是系統的數據，請生成一份專業、清晰的工程總結報告，用繁體中文。

數據概覽：
- 員工總數：{$total_employees} 人
- 判工總數：{$total_subcontractors} 人
- 地盤總數：{$total_sites} 個（活躍：{$active_sites} 個）

本月 ({$this_month_name}) 工作統計：
- 本月開工登記次數：{$month_entries} 次
- 今日開工登記：{$today_entries} 次
- 本月各工地開工情況：
{$site_work_text}

財務統計：
- 報價單總數：{$total_quotes} 份（本月新增：{$this_month_quotes} 份）
- 報價單總額：$" . number_format($total_quote_amount, 0) . "
- 帳單報銷總數：{$total_bills} 筆
- 帳單總金額：$" . number_format($total_bill_amount, 0) . "
- 本月帳單金額：$" . number_format($this_month_bill_amount, 0) . "
- 發票總數：{$total_invoices} 張
- 收據總數：{$total_receipts} 張

近期開工紀錄：
{$recent_work_text}

請生成以下 JSON 格式回覆（只回覆 JSON，不用 Markdown）：
{
  \"title\": \"一個吸引的標題\",
  \"summary\": \"整體摘要（3-5句話）\",
  \"highlights\": [\"重點1\", \"重點2\", \"重點3\", \"重點4\"],
  \"work_analysis\": \"開工情況分析\",
  \"financial_insight\": \"財務狀況簡評\",
  \"suggestion\": \"一個可行的建議\"
}";

$messages = [
    ['role' => 'system', 'content' => $system_prompt],
    ['role' => 'user', 'content' => '請生成今天的工程總結報告']
];

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

$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,
    'title' => $parsed['title'] ?? '工程總結報告',
    'summary' => $parsed['summary'] ?? '',
    'highlights' => $parsed['highlights'] ?? [],
    'work_analysis' => $parsed['work_analysis'] ?? '',
    'financial_insight' => $parsed['financial_insight'] ?? '',
    'suggestion' => $parsed['suggestion'] ?? ''
]);
