<?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 receipts WHERE id = ?");
        $stmt->execute([$id]);
        $success = '收據已成功刪除';
    } else {
        $error = '無效的收據ID';
    }
}

// 處理收據生成
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate') {
    $quote_id = $_POST['quotation_id'] ?? '';
    $percentage = (int)($_POST['percentage'] ?? 0);
    $receipt_no = 'REC-' . date('Ymd') . '-' . rand(100, 999);
    
    // 獲取報價單總額
    $stmt = $pdo->prepare("SELECT total_amount FROM quotations WHERE id = ?");
    $stmt->execute([$quote_id]);
    $quote_amount = $stmt->fetchColumn();
    
    if ($quote_id && $percentage > 0 && $percentage <= 100) {
        $amount = $quote_amount * ($percentage / 100);
        $stmt = $pdo->prepare("INSERT INTO receipts (quotation_id, receipt_no, amount, percentage) VALUES (?, ?, ?, ?)");
        $stmt->execute([$quote_id, $receipt_no, $amount, $percentage]);
        $success = '收據已成功生成';
    } else {
        $error = '請選擇報價單並輸入正確百分比';
    }
}

// 獲取所有收據
$receipts = $pdo->query("
    SELECT r.*, q.quote_no, q.project_name, c.name as company_name 
    FROM receipts r 
    JOIN quotations q ON r.quotation_id = q.id 
    JOIN quote_companies c ON q.company_id = c.id 
    ORDER BY r.created_at DESC
")->fetchAll();

// 獲取所有報價單供選擇
$quotations = $pdo->query("SELECT id, quote_no, project_name FROM quotations ORDER BY created_at DESC")->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>
    <button onclick="document.getElementById('add-modal').classList.remove('hidden')" 
        class="m3-btn m3-btn-success w-full sm:w-auto">
        <i class="fas fa-plus"></i> 生成新收據
    </button>
</div>

<?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; ?>

<?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; ?>

<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="whitespace-nowrap">日期</th>
                <th class="text-right whitespace-nowrap">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($receipts as $rec): ?>
            <tr>
                <td class="font-mono text-sm font-bold text-[#10B981] whitespace-nowrap"><?php echo htmlspecialchars($rec['receipt_no']); ?></td>
                <td class="text-xs text-[#64748B] whitespace-nowrap"><?php echo htmlspecialchars($rec['quote_no']); ?></td>
                <td class="font-medium text-[#0F172A]">
                    <span class="truncate-mobile block"><?php echo htmlspecialchars($rec['project_name']); ?></span>
                </td>
                <td class="whitespace-nowrap">
                    <span class="m3-chip m3-chip-success"><?php echo format_amount($rec['percentage']); ?>%</span>
                </td>
                <td class="font-bold text-[#0F172A] whitespace-nowrap">$<?php echo format_amount($rec['amount']); ?></td>
                <td class="text-sm text-[#64748B] whitespace-nowrap"><?php echo date('Y-m-d', strtotime($rec['created_at'])); ?></td>
                <td class="text-right whitespace-nowrap">
                    <div class="action-group">
                    <button type="button" onclick="downloadPDF('receipt_print', <?php echo $rec['id']; ?>)" title="下載 PDF">
                        <i class="fas fa-file-pdf"></i>
                    </button>
                    <a href="receipt_print.php?id=<?php echo $rec['id']; ?>" target="_blank" title="列印">
                        <i class="fas fa-print"></i>
                    </a>
                    <button type="button" onclick="shareReceipt(<?php echo $rec['id']; ?>)" title="分享">
                        <i class="fas fa-share-alt"></i>
                    </button>
                    <button type="button" onclick="confirmDelete(<?php echo $rec['id']; ?>, '<?php echo htmlspecialchars($rec['receipt_no']); ?>')" title="刪除">
                        <i class="fas fa-trash"></i>
                    </button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($receipts)): ?>
            <tr>
                <td colspan="7" class="text-center py-12 text-[#94A3B8] text-sm">暫無收據記錄</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

<!-- 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-md p-8">
        <h2 class="m3-title mb-6">生成工程收據</h2>
        <form action="receipts.php" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="generate">
            <div>
                <label class="m3-label">選擇報價單 *</label>
                <select name="quotation_id" required class="m3-select">
                    <option value="">-- 請選擇報價單 --</option>
                    <?php foreach ($quotations as $q): ?>
                    <option value="<?php echo $q['id']; ?>"><?php echo htmlspecialchars($q['quote_no'] . ' - ' . $q['project_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="m3-label">收款比例 (1% - 100%) *</label>
                <div class="relative">
                    <input type="number" name="percentage" min="1" max="100" required placeholder="如：40"
                        class="m3-input pr-12">
                    <span class="absolute right-4 top-1/2 -translate-y-1/2 text-[#94A3B8] text-sm font-medium">%</span>
                </div>
                <p class="text-xs text-[#94A3B8] mt-1.5">金額將根據報價單總額自動計算</p>
            </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-success font-bold">生成收據</button>
            </div>
        </form>
    </div>
</div>

<script>
function confirmDelete(id, receiptNo) {
    if (confirm('確定要刪除收據 ' + receiptNo + ' 嗎？\n\n此操作無法撤銷，請確認。')) {
        document.getElementById('delete-form').querySelector('input[name="id"]').value = id;
        document.getElementById('delete-form').submit();
    }
}
</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 shareReceipt(id) {
    const base = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const fullUrl = base + 'receipt_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'; ?>
