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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) redirect('/quotations.php');

// 自動增加單位欄位
$stmt = $pdo->query("SHOW COLUMNS FROM quotation_items LIKE 'unit_type'");
if (!$stmt->fetch()) {
    $pdo->exec("ALTER TABLE quotation_items ADD COLUMN unit_type VARCHAR(50) AFTER quantity");
}

// 自動增加排序欄位
$stmt = $pdo->query("SHOW COLUMNS FROM quotation_items LIKE 'sort_order'");
if (!$stmt->fetch()) {
    $pdo->exec("ALTER TABLE quotation_items ADD COLUMN sort_order INT DEFAULT 0");
    // 初始化現有數據的排序
    $pdo->exec("SET @i = 0; UPDATE quotation_items SET sort_order = (@i := @i + 1) ORDER BY id ASC");
}

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

// 獲取報價單基本資料
$stmt = $pdo->prepare("SELECT q.*, c.name as company_name FROM quotations q JOIN quote_companies c ON q.company_id = c.id WHERE q.id = ?");
$stmt->execute([$id]);
$quote = $stmt->fetch();
if (!$quote) redirect('/quotations.php');

// 處理新增項目
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_item') {
    $category = $_POST['category_name'] ?? '';
    $desc = $_POST['description'] ?? '';
    $qty = $_POST['quantity'] ?? 0;
    $unit = $_POST['unit_type'] ?? '';
    $price = $_POST['price'] ?? 0;
    $subtotal = $qty * $price;

    // 獲取當前最大排序值
    $stmt = $pdo->prepare("SELECT MAX(sort_order) FROM quotation_items WHERE quotation_id = ?");
    $stmt->execute([$id]);
    $max_sort = (int)$stmt->fetchColumn();

    $stmt = $pdo->prepare("INSERT INTO quotation_items (quotation_id, category_name, description, quantity, unit_type, price, subtotal, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$id, $category, $desc, $qty, $unit, $price, $subtotal, $max_sort + 1]);

    // 更新報價單總額
    $pdo->prepare("UPDATE quotations SET total_amount = (SELECT SUM(subtotal) FROM quotation_items WHERE quotation_id = ?) WHERE id = ?")
        ->execute([$id, $id]);
    
    $success = '項目已成功新增';
}

// 處理編輯項目
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_item') {
    $item_id = (int)$_POST['item_id'];
    $category = $_POST['category_name'] ?? '';
    $desc = $_POST['description'] ?? '';
    $qty = $_POST['quantity'] ?? 0;
    $unit = $_POST['unit_type'] ?? '';
    $price = $_POST['price'] ?? 0;
    $subtotal = $qty * $price;

    $stmt = $pdo->prepare("UPDATE quotation_items SET category_name = ?, description = ?, quantity = ?, unit_type = ?, price = ?, subtotal = ? WHERE id = ? AND quotation_id = ?");
    $stmt->execute([$category, $desc, $qty, $unit, $price, $subtotal, $item_id, $id]);

    // 更新報價單總額
    $pdo->prepare("UPDATE quotations SET total_amount = (SELECT SUM(subtotal) FROM quotation_items WHERE quotation_id = ?) WHERE id = ?")
        ->execute([$id, $id]);
    
    header("Location: quotation_edit.php?id=$id&success=項目已更新");
    exit;
}

// 處理排序更新 (AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_sort') {
    $order = $_POST['order'] ?? [];
    foreach ($order as $index => $item_id) {
        $stmt = $pdo->prepare("UPDATE quotation_items SET sort_order = ? WHERE id = ? AND quotation_id = ?");
        $stmt->execute([$index, $item_id, $id]);
    }
    echo json_encode(['success' => true]);
    exit;
}

// 處理刪除項目
if (isset($_GET['delete_item'])) {
    $item_id = (int)$_GET['delete_item'];
    $pdo->prepare("DELETE FROM quotation_items WHERE id = ? AND quotation_id = ?")->execute([$item_id, $id]);
    
    // 更新報價單總額
    $pdo->prepare("UPDATE quotations SET total_amount = COALESCE((SELECT SUM(subtotal) FROM quotation_items WHERE quotation_id = ?), 0) WHERE id = ?")
        ->execute([$id, $id]);
    
    $success = '項目已刪除';
}

// 處理常用類別管理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_parent_category') {
        $parent_name = trim($_POST['parent_category_name'] ?? '');
        if ($parent_name !== '') {
            $stmt = $pdo->prepare("INSERT INTO quote_parent_categories (category_name) VALUES (?)");
            $stmt->execute([$parent_name]);
            $success = '大類已成功新增';
        }
    } elseif ($_POST['action'] === 'add_category') {
        $cat_name = $_POST['category_name'] ?? '';
        $item_name = $_POST['item_name'] ?? '';
        $price = $_POST['unit_price'] ?? 0;
        $unit = $_POST['unit_type'] ?? '';
        $stmt = $pdo->prepare("INSERT INTO quote_categories (category_name, item_name, unit_price, unit_type) VALUES (?, ?, ?, ?)");
        $stmt->execute([$cat_name, $item_name, $price, $unit]);
        $success = '常用項目已成功新增';
    } elseif ($_POST['action'] === 'delete_category') {
        $cat_id = (int)$_POST['category_id'];
        $pdo->prepare("DELETE FROM quote_categories WHERE id = ?")->execute([$cat_id]);
        $success = '常用項目已刪除';
    } elseif ($_POST['action'] === 'delete_parent_category') {
        $parent_id = (int)$_POST['parent_id'];
        $pdo->prepare("DELETE FROM quote_parent_categories WHERE id = ?")->execute([$parent_id]);
        $success = '大類已刪除';
    }
}

// 獲取所有項目
$stmt = $pdo->prepare("SELECT * FROM quotation_items WHERE quotation_id = ? ORDER BY sort_order ASC, id ASC");
$stmt->execute([$id]);
$items = $stmt->fetchAll();

// 獲取大類供選擇
$parent_categories = $pdo->query("SELECT * FROM quote_parent_categories ORDER BY category_name ASC")->fetchAll();

// 獲取常用類別供選擇
$categories = $pdo->query("SELECT * FROM quote_categories ORDER BY category_name ASC")->fetchAll();

// 處理編輯報價單基本資料
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_quote') {
    $company_id = (int)($_POST['company_id'] ?? 0);
    $address = $_POST['address'] ?? '';
    $contact = $_POST['contact_person'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $project = $_POST['project_name'] ?? '';
    $date = $_POST['quote_date'] ?? date('Y-m-d');

    if ($company_id > 0 && !empty($address)) {
        $stmt = $pdo->prepare("UPDATE quotations SET company_id = ?, client_address = ?, contact_person = ?, phone = ?, project_name = ?, quote_date = ? WHERE id = ?");
        $stmt->execute([$company_id, $address, $contact, $phone, $project, $date, $id]);
        header("Location: quotation_edit.php?id=$id&success=報價單資料已更新");
        exit;
    } else {
        $error = '請選擇公司及填寫客戶地址';
    }
}

include __DIR__ . '/../includes/header.php';
?>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<style>
    .sortable-ghost {
        opacity: 0.4;
        background-color: #dbeafe !important;
    }
    .drag-handle {
        cursor: grab;
    }
    .drag-handle:active {
        cursor: grabbing;
    }
</style>

<div class="mb-8 flex flex-col sm:flex-row justify-between items-start sm:items-end gap-4">
    <div>
        <nav class="flex text-sm text-[#64748B] mb-1.5 gap-1">
            <a href="quotations.php" class="hover:text-[#4F46E5] transition">報價系統</a>
            <span class="text-[#CBD5E1]">/</span>
            <span class="text-[#0F172A] font-medium">編輯報價單</span>
        </nav>
        <h1 class="m3-headline flex items-center gap-2 flex-wrap">
            <?php echo htmlspecialchars($quote['project_name']); ?>
            <button onclick="openQuoteEditModal()" class="text-[#CBD5E1] hover:text-[#4F46E5] transition p-1 rounded-xl hover:bg-[#F1F5F9]">
                <i class="fas fa-pen text-xs"></i>
            </button>
            <span class="text-sm font-mono font-normal text-[#94A3B8] ml-1">#<?php echo htmlspecialchars($quote['quote_no']); ?></span>
        </h1>
    </div>
    <div class="flex gap-2 w-full sm:w-auto">
        <button onclick="shareQuote()" class="m3-btn m3-btn-text text-sm flex-1 sm:flex-none">
            <i class="fas fa-share-alt"></i> 分享
        </button>
        <a href="quotation_print.php?id=<?php echo $id; ?>" target="_blank" class="m3-btn m3-btn-filled text-sm flex-1 sm:flex-none">
            <i class="fas fa-print mr-1.5"></i> 預覽
        </a>
    </div>
</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; ?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Items Form -->
    <div class="lg:col-span-1">
        <div class="m3-card p-6 sticky top-6">
            <h2 class="m3-title mb-5 flex items-center gap-2">
                <i class="fas fa-plus-circle text-[#4F46E5]"></i> 新增報價項目
            </h2>
            <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="add_item">
                <div>
                    <label class="m3-label">大類</label>
                    <select name="category_name" id="cat-select" onchange="updateItemOptions()" class="m3-select">
                        <option value="其他">-- 請選擇類別 --</option>
                        <?php foreach ($parent_categories as $parent): ?>
                        <option value="<?php echo htmlspecialchars($parent['category_name']); ?>"><?php echo htmlspecialchars($parent['category_name']); ?></option>
                        <?php endforeach; ?>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div>
                    <label class="m3-label">常用項目 (可選)</label>
                    <select id="preset-select" onchange="fillPresetData()" class="m3-select bg-[#F8FAFC]">
                        <option value="">-- 請選擇常用項目 --</option>
                    </select>
                </div>
                <div>
                    <label class="m3-label">項目描述 *</label>
                    <textarea name="description" id="item-desc" required rows="3" class="m3-textarea"></textarea>
                </div>
                <div class="grid grid-cols-3 gap-3">
                    <div>
                        <label class="m3-label">數量</label>
                        <input type="number" step="0.01" name="quantity" id="item-qty" required value="1" class="m3-input">
                    </div>
                    <div>
                        <label class="m3-label">單位</label>
                        <input type="text" name="unit_type" id="item-unit" placeholder="如：呎" class="m3-input">
                    </div>
                    <div>
                        <label class="m3-label">單價 ($)</label>
                        <input type="number" step="0.01" name="price" id="item-price" required class="m3-input">
                    </div>
                </div>
                <button type="submit" class="m3-btn m3-btn-filled w-full">
                    加入報價單
                </button>
            </form>
        </div>

        <!-- 常用類別管理 -->
        <div class="m3-card overflow-hidden mt-5">
            <button type="button" onclick="toggleCategoryPanel()" class="w-full px-5 py-4 flex justify-between items-center hover:bg-[#F8FAFC] transition">
                <h3 class="m3-title-sm flex items-center gap-2">
                    <i class="fas fa-database text-[#4F46E5]"></i> 常用類別管理
                </h3>
                <i class="fas fa-chevron-down text-[#CBD5E1] text-xs transition-transform duration-200" id="cat-toggle-icon"></i>
            </button>
            <div id="category-panel" class="hidden border-t border-[#F1F5F9] px-5 pb-5 pt-4">
                <div class="flex justify-between items-center mb-3">
                    <h4 class="m3-label">大類列表</h4>
                    <button type="button" onclick="openCatModal('parent_category')" class="text-xs font-semibold text-[#4F46E5] hover:text-[#4338CA] transition">
                        <i class="fas fa-folder-plus mr-1"></i> 新增大類
                    </button>
                </div>
                <div class="flex flex-wrap gap-1.5 mb-4">
                    <?php foreach ($parent_categories as $parent): ?>
                    <span class="inline-flex items-center bg-[#EEF2FF] text-[#4F46E5] px-2.5 py-1 rounded-full text-xs font-medium">
                        <?php echo htmlspecialchars($parent['category_name']); ?>
                        <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="inline ml-1.5" onsubmit="return confirm('確定要刪除此大類？')">
                            <input type="hidden" name="action" value="delete_parent_category">
                            <input type="hidden" name="parent_id" value="<?php echo $parent['id']; ?>">
                            <button type="submit" class="hover:text-[#EF4444] transition-colors">
                                <i class="fas fa-times text-[10px]"></i>
                            </button>
                        </form>
                    </span>
                    <?php endforeach; ?>
                </div>

                <div class="flex justify-between items-center mb-3 mt-4">
                    <h4 class="m3-label">常用項目</h4>
                    <button type="button" onclick="openCatModal('category')" class="text-xs font-semibold text-[#4F46E5] hover:text-[#4338CA] transition">
                        <i class="fas fa-plus mr-1"></i> 新增項目
                    </button>
                </div>
                <div class="max-h-48 overflow-y-auto">
                    <table class="w-full text-xs">
                        <thead class="text-[#94A3B8] uppercase font-bold border-b border-[#F1F5F9]">
                            <tr>
                                <th class="py-1.5 text-left">項目</th>
                                <th class="py-1.5 text-right">單價</th>
                                <th class="py-1.5 text-right w-8"></th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#F8FAFC]">
                            <?php foreach ($categories as $cat): ?>
                            <tr>
                                <td class="py-1.5">
                                    <span class="text-[9px] font-bold text-[#4F46E5] block"><?php echo htmlspecialchars($cat['category_name']); ?></span>
                                    <span class="text-[#0F172A]"><?php echo htmlspecialchars($cat['item_name']); ?></span>
                                </td>
                                <td class="py-1.5 text-right text-[#0F172A] font-mono">
                                    $<?php echo format_amount($cat['unit_price']); ?>
                                    <span class="text-[#94A3B8] text-[10px]">/<?php echo htmlspecialchars($cat['unit_type']); ?></span>
                                </td>
                                <td class="py-1.5 text-right">
                                    <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" onsubmit="return confirm('確定要刪除此項目？')">
                                        <input type="hidden" name="action" value="delete_category">
                                        <input type="hidden" name="category_id" value="<?php echo $cat['id']; ?>">
                                        <button type="submit" class="text-[#CBD5E1] hover:text-[#EF4444] transition">
                                            <i class="fas fa-times text-[10px]"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- AI 智能輸入 -->
        <div class="m3-card overflow-hidden mt-5">
            <button type="button" onclick="toggleAIPanel()" class="w-full px-5 py-4 flex justify-between items-center hover:bg-[#F8FAFC] transition">
                <h3 class="m3-title-sm flex items-center gap-2">
                    <i class="fas fa-robot text-[#AF52DE]"></i> AI 智能輸入
                </h3>
                <i class="fas fa-chevron-down text-[#CBD5E1] text-xs transition-transform duration-200" id="ai-toggle-icon"></i>
            </button>
            <div id="ai-panel" class="hidden border-t border-[#F1F5F9] px-5 pb-5 pt-4">
                <p class="text-xs text-[#64748B] mb-3">輸入裝修項目需求，AI 會自動匹配類別、生成報價項目</p>
                <textarea id="ai-input" rows="4" placeholder="例如：全屋鏟底批灰 150呎，廳房天花油漆 200呎，浴室防水 1項，廚房灶台 1個" class="m3-textarea resize-none"></textarea>
                <div class="flex gap-2 mt-3">
                    <button type="button" onclick="startRecording()" id="record-btn" class="m3-btn m3-btn-tonal m3-btn-sm flex items-center gap-1.5">
                        <i class="fas fa-microphone"></i> 錄音
                    </button>
                    <button type="button" onclick="submitAI()" id="ai-submit-btn" class="flex-1 m3-btn" style="background: #AF52DE; color: white; border-radius: 9999px;">
                        <i class="fas fa-wand-magic-sparkles"></i> AI 生成項目
                    </button>
                </div>
                <div id="ai-status" class="mt-3 hidden"></div>
            </div>
        </div>
    </div>

    <!-- Items List -->
    <div class="lg:col-span-2">
        <div class="m3-card overflow-hidden">
            <div class="table-responsive">
            <table class="m3-table">
                <thead>
                    <tr>
                        <th class="w-10"></th>
                        <th>類別 / 描述</th>
                        <th>數量 / 單位</th>
                        <th>單價</th>
                        <th>小計</th>
                        <th class="text-right">操作</th>
                    </tr>
                </thead>
                <tbody id="sortable-items">
                    <?php foreach ($items as $item): ?>
                    <tr data-id="<?php echo $item['id']; ?>">
                        <td class="text-[#CBD5E1] w-10">
                            <i class="fas fa-grip-vertical drag-handle hover:text-[#94A3B8] transition cursor-grab"></i>
                        </td>
                        <td>
                            <span class="text-[10px] font-bold uppercase bg-[#EEF2FF] text-[#4F46E5] px-2 py-0.5 rounded block w-max mb-1">
                                <?php echo htmlspecialchars($item['category_name']); ?>
                            </span>
                            <span class="text-sm text-[#0F172A]"><?php echo nl2br(htmlspecialchars($item['description'])); ?></span>
                        </td>
                        <td class="text-sm text-[#64748B] whitespace-nowrap">
                            <?php echo format_amount($item['quantity']); ?>
                            <span class="text-[#94A3B8] text-xs"><?php echo htmlspecialchars($item['unit_type']); ?></span>
                        </td>
                        <td class="text-sm text-[#64748B] whitespace-nowrap">$<?php echo format_amount($item['price']); ?></td>
                        <td class="text-sm font-bold text-[#0F172A] whitespace-nowrap">$<?php echo format_amount($item['subtotal']); ?></td>
                        <td class="text-right whitespace-nowrap">
                            <div class="action-group justify-end">
                                <button onclick="openEditModal(<?php echo htmlspecialchars(json_encode($item)); ?>)" title="編輯">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <a href="?id=<?php echo $id; ?>&delete_item=<?php echo $item['id']; ?>" onclick="return confirm('確定刪除？')" title="刪除">
                                    <i class="fas fa-times-circle"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot style="border-top: 1px solid #F1F5F9;">
                    <tr>
                        <td colspan="3" class="text-right text-[#64748B] text-sm font-medium">總計金額</td>
                        <td class="text-lg font-bold text-[#4F46E5]" colspan="2">$<?php echo format_amount($quote['total_amount']); ?></td>
                    </tr>
                </tfoot>
            </table>
            </div>
        </div>
    </div>
</div>

<!-- Edit Item Modal -->
<div id="edit-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeEditModal()">
    <div class="m3-dialog w-full max-w-lg p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="m3-title">編輯項目</h2>
            <button onclick="closeEditModal()" class="text-[#94A3B8] hover:text-[#0F172A] p-1 rounded-xl hover:bg-[#F1F5F9] transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="edit_item">
            <input type="hidden" name="item_id" id="edit-item-id">
            
            <div>
                <label class="m3-label">大類</label>
                <select name="category_name" id="edit-cat-select" class="m3-select">
                    <?php foreach ($parent_categories as $parent): ?>
                    <option value="<?php echo htmlspecialchars($parent['category_name']); ?>"><?php echo htmlspecialchars($parent['category_name']); ?></option>
                    <?php endforeach; ?>
                    <option value="其他">其他</option>
                </select>
            </div>
            <div>
                <label class="m3-label">項目描述 *</label>
                <textarea name="description" id="edit-item-desc" required rows="4" class="m3-textarea"></textarea>
            </div>
            <div class="grid grid-cols-3 gap-4">
                <div>
                    <label class="m3-label">數量</label>
                    <input type="number" step="0.01" name="quantity" id="edit-item-qty" required class="m3-input">
                </div>
                <div>
                    <label class="m3-label">單位</label>
                    <input type="text" name="unit_type" id="edit-item-unit" class="m3-input">
                </div>
                <div>
                    <label class="m3-label">單價 ($)</label>
                    <input type="number" step="0.01" name="price" id="edit-item-price" required class="m3-input">
                </div>
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="closeEditModal()" 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>

<!-- 新增大類 Modal -->
<div id="parent_category-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeCatModal('parent_category')">
    <div class="m3-dialog w-full max-w-md p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="m3-title">新增大類</h2>
            <button type="button" onclick="closeCatModal('parent_category')" class="text-[#94A3B8] hover:text-[#0F172A] p-1 rounded-xl hover:bg-[#F1F5F9] transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="add_parent_category">
            <div>
                <label class="m3-label">大類名稱 *</label>
                <input type="text" name="parent_category_name" required placeholder="如：保護、清拆、泥水" class="m3-input">
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="closeCatModal('parent_category')" 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>

<!-- 新增常用項目 Modal -->
<div id="category-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeCatModal('category')">
    <div class="m3-dialog w-full max-w-md p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="m3-title">新增常用項目</h2>
            <button type="button" onclick="closeCatModal('category')" class="text-[#94A3B8] hover:text-[#0F172A] p-1 rounded-xl hover:bg-[#F1F5F9] transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="add_category">
            <div>
                <label class="m3-label">大類 *</label>
                <select name="category_name" required class="m3-select">
                    <option value="">請選擇大類</option>
                    <?php foreach ($parent_categories as $parent): ?>
                    <option value="<?php echo htmlspecialchars($parent['category_name']); ?>"><?php echo htmlspecialchars($parent['category_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="m3-label">項目名稱 *</label>
                <input type="text" name="item_name" required placeholder="如：全屋牆身剷底批灰" class="m3-input">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="m3-label">單價 ($)</label>
                    <input type="number" step="0.01" name="unit_price" required class="m3-input">
                </div>
                <div>
                    <label class="m3-label">單位</label>
                    <input type="text" name="unit_type" required placeholder="如：一呎、一項" class="m3-input">
                </div>
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="closeCatModal('category')" 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>

<!-- 編輯基本資料 Modal -->
<div id="quote-edit-modal" class="hidden fixed inset-0 m3-overlay z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeQuoteEditModal()">
    <div class="m3-dialog w-full max-w-lg p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="m3-title">編輯報價單資料</h2>
            <button onclick="closeQuoteEditModal()" class="text-[#94A3B8] hover:text-[#0F172A] p-1 rounded-xl hover:bg-[#F1F5F9] transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <?php
        $companies = $pdo->query("SELECT id, name FROM quote_companies ORDER BY name ASC")->fetchAll();
        ?>
        <form action="quotation_edit.php?id=<?php echo $id; ?>" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="edit_quote">
            <div>
                <label class="m3-label">選擇公司 *</label>
                <select name="company_id" id="eq-company" 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" id="eq-project" class="m3-input">
            </div>
            <div>
                <label class="m3-label">客戶地址 *</label>
                <input type="text" name="address" id="eq-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" id="eq-contact" class="m3-input">
                </div>
                <div>
                    <label class="m3-label">聯絡電話</label>
                    <input type="text" name="phone" id="eq-phone" class="m3-input">
                </div>
            </div>
            <div>
                <label class="m3-label">報價日期</label>
                <input type="date" name="quote_date" id="eq-date" class="m3-input">
            </div>
            <div class="flex gap-3 pt-2">
                <button type="button" onclick="closeQuoteEditModal()" 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>

<script>
    const presets = <?php echo json_encode($categories); ?>;

    function updateItemOptions() {
        const cat = document.getElementById('cat-select').value;
        const select = document.getElementById('preset-select');
        select.innerHTML = '<option value="">-- 請選擇常用項目 --</option>';
        
        presets.filter(p => p.category_name === cat).forEach(p => {
            const opt = document.createElement('option');
            opt.value = p.id;
            opt.innerText = p.item_name;
            select.appendChild(opt);
        });
    }

    function fillPresetData() {
        const id = document.getElementById('preset-select').value;
        const p = presets.find(item => item.id == id);
        if (p) {
            document.getElementById('item-desc').value = p.item_name;
            document.getElementById('item-price').value = p.unit_price;
            document.getElementById('item-unit').value = p.unit_type;
        }
    }

    // 編輯 Modal 功能
    function openEditModal(item) {
        document.getElementById('edit-item-id').value = item.id;
        document.getElementById('edit-cat-select').value = item.category_name;
        document.getElementById('edit-item-desc').value = item.description;
        document.getElementById('edit-item-qty').value = item.quantity;
        document.getElementById('edit-item-unit').value = item.unit_type;
        document.getElementById('edit-item-price').value = item.price;
        document.getElementById('edit-modal').classList.remove('hidden');
    }

    function closeEditModal() {
        document.getElementById('edit-modal').classList.add('hidden');
    }

    // 常用類別管理功能
    function toggleCategoryPanel() {
        const panel = document.getElementById('category-panel');
        const icon = document.getElementById('cat-toggle-icon');
        panel.classList.toggle('hidden');
        icon.style.transform = panel.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
    }

    function openCatModal(type) {
        document.getElementById(type + '-modal').classList.remove('hidden');
    }

    function closeCatModal(type) {
        document.getElementById(type + '-modal').classList.add('hidden');
    }

    // 編輯報價單基本資料
    function openQuoteEditModal() {
        document.getElementById('eq-company').value = '<?php echo $quote['company_id']; ?>';
        document.getElementById('eq-project').value = '<?php echo htmlspecialchars($quote['project_name']); ?>';
        document.getElementById('eq-address').value = '<?php echo htmlspecialchars($quote['client_address']); ?>';
        document.getElementById('eq-contact').value = '<?php echo htmlspecialchars($quote['contact_person']); ?>';
        document.getElementById('eq-phone').value = '<?php echo htmlspecialchars($quote['phone']); ?>';
        document.getElementById('eq-date').value = '<?php echo $quote['quote_date']; ?>';
        document.getElementById('quote-edit-modal').classList.remove('hidden');
    }

    function closeQuoteEditModal() {
        document.getElementById('quote-edit-modal').classList.add('hidden');
    }

    // 拖拽排序功能
    const el = document.getElementById('sortable-items');
    if (el) {
        Sortable.create(el, {
            animation: 150,
            handle: '.drag-handle',
            ghostClass: 'sortable-ghost',
            onEnd: function() {
                const order = [];
                el.querySelectorAll('tr').forEach(tr => {
                    order.push(tr.dataset.id);
                });

                // 發送到後端更新排序
                const formData = new FormData();
                formData.append('action', 'update_sort');
                order.forEach((id, index) => {
                    formData.append('order[]', id);
                });

                fetch('quotation_edit.php?id=<?php echo $id; ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('排序已更新');
                    }
                })
                .catch(error => console.error('排序更新失敗:', error));
            }
        });
    }

    // AI 功能
    let isRecording = false;
    let recognition = null;

    function toggleAIPanel() {
        const panel = document.getElementById('ai-panel');
        const icon = document.getElementById('ai-toggle-icon');
        panel.classList.toggle('hidden');
        icon.style.transform = panel.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
    }

    function startRecording() {
        const btn = document.getElementById('record-btn');
        
        if (isRecording) {
            if (recognition) recognition.stop();
            isRecording = false;
            btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
            btn.classList.remove('text-red-500', 'border-red-200');
            btn.classList.add('text-slate-500');
            return;
        }

        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            alert('您的瀏覽器不支援語音辨識，請使用 Chrome 或 Edge 瀏覽器，或直接輸入文字。');
            return;
        }

        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
        recognition.lang = 'zh-HK';
        recognition.continuous = true;
        recognition.interimResults = true;

        recognition.onstart = function() {
            isRecording = true;
            btn.innerHTML = '<i class="fas fa-stop"></i> 停止錄音';
            btn.classList.remove('text-slate-500');
            btn.classList.add('text-red-500', 'border-red-200');
        };

        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.onerror = function() {
            isRecording = false;
            btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
            btn.classList.remove('text-red-500', 'border-red-200');
            btn.classList.add('text-slate-500');
        };

        recognition.onend = function() {
            isRecording = false;
            btn.innerHTML = '<i class="fas fa-microphone"></i> 錄音';
            btn.classList.remove('text-red-500', 'border-red-200');
            btn.classList.add('text-slate-500');
        };

        recognition.start();
    }

    function submitAI() {
        const input = document.getElementById('ai-input').value.trim();
        if (!input) {
            alert('請先輸入裝修項目需求');
            return;
        }

        const btn = document.getElementById('ai-submit-btn');
        const status = document.getElementById('ai-status');
        
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> AI 處理中...';
        status.className = 'mt-3 p-3 bg-purple-50 text-purple-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);
        formData.append('quotation_id', '<?php echo $id; ?>');

        fetch('quotation_ai.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                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> ' + data.message;
                // 重新載入頁面以顯示新項目
                setTimeout(() => location.reload(), 1500);
            } 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;
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-wand-magic-sparkles"></i> AI 生成項目';
        });
    }

    function shareQuote() {
        const base = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
        const fullUrl = base + 'quotation_print.php?id=<?php echo $id; ?>';
        const shareData = {
            title: '裝修報價單',
            text: '<?php echo htmlspecialchars($quote['project_name']); ?>',
            url: fullUrl
        };
        if (navigator.share) {
            navigator.share(shareData).catch(function(e) {
                if (e.name !== 'AbortError') fallbackCopy(fullUrl, '報價單');
            });
        } else {
            fallbackCopy(fullUrl, '報價單');
        }
    }

    function fallbackCopy(url, label) {
        navigator.clipboard.writeText(url).then(function() {
            alert(label + '連結已複製到剪貼簿');
        }).catch(function() {
            prompt('請複製以下連結以分享：', url);
        });
    }
</script>

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