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

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

// 處理刪除報價單
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("DELETE FROM quotations WHERE id = ?");
        $stmt->execute([$id]);
        $success = '報價單已成功刪除';
    } else {
        $error = '無效的報價單ID';
    }
}

// 處理新增報價單 (基本資料)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $company_id = $_POST['company_id'] ?? '';
    $address = $_POST['address'] ?? '';
    $quote_no = 'Q-' . date('Ymd') . '-' . rand(100, 999);
    $contact = $_POST['contact_person'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $project = $_POST['project_name'] ?? '';
    $date = $_POST['quote_date'] ?? date('Y-m-d');

    if (!empty($company_id) && !empty($address)) {
        $stmt = $pdo->prepare("INSERT INTO quotations (company_id, client_address, quote_no, contact_person, phone, project_name, quote_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$company_id, $address, $quote_no, $contact, $phone, $project, $date]);
        $new_id = $pdo->lastInsertId();
        redirect('/quotation_edit.php?id=' . $new_id);
    } else {
        $error = '請填寫公司及客戶地址';
    }
}

// 處理複製報價單
if (isset($_GET['copy'])) {
    $source_id = (int)$_GET['copy'];
    
    // 獲取原始報價單
    $stmt = $pdo->prepare("SELECT * FROM quotations WHERE id = ?");
    $stmt->execute([$source_id]);
    $source = $stmt->fetch();
    
    if ($source) {
        // 生成新的報價編號
        $new_quote_no = 'Q-' . date('Ymd') . '-' . rand(100, 999);
        
        // 複製報價單主表
        $stmt = $pdo->prepare("INSERT INTO quotations (company_id, client_address, quote_no, contact_person, phone, project_name, quote_date, total_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $source['company_id'],
            $source['client_address'],
            $new_quote_no,
            $source['contact_person'],
            $source['phone'],
            $source['project_name'] . ' (副本)',
            date('Y-m-d'),
            $source['total_amount']
        ]);
        $new_id = $pdo->lastInsertId();
        
        // 複製所有報價項目
        $stmt = $pdo->prepare("SELECT * FROM quotation_items WHERE quotation_id = ?");
        $stmt->execute([$source_id]);
        $items = $stmt->fetchAll();
        
        foreach ($items as $item) {
            $stmt = $pdo->prepare("INSERT INTO quotation_items (quotation_id, category_name, description, quantity, unit_type, price, subtotal, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$new_id, $item['category_name'], $item['description'], $item['quantity'], $item['unit_type'], $item['price'], $item['subtotal'], $item['sort_order']]);
        }
        
        redirect('/quotation_edit.php?id=' . $new_id);
    } else {
        $error = '找不到原始報價單';
    }
}

// 獲取所有報價單
$quotations = $pdo->query("
    SELECT q.*, c.name as company_name 
    FROM quotations q 
    JOIN quote_companies c ON q.company_id = c.id 
    ORDER BY q.created_at DESC
")->fetchAll();

$companies = $pdo->query("SELECT id, name FROM quote_companies ORDER BY name ASC")->fetchAll();

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

<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
    <div>
        <h1 class="m3-headline">報價系統</h1>
        <p class="m3-body-sm text-[#64748B] mt-0.5">製作及管理客戶工程報價單</p>
    </div>
    <div class="flex flex-wrap gap-2 w-full sm:w-auto">
        <button onclick="document.getElementById('compare-modal').classList.remove('hidden')" 
            class="m3-btn m3-btn-success m3-btn-sm flex-1 sm:flex-none">
            <i class="fas fa-not-equal"></i> AI 對比
        </button>
        <button onclick="document.getElementById('add-modal').classList.remove('hidden')" 
            class="m3-btn m3-btn-filled flex-1 sm:flex-none">
            <i class="fas fa-plus"></i> 新增報價單
        </button>
    </div>
</div>

<?php if ($error): ?>
    <div class="m3-banner m3-banner-error mb-6 flex items-center gap-2.5">
        <i class="fas fa-exclamation-circle text-lg"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="m3-banner m3-banner-success mb-6 flex items-center gap-2.5">
        <i class="fas fa-check-circle text-lg"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<!-- Quotation List -->
<div class="m3-card overflow-hidden">
    <div class="table-responsive">
        <table class="m3-table">
            <thead>
                <tr>
                    <th class="whitespace-nowrap">報價編號</th>
                    <th class="whitespace-nowrap">公司</th>
                    <th class="whitespace-nowrap">客戶 / 項目</th>
                    <th class="whitespace-nowrap">總額</th>
                    <th class="whitespace-nowrap">日期</th>
                    <th class="text-right whitespace-nowrap">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($quotations as $quote): ?>
                <tr>
                    <td class="font-mono text-xs font-bold text-[#94A3B8] whitespace-nowrap"><?php echo htmlspecialchars($quote['quote_no']); ?></td>
                    <td class="font-medium text-[#0F172A] whitespace-nowrap"><?php echo htmlspecialchars($quote['company_name']); ?></td>
                    <td>
                        <p class="font-semibold text-[#0F172A]"><?php echo htmlspecialchars($quote['project_name'] ?: '未命名項目'); ?></p>
                        <p class="text-xs text-[#64748B] truncate-mobile mt-0.5"><?php echo htmlspecialchars($quote['client_address']); ?></p>
                    </td>
                    <td class="font-bold text-[#4F46E5] whitespace-nowrap">$<?php echo format_amount($quote['total_amount']); ?></td>
                    <td class="text-sm text-[#64748B] whitespace-nowrap"><?php echo htmlspecialchars($quote['quote_date']); ?></td>
                    <td class="text-right">
                        <div class="action-group">
                        <a href="quotation_edit.php?id=<?php echo $quote['id']; ?>" title="編輯">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="?copy=<?php echo $quote['id']; ?>" title="複製" onclick="return confirm('複製此報價單作為副本？')">
                            <i class="fas fa-copy"></i>
                        </a>
                        <button type="button" onclick="downloadPDF('quotation_print', <?php echo $quote['id']; ?>)" title="下載 PDF">
                            <i class="fas fa-file-pdf"></i>
                        </button>
                        <a href="quotation_print.php?id=<?php echo $quote['id']; ?>" target="_blank" title="列印">
                            <i class="fas fa-print"></i>
                        </a>
                        <button type="button" onclick="shareQuote(<?php echo $quote['id']; ?>)" title="分享">
                            <i class="fas fa-share-alt"></i>
                        </button>
                        <button type="button" onclick="confirmDelete(<?php echo $quote['id']; ?>, '<?php echo htmlspecialchars($quote['quote_no']); ?>')" title="刪除">
                            <i class="fas fa-trash"></i>
                        </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($quotations)): ?>
                <tr>
                    <td colspan="6" class="text-center py-12 text-[#94A3B8] text-sm">暫無報價單</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Modal -->
<div id="add-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)document.getElementById('add-modal').classList.add('hidden')">
    <div class="m3-dialog w-full max-w-lg p-8 overflow-y-auto max-h-[90vh]">
        <h2 class="m3-title mb-6">新增報價單</h2>
        <form action="quotations.php" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="add">
            <div>
                <label class="m3-label">選擇公司 *</label>
                <select name="company_id" required class="m3-select">
                    <option value="">-- 請選擇公司 --</option>
                    <?php foreach ($companies as $comp): ?>
                    <option value="<?php echo $comp['id']; ?>"><?php echo htmlspecialchars($comp['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="m3-label">項目名稱</label>
                <input type="text" name="project_name" placeholder="如：將軍澳天晉全屋裝修" class="m3-input">
            </div>
            <div>
                <label class="m3-label">客戶地址 *</label>
                <input type="text" name="address" required class="m3-input">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="m3-label">聯絡人</label>
                    <input type="text" name="contact_person" class="m3-input">
                </div>
                <div>
                    <label class="m3-label">聯絡電話</label>
                    <input type="text" name="phone" class="m3-input">
                </div>
            </div>
            <div>
                <label class="m3-label">報價日期</label>
                <input type="date" name="quote_date" value="<?php echo date('Y-m-d'); ?>" class="m3-input">
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="document.getElementById('add-modal').classList.add('hidden')" class="flex-1 m3-btn m3-btn-tonal">取消</button>
                <button type="submit" class="flex-1 m3-btn m3-btn-filled">開始編寫項目</button>
            </div>
        </form>
    </div>
</div>

<!-- Compare Modal -->
<div id="compare-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)document.getElementById('compare-modal').classList.add('hidden')">
    <div class="m3-dialog w-full max-w-2xl p-8 overflow-y-auto max-h-[90vh]">
        <div class="flex justify-between items-center mb-6">
            <h2 class="m3-title flex items-center gap-2">
                <i class="fas fa-robot text-[#10B981]"></i>AI 報價單對比
            </h2>
            <button onclick="document.getElementById('compare-modal').classList.add('hidden')" class="text-[#94A3B8] hover:text-[#0F172A] p-1 rounded-xl hover:bg-[#F1F5F9] transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
                <label class="m3-label">選擇第一份報價單 *</label>
                <select id="compare-q1" class="m3-select">
                    <option value="">-- 請選擇 --</option>
                    <?php foreach ($quotations as $q): ?>
                    <option value="<?php echo $q['id']; ?>"><?php echo htmlspecialchars($q['project_name'] ?: $q['quote_no']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="m3-label">選擇第二份報價單 *</label>
                <select id="compare-q2" class="m3-select">
                    <option value="">-- 請選擇 --</option>
                    <?php foreach ($quotations as $q): ?>
                    <option value="<?php echo $q['id']; ?>"><?php echo htmlspecialchars($q['project_name'] ?: $q['quote_no']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <button onclick="runCompare()" id="compare-btn" class="m3-btn m3-btn-success w-full">
            <i class="fas fa-wand-magic-sparkles"></i> AI 對比分析
        </button>
        <div id="compare-result" class="mt-6 hidden"></div>
    </div>
</div>

<script>
function confirmDelete(id, quoteNo) {
    if (confirm('確定要刪除報價單 ' + quoteNo + ' 嗎？\n\n此操作無法撤銷，請確認。')) {
        document.getElementById('delete-form').querySelector('input[name="id"]').value = id;
        document.getElementById('delete-form').submit();
    }
}

function runCompare() {
    const q1 = document.getElementById('compare-q1').value;
    const q2 = document.getElementById('compare-q2').value;
    if (!q1 || !q2) { alert('請選擇兩份報價單'); return; }
    if (q1 === q2) { alert('請選擇兩份不同的報價單'); return; }

    const btn = document.getElementById('compare-btn');
    const result = document.getElementById('compare-result');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> AI 分析中...';
    result.className = 'mt-6';
    result.innerHTML = '<div class="text-center py-10 text-emerald-500"><i class="fas fa-spinner fa-spin text-3xl mb-3 block"></i><p>AI 正在分析比對兩份報價單...</p></div>';
    result.classList.remove('hidden');

    const formData = new FormData();
    formData.append('quote1_id', q1);
    formData.append('quote2_id', q2);

    fetch('compare_ai.php', { method: 'POST', body: formData })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-wand-magic-sparkles"></i> AI 對比分析';
        
        if (data.success) {
            let html = '<div class="space-y-4">';
            
            // 總額對比
            html += '<div class="grid grid-cols-2 gap-4">';
            html += '<div class="bg-slate-50 rounded-xl p-4 text-center border border-slate-200"><p class="text-xs text-slate-500">' + data.quote1_name + '</p><p class="text-2xl font-bold text-slate-800">$' + data.quote1_total.toLocaleString() + '</p></div>';
            html += '<div class="bg-slate-50 rounded-xl p-4 text-center border border-slate-200"><p class="text-xs text-slate-500">' + data.quote2_name + '</p><p class="text-2xl font-bold text-slate-800">$' + data.quote2_total.toLocaleString() + '</p></div>';
            html += '</div>';
            
            html += '<div class="bg-gradient-to-r from-emerald-50 to-blue-50 rounded-xl p-4 border border-emerald-100">';
            html += '<p class="text-sm text-slate-700">' + data.summary + '</p></div>';
            
            if (data.same_items && data.same_items.length > 0) {
                html += '<div><h4 class="text-sm font-bold text-slate-800 mb-2"><i class="fas fa-check-circle text-green-500 mr-1"></i>相同/類似項目</h4>';
                html += '<ul class="space-y-1">';
                data.same_items.forEach(function(item) { html += '<li class="text-xs text-slate-600 bg-green-50 px-3 py-2 rounded-lg">• ' + item + '</li>'; });
                html += '</ul></div>';
            }
            
            if (data.diff_items && data.diff_items.length > 0) {
                html += '<div><h4 class="text-sm font-bold text-slate-800 mb-2"><i class="fas fa-exchange-alt text-amber-500 mr-1"></i>價格差異項目</h4>';
                html += '<ul class="space-y-1">';
                data.diff_items.forEach(function(item) { html += '<li class="text-xs text-slate-600 bg-amber-50 px-3 py-2 rounded-lg">• ' + item + '</li>'; });
                html += '</ul></div>';
            }
            
            if (data.unique_to_quote1 && data.unique_to_quote1.length > 0) {
                html += '<div><h4 class="text-sm font-bold text-slate-800 mb-2"><i class="fas fa-file text-blue-500 mr-1"></i>僅 A 有</h4>';
                html += '<ul class="space-y-1">';
                data.unique_to_quote1.forEach(function(item) { html += '<li class="text-xs text-slate-600 bg-blue-50 px-3 py-2 rounded-lg">• ' + item + '</li>'; });
                html += '</ul></div>';
            }
            
            if (data.unique_to_quote2 && data.unique_to_quote2.length > 0) {
                html += '<div><h4 class="text-sm font-bold text-slate-800 mb-2"><i class="fas fa-file text-purple-500 mr-1"></i>僅 B 有</h4>';
                html += '<ul class="space-y-1">';
                data.unique_to_quote2.forEach(function(item) { html += '<li class="text-xs text-slate-600 bg-purple-50 px-3 py-2 rounded-lg">• ' + item + '</li>'; });
                html += '</ul></div>';
            }
            
            html += '<div class="bg-slate-50 rounded-xl p-4 border border-slate-200">';
            html += '<h4 class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">價格對比</h4>';
            html += '<p class="text-sm text-slate-700">' + data.price_comparison + '</p></div>';
            
            if (data.recommendation) {
                html += '<div class="bg-amber-50 border border-amber-200 rounded-xl p-4 flex items-start gap-3">';
                html += '<i class="fas fa-lightbulb text-amber-500 mt-0.5"></i>';
                html += '<p class="text-sm text-amber-800">' + data.recommendation + '</p></div>';
            }
            
            html += '</div>';
            result.innerHTML = html;
        } else {
            result.innerHTML = '<div class="text-center py-10 text-red-500"><i class="fas fa-exclamation-circle text-3xl mb-3 block"></i><p>' + (data.error || '分析失敗') + '</p></div>';
        }
    })
    .catch(error => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-wand-magic-sparkles"></i> AI 對比分析';
        result.innerHTML = '<div class="text-center py-10 text-red-500"><i class="fas fa-exclamation-circle text-3xl mb-3 block"></i><p>請求失敗：' + error.message + '</p></div>';
    });
}
</script>

<form id="delete-form" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" value="">
</form>

<script>
function shareQuote(id) {
    const base = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const fullUrl = base + 'quotation_print.php?id=' + id;
    const shareData = {
        title: '裝修報價單',
        text: '查看工程報價單',
        url: fullUrl
    };
    if (navigator.share) {
        navigator.share(shareData).catch(function(e) {
            if (e.name !== 'AbortError') fallbackCopy(fullUrl, '報價單');
        });
    } else {
        fallbackCopy(fullUrl, '報價單');
    }
}
function downloadPDF(page, id) {
    const base = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const win = window.open(base + page + '.php?id=' + id, '_blank');
}
function fallbackCopy(url, label) {
    navigator.clipboard.writeText(url).then(function() {
        alert(label + '連結已複製到剪貼簿');
    }).catch(function() {
        prompt('請複製以下連結以分享：', url);
    });
}
</script>

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