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

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

$stmt = $pdo->prepare("
    SELECT r.*, q.quote_no, q.project_name, q.client_address, q.contact_person, q.phone, q.total_amount as quote_total,
           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 receipts r 
    JOIN quotations q ON r.quotation_id = q.id 
    JOIN quote_companies c ON q.company_id = c.id 
    WHERE r.id = ?
");
$stmt->execute([$id]);
$receipt = $stmt->fetch();
if (!$receipt) die("找不到收據");
?>
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>收據 - <?php echo $receipt['receipt_no']; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <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-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-grid-2 {
                grid-template-columns: 1fr !important;
                gap: 0.75rem !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.3);
            pointer-events: none;
            z-index: 0;
            white-space: nowrap;
            letter-spacing: 0.5em;
        }
    </style>
</head>
<body class="bg-slate-100 py-10" onload="window.print()">
    <div class="max-w-5xl mx-auto bg-white p-12 md:p-16 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">Receipt</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-emerald-700 text-white px-6 py-2 rounded-lg font-bold hover:bg-emerald-800 transition flex items-center shadow-lg">
                <i class="fas fa-print mr-2"></i> 列印
            </button>
            </div>
        </div>

        <!-- Header -->
        <div class="flex justify-between items-start mb-12 relative z-10 border-b-2 border-slate-900 pb-8 print-header">
            <div>
                <?php if ($receipt['logo_path']): ?>
                    <img src="../<?php echo $receipt['logo_path']; ?>" class="h-24 mb-6 object-contain">
                <?php endif; ?>
                <h1 class="text-3xl font-bold text-slate-900 mb-4 tracking-tight"><?php echo htmlspecialchars($receipt['co_name']); ?></h1>
                <div class="text-sm text-slate-600 space-y-2">
                    <p class="flex items-start"><i class="fas fa-map-marker-alt w-5 mr-2 mt-1 text-slate-400"></i><span><?php echo htmlspecialchars($receipt['co_addr']); ?></span></p>
                    <div class="flex flex-wrap gap-x-6 gap-y-2">
                        <p class="flex items-center"><i class="fas fa-phone w-5 mr-2 text-slate-400"></i><?php echo htmlspecialchars($receipt['co_phone']); ?></p>
                        <p class="flex items-center"><i class="fas fa-envelope w-5 mr-2 text-slate-400"></i><?php echo htmlspecialchars($receipt['co_email']); ?></p>
                    </div>
                </div>
            </div>
            <div class="text-right">
                <div class="bg-emerald-600 text-white p-6 mb-6 inline-block min-w-[200px] text-center">
                    <h2 class="text-3xl font-bold tracking-[0.3em] mb-1">收據</h2>
                    <p class="text-xs font-light tracking-[0.2em] opacity-70 uppercase">Official Receipt</p>
                </div>
                <div class="space-y-4">
                    <div>
                        <p class="text-slate-400 uppercase text-[10px] font-bold tracking-widest mb-1">收據編號 / Receipt No.</p>
                        <p class="text-xl font-mono font-bold text-slate-900"><?php echo htmlspecialchars($receipt['receipt_no']); ?></p>
                    </div>
                    <div>
                        <p class="text-slate-400 uppercase text-[10px] font-bold tracking-widest mb-1">簽發日期 / Date of Issue</p>
                        <p class="text-lg font-medium text-slate-900"><?php echo date('Y-m-d', strtotime($receipt['created_at'])); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Client & Project -->
        <div class="grid grid-cols-2 gap-8 mb-12 relative z-10 print-grid-2">
            <div class="p-8 bg-slate-50 border border-slate-200">
                <h3 class="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4 flex items-center">
                    <span class="w-2 h-2 bg-slate-900 mr-2"></span> 致客戶 / To
                </h3>
                <div class="space-y-2">
                    <p class="text-2xl font-bold text-slate-900"><?php echo htmlspecialchars($receipt['contact_person'] ?: '客戶'); ?></p>
                    <p class="text-sm text-slate-600 leading-relaxed"><?php echo htmlspecialchars($receipt['client_address']); ?></p>
                    <p class="text-sm font-medium text-slate-500 mt-4 flex items-center">
                        <i class="fas fa-phone-alt mr-2 text-xs"></i> <?php echo htmlspecialchars($receipt['phone'] ?: '-'); ?>
                    </p>
                </div>
            </div>
            <div class="p-8 bg-slate-50 border border-slate-200">
                <h3 class="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4 flex items-center">
                    <span class="w-2 h-2 bg-emerald-600 mr-2"></span> 工程項目 / Project
                </h3>
                <div class="space-y-3">
                    <p class="text-xl font-bold text-slate-900 leading-tight"><?php echo htmlspecialchars($receipt['project_name']); ?></p>
                    <div class="pt-4 border-t border-slate-200">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">報價單參考 / Quote Ref.</p>
                        <span class="text-sm font-mono text-slate-600"><?php echo htmlspecialchars($receipt['quote_no']); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Confirmation Content -->
        <div class="relative z-10 flex-grow flex flex-col justify-center py-12 avoid-break">
            <div class="max-w-2xl mx-auto w-full bg-emerald-50 border-y-4 border-emerald-600 p-12 text-center shadow-lg">
                <p class="text-[10px] font-black text-emerald-600 uppercase tracking-[0.4em] mb-8">收到款項確認 / Payment Confirmation</p>
                <p class="text-2xl text-slate-800 mb-8 font-medium">茲收到上述客戶支付工程款項</p>
                <div class="inline-block bg-white px-16 py-8 shadow-inner border border-emerald-100">
                    <p class="text-5xl font-black text-emerald-600 font-mono tracking-tighter">HKD $<?php echo format_amount($receipt['amount']); ?></p>
                </div>
                <div class="mt-10 flex justify-center gap-12 text-sm text-slate-500 italic">
                    <p>比例: <?php echo format_amount($receipt['percentage']); ?>%</p>
                    <p>狀態: 已入賬 / Paid</p>
                </div>
            </div>
        </div>

        <!-- Footer & Signature -->
        <div class="mt-12 relative z-10 avoid-break">
            <div class="grid grid-cols-2 gap-16 print-grid-2">
                <div class="bg-slate-50 p-8 border border-slate-200">
                    <h3 class="text-[10px] font-black text-slate-900 uppercase tracking-[0.2em] mb-6 border-b-2 border-slate-900 pb-2">備註 / Remarks</h3>
                    <div class="space-y-4">
                        <p class="text-[10px] text-slate-500 leading-relaxed">
                            1. 此收據僅作為收到款項之正式憑證。<br>
                            2. 支票付款須待銀行兌現後方為有效。
                        </p>
                    </div>
                </div>
                <div class="flex flex-col justify-end items-center">
                    <div class="relative w-full max-w-[280px]">
                        <?php if ($receipt['stamp_path']): ?>
                            <img src="../<?php echo $receipt['stamp_path']; ?>" class="absolute left-1/2 -translate-x-1/2 w-48 h-48 object-contain opacity-80 pointer-events-none mix-blend-multiply" style="top: -141px">
                        <?php endif; ?>
                        <div class="w-full border-b-2 border-slate-900 mb-4 relative z-10"></div>
                        <div class="text-center relative z-10">
                            <p class="text-[10px] font-black text-slate-900 uppercase tracking-widest mb-1">公司簽署及蓋印</p>
                            <p class="text-[8px] text-slate-400 uppercase tracking-tight">Authorized Signature & Company Chop</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Page Footer -->
        <div class="mt-16 text-center border-t border-slate-100 pt-8 text-[9px] text-slate-400 uppercase tracking-[0.3em] relative z-10">
            <p>這是一份由 <?php echo APP_NAME; ?> 自動生成的正式電子文件，無需手寫簽署亦具備法律效力</p>
            <p class="mt-2">Computer Generated Document | Confidential & Official</p>
        </div>
    </div>

<script>
function sharePrint() {
    const shareData = {
        title: '工程收據 - <?php echo htmlspecialchars($receipt['receipt_no']); ?>',
        text: '<?php echo htmlspecialchars($receipt['project_name']); ?> - $<?php echo format_amount($receipt['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>