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

// 自動建立大類表
$pdo->exec("CREATE TABLE IF NOT EXISTS quote_parent_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// 如果大類表是空的，插入預設大類
$count = $pdo->query("SELECT COUNT(*) FROM quote_parent_categories")->fetchColumn();
if ($count == 0) {
    $defaults = ['保護', '清拆', '泥水', '電力', '木工', '家具定制', '油漆', '其他'];
    $stmt = $pdo->prepare("INSERT INTO quote_parent_categories (category_name) VALUES (?)");
    foreach ($defaults as $cat) {
        $stmt->execute([$cat]);
    }
}

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

// 處理公司設定
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_company') {
        $name = $_POST['name'] ?? '';
        $address = $_POST['address'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $email = $_POST['email'] ?? '';
        $logo_path = '';
        $stamp_path = '';

        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('logo_') . '.' . $ext;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], UPLOAD_DIR . 'logos/' . $filename)) {
                $logo_path = 'uploads/logos/' . $filename;
            }
        }

        if (isset($_FILES['stamp']) && $_FILES['stamp']['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES['stamp']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('stamp_') . '.' . $ext;
            if (move_uploaded_file($_FILES['stamp']['tmp_name'], UPLOAD_DIR . 'logos/' . $filename)) {
                $stamp_path = 'uploads/logos/' . $filename;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO quote_companies (name, logo_path, stamp_path, address, phone, email) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $logo_path, $stamp_path, $address, $phone, $email]);
        $success = '公司資料已成功新增';
    } elseif ($_POST['action'] === 'edit_company') {
        $id = (int)$_POST['id'];
        $name = $_POST['name'] ?? '';
        $address = $_POST['address'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $email = $_POST['email'] ?? '';

        // 先獲取舊路徑
        $stmt = $pdo->prepare("SELECT logo_path, stamp_path FROM quote_companies WHERE id = ?");
        $stmt->execute([$id]);
        $old = $stmt->fetch();
        $logo_path = $old['logo_path'];
        $stamp_path = $old['stamp_path'];

        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('logo_') . '.' . $ext;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], UPLOAD_DIR . 'logos/' . $filename)) {
                $logo_path = 'uploads/logos/' . $filename;
            }
        }

        if (isset($_FILES['stamp']) && $_FILES['stamp']['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES['stamp']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('stamp_') . '.' . $ext;
            if (move_uploaded_file($_FILES['stamp']['tmp_name'], UPLOAD_DIR . 'logos/' . $filename)) {
                $stamp_path = 'uploads/logos/' . $filename;
            }
        }

        $stmt = $pdo->prepare("UPDATE quote_companies SET name = ?, logo_path = ?, stamp_path = ?, address = ?, phone = ?, email = ? WHERE id = ?");
        $stmt->execute([$name, $logo_path, $stamp_path, $address, $phone, $email, $id]);
        $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 = '報價類別已成功新增';
    }
}

// 處理新增大類
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_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 = '大類已成功新增';
    }
}

// 處理刪除大類
if (isset($_GET['delete_parent_category'])) {
    $pdo->prepare("DELETE FROM quote_parent_categories WHERE id = ?")->execute([(int)$_GET['delete_parent_category']]);
    $success = '大類已刪除';
}

// 處理刪除
if (isset($_GET['delete_company'])) {
    try {
        $pdo->prepare("DELETE FROM quote_companies WHERE id = ?")->execute([(int)$_GET['delete_company']]);
        $success = '公司已刪除';
    } catch (PDOException $e) {
        if ($e->getCode() == '23000') {
            $error = '無法刪除：該公司旗下已有報價單或發票紀錄。請先刪除相關紀錄，或直接編輯公司資料。';
        } else {
            $error = '刪除失敗：' . $e->getMessage();
        }
    }
}
if (isset($_GET['delete_category'])) {
    $pdo->prepare("DELETE FROM quote_categories WHERE id = ?")->execute([(int)$_GET['delete_category']]);
    $success = '類別已刪除';
}

$companies = $pdo->query("SELECT * FROM quote_companies ORDER BY created_at DESC")->fetchAll();
$categories = $pdo->query("SELECT * FROM quote_categories ORDER BY category_name ASC")->fetchAll();
$parent_categories = $pdo->query("SELECT * FROM quote_parent_categories ORDER BY category_name ASC")->fetchAll();

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

<div class="mb-8">
    <h1 class="text-2xl font-bold text-slate-800">報價設定</h1>
    <p class="text-slate-500">設定報價單抬頭公司資訊及常用報價項目單價</p>
</div>

<?php if ($success): ?>
    <div class="bg-green-50 text-green-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 flex items-center border border-red-100">
        <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- Company Management -->
    <div class="space-y-6">
        <div class="flex justify-between items-center">
            <h2 class="text-lg font-bold text-slate-800">公司資料管理</h2>
            <button onclick="openModal('company')" class="text-blue-600 hover:text-blue-800 text-sm font-bold">
                <i class="fas fa-plus mr-1"></i> 新增公司
            </button>
        </div>
        <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
            <table class="w-full text-left">
                <thead class="bg-slate-50 text-slate-500 text-xs uppercase font-bold">
                    <tr>
                        <th class="px-6 py-4">公司</th>
                        <th class="px-6 py-4">聯繫方式</th>
                        <th class="px-6 py-4 text-right">操作</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php foreach ($companies as $comp): ?>
                    <tr class="hover:bg-slate-50 transition">
                        <td class="px-6 py-4">
                            <div class="flex items-center">
                                <?php if ($comp['logo_path']): ?>
                                    <img src="../<?php echo $comp['logo_path']; ?>" class="w-10 h-10 object-contain rounded mr-3 bg-slate-100" title="公司 Logo">
                                <?php endif; ?>
                                <?php if ($comp['stamp_path']): ?>
                                    <img src="../<?php echo $comp['stamp_path']; ?>" class="w-10 h-10 object-contain rounded mr-3 bg-slate-100 border border-red-100" title="公司印章">
                                <?php endif; ?>
                                <span class="font-bold text-slate-800"><?php echo htmlspecialchars($comp['name']); ?></span>
                            </div>
                        </td>
                        <td class="px-6 py-4 text-sm text-slate-500">
                            <p><?php echo htmlspecialchars($comp['phone']); ?></p>
                            <p><?php echo htmlspecialchars($comp['email']); ?></p>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <button onclick='openEditModal(<?php echo json_encode($comp); ?>)' class="text-blue-400 hover:text-blue-600 mr-3">
                                <i class="fas fa-edit"></i>
                            </button>
                            <a href="?delete_company=<?php echo $comp['id']; ?>" onclick="return confirm('確定要刪除嗎？')" class="text-slate-400 hover:text-red-600">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Category Management -->
    <div class="space-y-6">
        <div class="flex justify-between items-center">
            <h2 class="text-lg font-bold text-slate-800">常用報價類別</h2>
            <div class="flex gap-2">
                <button onclick="openModal('parent_category')" class="text-blue-600 hover:text-blue-800 text-sm font-bold">
                    <i class="fas fa-folder-plus mr-1"></i> 新增大類
                </button>
                <button onclick="openModal('category')" class="text-blue-600 hover:text-blue-800 text-sm font-bold">
                    <i class="fas fa-plus mr-1"></i> 新增項目
                </button>
            </div>
        </div>

        <?php if (count($parent_categories) > 0): ?>
        <div class="bg-slate-50 rounded-xl p-4 mb-4">
            <h3 class="text-xs font-bold text-slate-500 uppercase mb-3">大類</h3>
            <div class="flex flex-wrap gap-2">
                <?php foreach ($parent_categories as $parent): ?>
                <span class="inline-flex items-center bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">
                    <?php echo htmlspecialchars($parent['category_name']); ?>
                    <a href="?delete_parent_category=<?php echo $parent['id']; ?>" onclick="return confirm('確定要刪除嗎？')" class="ml-2 text-blue-500 hover:text-red-600">
                        <i class="fas fa-times text-xs"></i>
                    </a>
                </span>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
            <table class="w-full text-left">
                <thead class="bg-slate-50 text-slate-500 text-xs uppercase font-bold">
                    <tr>
                        <th class="px-6 py-4">大類/項目</th>
                        <th class="px-6 py-4">單價/單位</th>
                        <th class="px-6 py-4 text-right">操作</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php foreach ($categories as $cat): ?>
                    <tr class="hover:bg-slate-50 transition">
                        <td class="px-6 py-4">
                            <span class="text-[10px] font-bold uppercase bg-slate-100 px-2 py-0.5 rounded text-slate-500 block w-max mb-1">
                                <?php echo htmlspecialchars($cat['category_name']); ?>
                            </span>
                            <span class="font-medium text-slate-800"><?php echo htmlspecialchars($cat['item_name']); ?></span>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <span class="text-blue-600 font-bold">$<?php echo format_amount($cat['unit_price']); ?></span>
                            <span class="text-slate-400">/ <?php echo htmlspecialchars($cat['unit_type']); ?></span>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <a href="?delete_category=<?php echo $cat['id']; ?>" onclick="return confirm('確定要刪除嗎？')" class="text-slate-400 hover:text-red-600">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Company Modal -->
<div id="company-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl">
        <h2 id="modal-title" class="text-xl font-bold text-slate-800 mb-6">新增公司</h2>
        <form action="quote_settings.php" method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="action" id="form-action" value="add_company">
            <input type="hidden" name="id" id="company-id" value="">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">公司名稱 *</label>
                <input type="text" name="name" id="company-name" required class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">公司地址</label>
                <input type="text" name="address" id="company-address" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">電話</label>
                    <input type="text" name="phone" id="company-phone" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">電郵</label>
                    <input type="email" name="email" id="company-email" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">公司 LOGO <span class="text-xs text-slate-400 font-normal">(若不更新請留空)</span></label>
                <input type="file" name="logo" accept="image/*" class="w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">公司印章 <span class="text-xs text-slate-400 font-normal">(若不更新請留空)</span></label>
                <input type="file" name="stamp" accept="image/*" class="w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-red-50 file:text-red-700 hover:file:bg-red-100">
            </div>
            <div class="pt-4 flex gap-3">
                <button type="button" onclick="closeModal('company')" class="flex-1 py-2 border border-slate-200 rounded-lg">取消</button>
                <button type="submit" class="flex-1 py-2 bg-blue-600 text-white rounded-lg">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- Parent Category Modal -->
<div id="parent_category-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl">
        <h2 class="text-xl font-bold text-slate-800 mb-6">新增大類</h2>
        <form action="quote_settings.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="add_parent_category">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">大類名稱 *</label>
                <input type="text" name="parent_category_name" required placeholder="如：保護、清拆、泥水" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="pt-4 flex gap-3">
                <button type="button" onclick="closeModal('parent_category')" class="flex-1 py-2 border border-slate-200 rounded-lg">取消</button>
                <button type="submit" class="flex-1 py-2 bg-blue-600 text-white rounded-lg">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- Category Modal -->
<div id="category-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl">
        <h2 class="text-xl font-bold text-slate-800 mb-6">新增類別項目</h2>
        <form action="quote_settings.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="add_category">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">大類 *</label>
                <select name="category_name" id="category-select" required class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                    <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="block text-sm font-medium text-slate-700 mb-1">項目名稱 *</label>
                <input type="text" name="item_name" required placeholder="如：全屋牆身剷底批灰" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">單價 ($)</label>
                    <input type="number" step="0.01" name="unit_price" required class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">單位</label>
                    <input type="text" name="unit_type" required placeholder="如：一呎、一項" class="w-full px-4 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            <div class="pt-4 flex gap-3">
                <button type="button" onclick="closeModal('category')" class="flex-1 py-2 border border-slate-200 rounded-lg">取消</button>
                <button type="submit" class="flex-1 py-2 bg-blue-600 text-white rounded-lg">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    function openModal(type) {
        if (type === 'company') {
            document.getElementById('modal-title').innerText = '新增公司';
            document.getElementById('form-action').value = 'add_company';
            document.getElementById('company-id').value = '';
            document.getElementById('company-name').value = '';
            document.getElementById('company-address').value = '';
            document.getElementById('company-phone').value = '';
            document.getElementById('company-email').value = '';
        }
        document.getElementById(type + '-modal').classList.remove('hidden');
    }

    function openEditModal(company) {
        document.getElementById('modal-title').innerText = '編輯公司';
        document.getElementById('form-action').value = 'edit_company';
        document.getElementById('company-id').value = company.id;
        document.getElementById('company-name').value = company.name;
        document.getElementById('company-address').value = company.address;
        document.getElementById('company-phone').value = company.phone;
        document.getElementById('company-email').value = company.email;
        document.getElementById('company-modal').classList.remove('hidden');
    }

    function closeModal(type) {
        document.getElementById(type + '-modal').classList.add('hidden');
    }
</script>

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