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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) die("無效的報價單編號");

$stmt = $pdo->prepare("
    SELECT q.*, c.name as co_name, c.logo_path, c.stamp_path, c.address as co_addr, c.phone as co_phone, c.email as co_email 
    FROM quotations q 
    JOIN quote_companies c ON q.company_id = c.id 
    WHERE q.id = ?
");
$stmt->execute([$id]);
$quote = $stmt->fetch();
if (!$quote) die("找不到報價單");

$stmt = $pdo->prepare("SELECT * FROM quotation_items WHERE quotation_id = ? ORDER BY id ASC");
$stmt->execute([$id]);
$items = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>報價單 - <?php echo $quote['quote_no']; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Noto Sans TC', sans-serif; 
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
            color: #1e293b;
        }
        @media print {
            .no-print { display: none !important; }
            body { padding: 0 !important; background: white !important; }
            .print-shadow { box-shadow: none !important; border: none !important; }
            .page-break { page-break-after: always; }
            tr { page-break-inside: avoid; }
            .avoid-break { page-break-inside: avoid; }
        }
        @media (max-width: 640px) {
            .print-container {
                padding: 1rem !important;
                margin: 0 !important;
                max-width: 100% !important;
                border-radius: 0 !important;
                min-height: auto !important;
            }
            .print-grid-2 {
                grid-template-columns: 1fr !important;
                gap: 0.75rem !important;
            }
            .print-grid-5 {
                grid-template-columns: 1fr !important;
                gap: 0.75rem !important;
            }
            .print-grid-5 .col-span-3,
            .print-grid-5 .col-span-2 {
                grid-column: span 1 !important;
            }
            .print-header {
                flex-direction: column !important;
                gap: 1rem !important;
            }
            .print-header > div {
                width: 100% !important;
                text-align: left !important;
            }
            .print-header .text-right {
                text-align: left !important;
            }
            .print-total-wrap {
                max-width: 100% !important;
            }
            .no-print {
                flex-direction: column !important;
                gap: 0.5rem !important;
            }
            .no-print button {
                width: 100% !important;
                justify-content: center !important;
            }
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-30deg);
            font-size: 10rem;
            font-weight: 900;
            color: rgba(241, 245, 249, 0.2);
            pointer-events: none;
            z-index: 0;
            white-space: nowrap;
            letter-spacing: 0.5em;
        }
        .item-row:nth-child(even) {
            background-color: #f8fafc;
        }
        .item-row td {
            padding-top: 10px;
            padding-bottom: 10px;
        }
        .item-row td:first-child {
            padding-top: 10px;
            padding-bottom: 10px;
        }
        .description-cell {
            line-height: 1.5;
        }
        .description-cell .cat-badge {
            font-size: 8px;
            margin-bottom: 2px;
        }
    </style>
</head>
<body class="bg-slate-100 py-10" onload="window.print()">
    <div class="max-w-5xl mx-auto bg-white px-12 md:px-14 py-10 shadow-2xl print-shadow rounded-none relative overflow-hidden min-h-[1123px] flex flex-col print-container">
        <!-- Watermark -->
        <div class="watermark uppercase print:block hidden">Quotation</div>

        <div class="no-print flex justify-between mb-8">
            <button onclick="window.history.back()" class="bg-slate-600 text-white px-6 py-2 rounded-lg font-bold hover:bg-slate-700 transition flex items-center shadow-lg">
                <i class="fas fa-arrow-left mr-2"></i> 返回 / Back
            </button>
            <div class="flex gap-2">
            <button onclick="sharePrint()" class="bg-sky-600 text-white px-6 py-2 rounded-lg font-bold hover:bg-sky-700 transition flex items-center shadow-lg">
                <i class="fas fa-share-alt mr-2"></i> 分享
            </button>
            <button onclick="window.print()" class="bg-blue-700 text-white px-6 py-2 rounded-lg font-bold hover:bg-blue-800 transition flex items-center shadow-lg">
                <i class="fas fa-print mr-2"></i> 列印
            </button>
            </div>
        </div>

        <!-- Top Section: Company + Client + Project (Compact) -->
        <div class="relative z-10">
            <div class="flex justify-between items-start mb-6 print-header">
                <div>
                    <?php if ($quote['logo_path']): ?>
                        <img src="../<?php echo $quote['logo_path']; ?>" class="h-20 mb-4 object-contain">
                    <?php endif; ?>
                    <h1 class="text-2xl font-bold text-slate-900 mb-2 tracking-tight"><?php echo htmlspecialchars($quote['co_name']); ?></h1>
                    <div class="text-xs text-slate-500 space-y-1">
                        <p class="flex items-start"><i class="fas fa-map-marker-alt w-4 mr-1.5 mt-0.5 text-slate-400"></i><span><?php echo htmlspecialchars($quote['co_addr']); ?></span></p>
                        <div class="flex flex-wrap gap-x-5">
                            <p class="flex items-center"><i class="fas fa-phone w-4 mr-1.5 text-slate-400"></i><?php echo htmlspecialchars($quote['co_phone']); ?></p>
                            <p class="flex items-center"><i class="fas fa-envelope w-4 mr-1.5 text-slate-400"></i><?php echo htmlspecialchars($quote['co_email']); ?></p>
                        </div>
                    </div>
                </div>
                <div class="text-right">
                    <div class="bg-slate-900 text-white px-8 py-4 inline-block text-center mb-4">
                        <h2 class="text-2xl font-bold tracking-[0.3em]">報價單</h2>
                        <p class="text-[9px] font-light tracking-[0.2em] opacity-70 uppercase">Quotation</p>
                    </div>
                    <div class="space-y-1.5">
                        <p class="text-[9px] text-slate-400 uppercase font-bold tracking-widest">文件編號 / Document No.</p>
                        <p class="text-base font-mono font-bold text-slate-900"><?php echo htmlspecialchars($quote['quote_no']); ?></p>
                        <p class="text-[9px] text-slate-400 uppercase font-bold tracking-widest mt-2">簽發日期 / Date of Issue</p>
                        <p class="text-sm font-medium text-slate-900"><?php echo htmlspecialchars($quote['quote_date']); ?></p>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-2 gap-6 mb-6 print-grid-2">
                <div class="bg-slate-50 border border-slate-200 rounded-sm px-6 py-4">
                    <h3 class="text-[9px] font-bold text-slate-500 uppercase tracking-[0.15em] mb-2">
                        <span class="w-1.5 h-1.5 bg-slate-900 inline-block mr-1.5 align-middle"></span> 致客戶 / Bill To
                    </h3>
                    <p class="text-base font-bold text-slate-900"><?php echo htmlspecialchars($quote['contact_person'] ?: '客戶'); ?></p>
                    <p class="text-xs text-slate-600 leading-relaxed mt-0.5"><?php echo htmlspecialchars($quote['client_address']); ?></p>
                    <p class="text-xs text-slate-500 mt-2"><i class="fas fa-phone-alt mr-1.5 text-[10px]"></i> <?php echo htmlspecialchars($quote['phone'] ?: '-'); ?></p>
                </div>
                <div class="bg-slate-50 border border-slate-200 rounded-sm px-6 py-4">
                    <h3 class="text-[9px] font-bold text-slate-500 uppercase tracking-[0.15em] mb-2">
                        <span class="w-1.5 h-1.5 bg-blue-600 inline-block mr-1.5 align-middle"></span> 工程項目 / Project
                    </h3>
                    <p class="text-base font-bold text-slate-900"><?php echo htmlspecialchars($quote['project_name']); ?></p>
                    <div class="mt-2">
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-medium bg-blue-100 text-blue-800">
                            正式報價 / Official Quote
                        </span>
                    </div>
                </div>
            </div>

            <div class="border-t-2 border-slate-900 mb-6"></div>
        </div>

        <!-- Items Table -->
        <div class="relative z-10 flex-grow">
            <table class="w-full border-collapse">
                <thead>
                    <tr class="bg-slate-900 text-white text-[9px] uppercase tracking-[0.2em]">
                        <th class="px-3 py-3 text-center w-10 border-r border-slate-800">#</th>
                        <th class="px-5 py-3 text-left border-r border-slate-800">項目描述 / Description</th>
                        <th class="px-3 py-3 text-center w-20 border-r border-slate-800">數量 / Qty</th>
                        <th class="px-3 py-3 text-right w-28 border-r border-slate-800">單價 / Unit Price</th>
                        <th class="px-3 py-3 text-right w-28">金額 / Amount</th>
                    </tr>
                </thead>
                <tbody class="text-xs">
                    <?php foreach ($items as $index => $item): ?>
                    <tr class="item-row border-b border-slate-100">
                        <td class="px-3 text-center text-slate-400 font-mono"><?php echo str_pad($index + 1, 2, '0', STR_PAD_LEFT); ?></td>
                        <td class="px-5 description-cell">
                            <span class="cat-badge font-bold uppercase text-blue-600 block"><?php echo htmlspecialchars($item['category_name']); ?></span>
                            <p class="text-slate-800 whitespace-pre-wrap"><?php echo htmlspecialchars($item['description']); ?></p>
                        </td>
                        <td class="px-3 text-center text-slate-600 font-mono">
                            <?php echo format_amount($item['quantity']); ?>
                        </td>
                        <td class="px-3 text-right text-slate-600 font-mono">
                            <?php if ($item['quantity'] != 1): ?>
                                $<?php echo format_amount($item['price']); ?>
                                <?php if ($item['unit_type']): ?>
                                    <span class="text-[9px] text-slate-400 block"><?php echo htmlspecialchars($item['unit_type']); ?></span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <td class="px-3 text-right font-bold text-slate-900 font-mono">$<?php echo format_amount($item['subtotal']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Summary & Terms -->
        <div class="mt-8 relative z-10 avoid-break">
            <div class="flex justify-end mb-8">
                <div class="w-full max-w-sm print-total-wrap">
                    <div class="bg-slate-900 text-white px-8 py-5 flex justify-between items-center">
                        <div class="text-left">
                            <p class="text-[9px] font-bold uppercase tracking-[0.2em] opacity-60">總額 / Total Amount</p>
                            <p class="text-[11px] italic opacity-80">港幣 <?php echo format_amount($quote['total_amount']); ?> 元正</p>
                        </div>
                        <div class="text-right">
                            <p class="text-3xl font-black font-mono tracking-tight">$<?php echo format_amount($quote['total_amount']); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-5 gap-8 print-grid-5">
                <div class="col-span-3 bg-slate-50 border border-slate-200 px-6 py-5">
                    <h3 class="text-[9px] font-bold text-slate-900 uppercase tracking-[0.15em] mb-3 border-b border-slate-300 pb-2">條款及細則 / Terms</h3>
                    <ul class="text-[9px] text-slate-500 space-y-2 list-none">
                        <li class="flex items-start"><span class="w-1 h-1 bg-slate-400 mr-2.5 mt-1 flex-shrink-0"></span> 報價有效期為發出日起計 14 天。</li>
                        <li class="flex items-start"><span class="w-1 h-1 bg-slate-400 mr-2.5 mt-1 flex-shrink-0"></span> 確認報價後需支付總額之 40% 作為訂金。</li>
                        <li class="flex items-start"><span class="w-1 h-1 bg-slate-400 mr-2.5 mt-1 flex-shrink-0"></span> 所有工程項目均享有一年結構保養（人為損壞除外）。</li>
                        <li class="flex items-start"><span class="w-1 h-1 bg-slate-400 mr-2.5 mt-1 flex-shrink-0"></span> 最終價格將根據現場實際度尺及施工情況作調整。</li>
                    </ul>
                </div>
                <div class="col-span-2 flex flex-col justify-end items-center">
                    <div class="relative w-full max-w-[240px]">
                        <?php if ($quote['stamp_path']): ?>
                            <img src="../<?php echo $quote['stamp_path']; ?>" class="absolute left-1/2 -translate-x-1/2 w-40 h-40 object-contain opacity-80 pointer-events-none mix-blend-multiply" style="top: -120px">
                        <?php endif; ?>
                        <div class="w-full border-b border-slate-900 mb-3 relative z-10"></div>
                        <div class="text-center relative z-10">
                            <p class="text-[9px] font-bold text-slate-900 uppercase tracking-widest">公司簽署及蓋印</p>
                            <p class="text-[7px] text-slate-400 uppercase tracking-tight">Authorized Signature & Company Chop</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Page Footer -->
        <div class="mt-10 text-center border-t border-slate-100 pt-6 text-[8px] text-slate-400 uppercase tracking-[0.2em] relative z-10">
            <p>這是一份由 <?php echo APP_NAME; ?> 自動生成的正式電子文件</p>
            <p class="mt-1">Computer Generated Document | Confidential & Official</p>
        </div>
    </div>

<script>
function sharePrint() {
    const shareData = {
        title: '裝修報價單 - <?php echo htmlspecialchars($quote['quote_no']); ?>',
        text: '<?php echo htmlspecialchars($quote['project_name']); ?> - $<?php echo format_amount($quote['total_amount']); ?>',
        url: window.location.href
    };
    if (navigator.share) {
        navigator.share(shareData).catch(function(e) {
            if (e.name !== 'AbortError') fallbackCopy(window.location.href, '報價單');
        });
    } else {
        fallbackCopy(window.location.href, '報價單');
    }
}
function fallbackCopy(url, label) {
    navigator.clipboard.writeText(url).then(function() {
        alert(label + '連結已複製到剪貼簿');
    }).catch(function() {
        prompt('請複製以下連結以分享：', url);
    });
}
</script>
</body>
</html>
