<?php
require_once __DIR__ . '/../config/config.php';
requireLogin();

$success = '';
$error = '';

// 處理判工登記
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sub_ids = $_POST['subcontractor_ids'] ?? [];
    $site_id = $_POST['site_id'] ?? '';
    $work_date = $_POST['work_date'] ?? date('Y-m-d');
    $work_type = $_POST['work_type'] ?? '';

    if (!empty($sub_ids) && !empty($site_id)) {
        $stmt = $pdo->prepare("INSERT INTO work_entries (worker_type, worker_id, site_id, work_date, work_type) VALUES ('subcontractor', ?, ?, ?, ?)");
        foreach ($sub_ids as $sub_id) {
            $stmt->execute([$sub_id, $site_id, $work_date, $work_type]);
        }
        $success = '已成功登記 ' . count($sub_ids) . ' 名判工開工';
    } else {
        $error = '請選擇判工及地盤';
    }
}

// 獲取所有判工及地盤
$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();

include __DIR__ . '/../includes/header.php';
?>

<div class="mb-8">
    <h1 class="text-2xl font-bold text-slate-800">判工登記</h1>
    <p class="text-slate-500">登記外部判工/分判商今日或特定日期的工作情況</p>
</div>

<?php if ($success): ?>
    <div class="bg-indigo-50 text-indigo-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden max-w-4xl">
    <form action="sub_work_entry.php" method="POST" class="p-8 space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">選擇地盤 *</label>
                <select name="site_id" required class="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 outline-none">
                    <option value="">-- 請選擇地盤 --</option>
                    <?php foreach ($sites as $site): ?>
                    <option value="<?php echo $site['id']; ?>">
                        <?php echo htmlspecialchars($site['location'] . ($site['unit'] ? ' - ' . $site['unit'] : '')); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">工作日期</label>
                <input type="date" name="work_date" value="<?php echo date('Y-m-d'); ?>" 
                    class="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 outline-none">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-slate-700 mb-2">工種 / 工作內容</label>
                <input type="text" name="work_type" placeholder="如：水電、木工、冷氣"
                    class="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 outline-none">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-slate-700 mb-2">選擇判工 (可多選) *</label>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-slate-50 rounded-xl border border-slate-100 max-h-60 overflow-y-auto">
                    <?php foreach ($subcontractors as $sub): ?>
                    <label class="flex items-center space-x-2 cursor-pointer p-2 hover:bg-white rounded-lg transition">
                        <input type="checkbox" name="subcontractor_ids[]" value="<?php echo $sub['id']; ?>" class="w-4 h-4 text-indigo-600 rounded">
                        <span class="text-sm text-slate-700"><?php echo htmlspecialchars($sub['name']); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="pt-6 border-t border-slate-100 flex justify-end">
            <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-10 py-3 rounded-xl shadow-lg hover:shadow-xl transition transform hover:-translate-y-0.5 font-bold">
                確認登記開工
            </button>
        </div>
    </form>
</div>

<!-- AI 智能開工登記 -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 mt-6 max-w-4xl overflow-hidden">
    <button type="button" onclick="toggleAIPanel()" class="w-full px-8 py-4 flex justify-between items-center hover:bg-slate-50 transition">
        <h3 class="text-base font-bold text-slate-800"><i class="fas fa-robot text-indigo-500 mr-2"></i>AI 智能判工登記</h3>
        <i class="fas fa-chevron-down text-slate-400 text-xs transition-transform" id="ai-icon"></i>
    </button>
    <div id="ai-panel" class="hidden border-t border-slate-100 px-8 pb-8 pt-4">
        <p class="text-xs text-slate-500 mb-3">用語音或文字輸入判工開工資訊，AI 會自動辨識，支援同時登記多人</p>
        <textarea id="ai-input" rows="3" placeholder="例如：今日天晉3座18樓B室，水電判工陳師傅同李師傅一齊開工" class="w-full px-4 py-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-indigo-500 text-sm resize-none"></textarea>
        <div class="flex gap-2 mt-3">
            <button type="button" onclick="startRecording()" id="record-btn" class="px-4 py-2.5 border border-slate-200 rounded-lg text-slate-500 hover:text-red-500 hover:border-red-200 transition text-sm flex items-center gap-1.5">
                <i class="fas fa-microphone"></i> 錄音
            </button>
            <button type="button" onclick="submitWorkAI(false)" id="ai-btn" class="bg-indigo-600 text-white py-2.5 rounded-lg font-bold hover:bg-indigo-700 transition text-sm flex items-center justify-center gap-2 px-5">
                <i class="fas fa-wand-magic-sparkles"></i> AI 分析
            </button>
            <button type="button" onclick="submitWorkAI(true)" id="ai-reg-btn" class="flex-1 bg-green-600 text-white py-2.5 rounded-lg font-bold hover:bg-green-700 transition text-sm flex items-center justify-center gap-2">
                <i class="fas fa-check-double"></i> AI 自動登記開工
            </button>
        </div>
        <div id="ai-status" class="mt-3 hidden"></div>
        <div id="ai-result" class="mt-3 hidden"></div>
    </div>
</div>

<script>
let isRecording = false;
let recognition = null;

function toggleAIPanel() {
    const panel = document.getElementById('ai-panel');
    const icon = document.getElementById('ai-icon');
    panel.classList.toggle('hidden');
    icon.style.transform = panel.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
}

function startRecording() {
    const btn = document.getElementById('record-btn');
    if (isRecording) {
        if (recognition) recognition.stop();
        isRecording = false;
        btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
        btn.classList.remove('text-red-500', 'border-red-200');
        btn.classList.add('text-slate-500');
        return;
    }
    if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
        alert('您的瀏覽器不支援語音辨識，請使用 Chrome 或 Edge，或直接輸入文字。');
        return;
    }
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    recognition = new SpeechRecognition();
    recognition.lang = 'zh-HK';
    recognition.continuous = true;
    recognition.interimResults = true;
    recognition.onstart = function() {
        isRecording = true;
        btn.innerHTML = '<i class="fas fa-stop"></i> 停止錄音';
        btn.classList.remove('text-slate-500');
        btn.classList.add('text-red-500', 'border-red-200');
    };
    recognition.onresult = function(event) {
        let transcript = '';
        for (let i = 0; i < event.results.length; i++) {
            transcript += event.results[i][0].transcript;
        }
        document.getElementById('ai-input').value = transcript;
    };
    recognition.onerror = function() { stopRec(btn); };
    recognition.onend = function() { stopRec(btn); };
    recognition.start();
}

function stopRec(btn) {
    isRecording = false;
    btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
    btn.classList.remove('text-red-500', 'border-red-200');
    btn.classList.add('text-slate-500');
}

function submitWorkAI(register) {
    const input = document.getElementById('ai-input').value.trim();
    if (!input) { alert('請先輸入開工內容'); return; }

    const btn = register ? document.getElementById('ai-reg-btn') : document.getElementById('ai-btn');
    const otherBtn = register ? document.getElementById('ai-btn') : document.getElementById('ai-reg-btn');
    const status = document.getElementById('ai-status');
    const result = document.getElementById('ai-result');
    
    btn.disabled = true;
    otherBtn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 處理中...';
    status.className = 'mt-3 p-3 bg-indigo-50 text-indigo-700 rounded-lg text-xs';
    status.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> AI 正在分析開工資料...';
    status.classList.remove('hidden');
    result.classList.add('hidden');

    const formData = new FormData();
    formData.append('input', input);
    if (register) formData.append('register', '1');

    fetch('work_entry_ai.php', { method: 'POST', body: formData })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        otherBtn.disabled = false;
        btn.innerHTML = register ? '<i class="fas fa-check-double"></i> AI 自動登記開工' : '<i class="fas fa-wand-magic-sparkles"></i> AI 分析';
        
        if (data.success && data.registered) {
            status.className = 'mt-3 p-3 bg-green-50 text-green-700 rounded-lg text-xs';
            status.innerHTML = '<i class="fas fa-check-circle mr-2"></i> ' + data.message;
            
            result.innerHTML = '<div class="bg-green-50 rounded-lg p-4 text-sm mt-3">' +
                '<div class="flex items-center gap-3">' +
                '<i class="fas fa-check-circle text-green-500 text-2xl"></i>' +
                '<div><p class="text-green-700 font-bold text-base">登記完成！</p>' +
                '<p class="text-green-600 text-xs mt-1">' + (data.summary || '') + '</p></div></div>' +
                '<button onclick="location.reload()" class="mt-3 w-full bg-green-600 text-white py-2 rounded-lg font-bold hover:bg-green-700 transition text-sm">' +
                '<i class="fas fa-sync-alt mr-1"></i> 刷新頁面查看</button></div>';
            result.classList.remove('hidden');
            return;
        }
        
        if (data.success) {
            let html = '<div class="bg-green-50 rounded-lg p-4 text-sm">';
            html += '<p class="text-green-700 font-bold mb-2"><i class="fas fa-check-circle mr-2"></i>' + (data.summary || '分析完成') + '</p>';
            
            if (data.unmatched_workers && data.unmatched_workers.length > 0) {
                html += '<p class="text-amber-600 mt-2"><i class="fas fa-exclamation-triangle mr-2"></i>找不到以下判工，請先到判工管理新增：<br>';
                data.unmatched_workers.forEach(function(name) { html += '&nbsp;&nbsp;• ' + name + '<br>'; });
                html += '</p>';
            }

            if (data.entries && data.entries.length > 0) {
                const allMatched = data.entries.every(function(e) { return e.worker_id !== null; });
                
                html += '<div class="mt-3 space-y-2">';
                data.entries.forEach(function(entry) {
                    html += '<div class="bg-white border border-slate-200 rounded-lg p-3 flex justify-between items-center">';
                    html += '<div><span class="font-medium text-slate-800">' + entry.worker_name + '</span>';
                    if (entry.worker_id) {
                        html += '<span class="text-indigo-600 text-xs ml-2">✓ 已匹配</span>';
                    } else {
                        html += '<span class="text-red-400 text-xs ml-2">✗ 未匹配</span>';
                    }
                    html += '<p class="text-xs text-slate-500 mt-0.5">' + (entry.site_name || '') + ' | ' + (entry.work_type || '') + ' | ' + entry.work_date + '</p></div>';
                    if (entry.worker_id) {
                        html += '<button onclick="autoFill(' + entry.worker_id + ',\'' + entry.worker_type + '\',' + entry.site_id + ',\'' + entry.work_date + '\',\'' + entry.work_type + '\')" class="text-indigo-600 hover:text-indigo-800 text-xs font-bold px-3 py-1.5 border border-indigo-200 rounded-lg hover:bg-indigo-50">填入表單</button>';
                    }
                    html += '</div>';
                });
                html += '</div>';
                
                if (allMatched && data.unmatched_workers.length === 0) {
                    html += '<button onclick="registerAllFromResult()" class="mt-3 w-full bg-green-600 text-white py-2.5 rounded-lg font-bold hover:bg-green-700 transition text-sm flex items-center justify-center gap-2">' +
                        '<i class="fas fa-check-double"></i> 一鍵登記全部</button>';
                }
            }
            html += '</div>';
            result.innerHTML = html;
            result.classList.remove('hidden');
            status.classList.add('hidden');
        } else {
            status.className = 'mt-3 p-3 bg-red-50 text-red-600 rounded-lg text-xs';
            status.innerHTML = '<i class="fas fa-exclamation-circle mr-2"></i> ' + (data.error || '分析失敗');
            if (data.entries) {
                let html = '<div class="bg-amber-50 rounded-lg p-4 text-sm mt-3">';
                html += '<p class="text-amber-700 font-bold mb-2"><i class="fas fa-exclamation-triangle mr-2"></i>部分匹配結果：</p>';
                data.entries.forEach(function(entry) {
                    html += '<div class="text-xs text-slate-600 py-1">• ' + entry.worker_name + ' → ' + (entry.worker_id ? '✓ 已匹配' : '✗ 未匹配') + '</div>';
                });
                html += '</div>';
                result.innerHTML = html;
                result.classList.remove('hidden');
            }
        }
    })
    .catch(error => {
        btn.disabled = false;
        otherBtn.disabled = false;
        btn.innerHTML = register ? '<i class="fas fa-check-double"></i> AI 自動登記開工' : '<i class="fas fa-wand-magic-sparkles"></i> AI 分析';
        status.className = 'mt-3 p-3 bg-red-50 text-red-600 rounded-lg text-xs';
        status.innerHTML = '<i class="fas fa-exclamation-circle mr-2"></i> 請求失敗：' + error.message;
    });
}

function autoFill(workerId, workerType, siteId, date, workType) {
    const form = document.querySelector('form');
    const checkboxes = form.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(function(cb) {
        if (parseInt(cb.value) === workerId) cb.checked = true;
    });
    const siteSelect = form.querySelector('select[name="site_id"]');
    if (siteSelect) siteSelect.value = siteId;
    const dateInput = form.querySelector('input[type="date"]');
    if (dateInput) dateInput.value = date;
    const workTypeInput = form.querySelector('input[name="work_type"]');
    if (workTypeInput && workType) workTypeInput.value = workType;
    form.scrollIntoView({ behavior: 'smooth' });
}

function registerAllFromResult() {
    submitWorkAI(true);
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
