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

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

// 處理帳單報銷
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $site_id = $_POST['site_id'] ?? '';
    $bill_date = $_POST['bill_date'] ?? date('Y-m-d');
    $amount = $_POST['amount'] ?? 0;
    $description = $_POST['description'] ?? '';
    $image_path = '';

    if (!empty($site_id) && !empty($amount)) {
        // 處理圖片上傳
        if (isset($_FILES['bill_image']) && $_FILES['bill_image']['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES['bill_image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('bill_') . '.' . $ext;
            if (move_uploaded_file($_FILES['bill_image']['tmp_name'], UPLOAD_DIR . 'bills/' . $filename)) {
                $image_path = 'uploads/bills/' . $filename;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO bills (site_id, bill_date, amount, image_path, description) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$site_id, $bill_date, $amount, $image_path, $description]);
        $success = '帳單報銷已成功提交';
    } else {
        $error = '請填寫地盤及金額';
    }
}

// 處理刪除
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("SELECT image_path FROM bills WHERE id = ?");
    $stmt->execute([$id]);
    $bill = $stmt->fetch();
    if ($bill && $bill['image_path']) {
        @unlink(__DIR__ . '/../' . $bill['image_path']);
    }
    $pdo->prepare("DELETE FROM bills WHERE id = ?")->execute([$id]);
    $success = '帳單紀錄已刪除';
}

// 獲取所有地盤供選擇
$sites = $pdo->query("SELECT id, location, unit FROM sites ORDER BY location ASC")->fetchAll();

// 獲取最近的報銷紀錄
$bills = $pdo->query("
    SELECT b.*, s.location, s.unit 
    FROM bills b 
    JOIN sites s ON b.site_id = s.id 
    ORDER BY b.bill_date DESC, b.created_at DESC
")->fetchAll();

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

<div class="flex justify-between items-center mb-8">
    <div>
        <h1 class="text-2xl font-bold text-slate-800">帳單報銷</h1>
        <p class="text-slate-500">上傳單據、登記各項雜費及材料支出</p>
    </div>
    <button onclick="document.getElementById('add-modal').classList.remove('hidden')" 
        class="bg-orange-600 hover:bg-orange-700 text-white px-4 py-2 rounded-lg flex items-center shadow-sm transition">
        <i class="fas fa-plus mr-2"></i> 新增報銷
    </button>
</div>

<?php if ($success): ?>
    <div class="bg-green-50 text-green-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; ?>

<!-- Bills List -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-100 text-slate-500 text-sm font-semibold">
                <tr>
                    <th class="px-6 py-4">日期</th>
                    <th class="px-6 py-4">地盤</th>
                    <th class="px-6 py-4">項目說明</th>
                    <th class="px-6 py-4">金額</th>
                    <th class="px-6 py-4">單據</th>
                    <th class="px-6 py-4 text-right">操作</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php foreach ($bills as $bill): ?>
                <tr class="hover:bg-slate-50 transition">
                    <td class="px-6 py-4 text-slate-700"><?php echo htmlspecialchars($bill['bill_date']); ?></td>
                    <td class="px-6 py-4">
                        <span class="font-medium text-slate-800"><?php echo htmlspecialchars($bill['location']); ?></span>
                        <span class="text-slate-400 text-xs block"><?php echo htmlspecialchars($bill['unit']); ?></span>
                    </td>
                    <td class="px-6 py-4 text-slate-600"><?php echo htmlspecialchars($bill['description'] ?: '-'); ?></td>
                    <td class="px-6 py-4 text-orange-600 font-bold">$<?php echo format_amount($bill['amount']); ?></td>
                    <td class="px-6 py-4">
                        <?php if ($bill['image_path']): ?>
                            <button onclick="previewImage('../<?php echo $bill['image_path']; ?>')" class="text-blue-500 hover:text-blue-700">
                                <i class="fas fa-image text-xl"></i>
                            </button>
                        <?php else: ?>
                            <span class="text-slate-300 text-xs italic">無圖片</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <a href="?delete=<?php echo $bill['id']; ?>" onclick="return confirm('確定要刪除此紀錄嗎？')" class="text-slate-400 hover:text-red-600">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($bills)): ?>
                <tr>
                    <td colspan="6" class="px-6 py-10 text-center text-slate-400">暫無報銷紀錄</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Modal -->
<div id="add-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl transform transition-all overflow-y-auto max-h-[90vh]">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-slate-800">新增報銷</h2>
            <button onclick="document.getElementById('add-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form action="bills.php" method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="action" value="add">
            
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">選擇地盤 *</label>
                <select name="site_id" required class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-orange-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-1">日期</label>
                <input type="date" name="bill_date" value="<?php echo date('Y-m-d'); ?>" 
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-orange-500 outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">金額 *</label>
                <div class="relative">
                    <span class="absolute left-3 top-2 text-slate-400">$</span>
                    <input type="number" step="0.01" name="amount" required placeholder="0.00"
                        class="w-full pl-8 pr-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-orange-500 outline-none">
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">項目說明</label>
                <textarea name="description" rows="2" placeholder="如：購買五金零件、交通費等"
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-orange-500 outline-none"></textarea>
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">上傳單據圖片</label>
                <input type="file" name="bill_image" accept="image/*"
                    class="w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-orange-50 file:text-orange-700 hover:file:bg-orange-100">
            </div>

            <div class="pt-4 flex gap-3">
                <button type="button" onclick="document.getElementById('add-modal').classList.add('hidden')" 
                    class="flex-1 px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 transition">
                    取消
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 shadow-lg transition">
                    確認提交
                </button>
            </div>
        </form>

        <!-- AI 智能辨識 -->
        <div class="mt-6 pt-6 border-t border-slate-100">
            <h3 class="text-sm font-bold text-slate-800 mb-3"><i class="fas fa-robot text-orange-500 mr-2"></i>AI 智能辨識單據</h3>
            <p class="text-xs text-slate-500 mb-3">輸入單據描述或用語音講出，AI 會自動填寫表單</p>
            <textarea id="ai-input" rows="2" placeholder="例如：今日天晉買咗五金零件$350，或直接上傳單據照片"
                class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-orange-500 text-sm resize-none"></textarea>
            <div class="flex gap-2 mt-3">
                <button type="button" onclick="startRecording()" id="record-btn" class="px-3 py-2 border border-slate-200 rounded-lg text-slate-500 hover:text-red-500 text-xs flex items-center gap-1">
                    <i class="fas fa-microphone"></i> 錄音
                </button>
                <button type="button" onclick="submitBillAI()" class="flex-1 bg-orange-500 text-white py-2 rounded-lg font-bold hover:bg-orange-600 transition text-xs flex items-center justify-center gap-2">
                    <i class="fas fa-wand-magic-sparkles"></i> AI 自動填寫
                </button>
            </div>
            <div id="ai-status" class="mt-3 hidden"></div>
        </div>
    </div>
</div>

<!-- Image Preview Modal -->
<div id="preview-modal" class="hidden fixed inset-0 bg-black bg-opacity-90 z-[60] flex items-center justify-center p-4" onclick="this.classList.add('hidden')">
    <img id="preview-img" src="" class="max-w-full max-h-full shadow-2xl">
</div>

<script>
    function previewImage(src) {
        document.getElementById('preview-img').src = src;
        document.getElementById('preview-modal').classList.remove('hidden');
    }

    function startRecording() {
        const btn = document.getElementById('record-btn');
        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            alert('您的瀏覽器不支援語音辨識，請使用 Chrome 或 Edge。');
            return;
        }
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const recognition = new SpeechRecognition();
        recognition.lang = 'zh-HK';
        recognition.continuous = true;
        recognition.interimResults = true;
        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.onend = function() {
            btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
            btn.classList.remove('text-red-500');
        };
        btn.innerHTML = '<i class="fas fa-stop"></i> 停止';
        btn.classList.add('text-red-500');
        recognition.start();
        setTimeout(() => { recognition.stop(); }, 15000);
    }

    function submitBillAI() {
        const input = document.getElementById('ai-input').value.trim();
        if (!input) { alert('請先輸入單據描述'); return; }
        const status = document.getElementById('ai-status');
        status.className = 'mt-3 p-3 bg-orange-50 text-orange-700 rounded-lg text-xs';
        status.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> AI 正在辨識...';
        status.classList.remove('hidden');
        
        const formData = new FormData();
        formData.append('input', input);
        
        fetch('bill_ai.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                if (data.site_id) document.querySelector('select[name="site_id"]').value = data.site_id;
                if (data.amount) document.querySelector('input[name="amount"]').value = data.amount;
                if (data.description) document.querySelector('textarea[name="description"]').value = data.description;
                if (data.bill_date) document.querySelector('input[name="bill_date"]').value = data.bill_date;
                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> 已自動填寫表單，請確認後提交';
            } 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 || '辨識失敗');
            }
        })
        .catch(error => {
            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;
        });
    }
</script>

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