<!DOCTYPE html>
<html>
<head>
    <title>จัดการสินค้า</title>
    <link rel="stylesheet" href="/css/style.css">
    <script>
        function getStockStatus(current, minimum) {
            current = parseInt(current) || 0;
            minimum = parseInt(minimum) || 0;
            
            if (current <= 0) {
                return { text: 'หมด', class: 'status-out' };
            }
            if (current <= minimum) {
                return { text: 'ต่ำ', class: 'status-low' };
            }
            return { text: 'ปกติ', class: 'status-normal' };
        }
    </script>
</head>
<body>
    <div class="container">
        
        <div class="header">
            <h1>จัดการสต็อกสินค้า</h1>
            <nav>
                <a href="/categories">จัดการหมวดหมู่</a>
                <a href="/auth/logout" class="logout-btn">ออกจากระบบ</a>
            </nav>
        </div>
        <div class="search-section">
            <form action="/products" method="GET" class="search-form">
                <input 
                    type="text" 
                    name="search"   
                    placeholder="ค้นหาสินค้า" 
                    value="<%= searchQuery %>"
                >
                <button type="submit">ค้นหา</button>
                <% if (searchQuery) { %>
                    <a href="/products" class="clear-search">ล้างการค้นหา</a>
                <% } %>
            </form>
        </div>

       
        <div class="add-product-section">
            <form action="/products" method="POST">
                <div class="form-row">
                    <input type="text" name="name" placeholder="ชื่อสินค้า" required>
                    <input type="number" name="price" placeholder="ราคา" required>
                </div>
                <div class="form-row">
                    <input type="number" name="stock_quantity" placeholder="จำนวนในสต็อก" required>
                    <input type="number" name="minimum_stock" placeholder="จำนวนขั้นต่ำ" required>
                </div>
                <div class="form-row">
                    <input type="text" name="location" placeholder="ตำแหน่งจัดเก็บ">
                    <select name="category_id" required>
                        <option value="">เลือกหมวดหมู่</option>
                        <% categories.forEach(category => { %>
                            <option value="<%= category.id %>"><%= category.name %></option>
                        <% }); %>
                    </select>
                </div>
                <button type="submit">เพิ่มสินค้า</button>
            </form>
        </div>

        
        <div class="product-list">
            <table>
                <thead>
                    <tr>
                        <th>ชื่อสินค้า</th>
                        <th>ราคา</th>
                        <th>จำนวน</th>
                        <th>ขั้นต่ำ</th>
                        <th>ตำแหน่ง</th>
                        <th>หมวดหมู่</th>
                        <th>สถานะ</th>
                        <th>จัดการ</th>
                    </tr>
                </thead>
                <tbody>
                    <% if (products && products.length > 0) { %>
                        <% products.forEach(product => { %>
                            <tr>
                                <td><%= product.name %></td>
                                <td><%= product.price %></td>
                                <td><%= product.stock_quantity %></td>
                                <td><%= product.minimum_stock %></td>
                                <td><%= product.location || '-' %></td>
                                <td><%= product.category_name %></td>
                                <td>
                                    <% const status = getStockStatus(product.stock_quantity, product.minimum_stock); %>
                                    <span class="status <%= status.class %>"><%= status.text %></span>
                                </td>
                                <td>
                                    <button onclick="editProduct('<%= product.id %>')">แก้ไข</button>
                                    <button onclick="deleteProduct('<%= product.id %>')">ลบ</button>
                                    <button onclick="showStockModal('<%= product.id %>', 'in')">เพิ่มสต็อก</button>
                                    <button onclick="showStockModal('<%= product.id %>', 'out')">เบิกสต็อก</button>
                                    <button onclick="showHistory('<%= product.id %>')">ประวัติ</button>
                                </td>
                            </tr>
                        <% }); %>
                    <% } else { %>
                        <tr>
                            <td colspan="8" class="empty-message">ไม่พบข้อมูลสินค้า</td>
                        </tr>
                    <% } %>
                </tbody>
            </table>
        </div>
    </div>

    
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h2>แก้ไขสินค้า</h2>
            <form id="editForm">
                <div class="form-row">
                    <input type="text" id="editName" placeholder="ชื่อสินค้า" required>
                    <input type="number" id="editPrice" placeholder="ราคา" required>
                </div>
                <div class="form-row">
                    <input type="text" id="editLocation" placeholder="ตำแหน่งจัดเก็บ">
                    <select id="editCategory" required>
                        <option value="">เลือกหมวดหมู่</option>
                        <% categories.forEach(category => { %>
                            <option value="<%= category.id %>"><%= category.name %></option>
                        <% }); %>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit">บันทึก</button>
                    <button type="button" onclick="closeEditModal()">ยกเลิก</button>
                </div>
            </form>
        </div>
    </div>

   
    <div id="stockModal" class="modal">
        <div class="modal-content">
            <h2 id="modalTitle"></h2>
            <form id="stockForm">
                <input type="number" id="stockQuantity" placeholder="จำนวน" required>
                <textarea id="stockDescription" placeholder="รายละเอียด"></textarea>
                <div class="form-actions">
                    <button type="submit">บันทึก</button>
                    <button type="button" onclick="closeModal()">ยกเลิก</button>
                </div>
            </form>
        </div>
    </div>

   
    <div id="historyModal" class="modal">
        <div class="modal-content">
            <h2>ประวัติการเคลื่อนไหว</h2>
            <table id="historyTable">
                <thead>
                    <tr>
                        <th>วันที่</th>
                        <th>ประเภท</th>
                        <th>จำนวน</th>
                        <th>ผู้ดำเนินการ</th>
                        <th>รายละเอียด</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <button onclick="closeHistoryModal()">ปิด</button>
        </div>
    </div>

    <script>
        const editModal = document.getElementById('editModal');
        let currentProductId = null;
        function editProduct(id) {
            currentProductId = id;
            fetch(`/products/${id}`)
                .then(response => response.json())
                .then(product => {
                    document.getElementById('editName').value = product.name;
                    document.getElementById('editPrice').value = product.price;
                    document.getElementById('editStockQuantity').value = product.stock_quantity;
                    document.getElementById('editMinimumStock').value = product.minimum_stock;
                    document.getElementById('editLocation').value = product.location || '';
                    document.getElementById('editCategory').value = product.category_id;
                    editModal.style.display = 'block';
                });
        }

        function closeEditModal() {
            editModal.style.display = 'none';
        }

        document.getElementById('editForm').onsubmit = function(e) {
            e.preventDefault();
            const data = {
                name: document.getElementById('editName').value,
                price: document.getElementById('editPrice').value,
                stock_quantity: document.getElementById('editStockQuantity').value,
                minimum_stock: document.getElementById('editMinimumStock').value,
                location: document.getElementById('editLocation').value,
                category_id: document.getElementById('editCategory').value
            };

            fetch(`/products/${currentProductId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }).then(() => {
                closeEditModal();
                window.location.reload();
            });
        };

        function deleteProduct(id) {
            if (confirm('ต้องการลบสินค้านี้?')) {
                fetch(`/products/${id}`, { method: 'DELETE' })
                    .then(() => window.location.reload());
            }
        }

        let currentType;

        function showStockModal(productId, type) {
            currentProductId = productId;
            currentType = type;
            document.getElementById('modalTitle').textContent = type === 'in' ? 'เพิ่มสต็อก' : 'เบิกสต็อก';
            document.getElementById('stockModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('stockModal').style.display = 'none';
            document.getElementById('stockForm').reset();
        }

        document.getElementById('stockForm').onsubmit = async function(e) {
            e.preventDefault();
            const data = {
                product_id: currentProductId,
                quantity: document.getElementById('stockQuantity').value,
                description: document.getElementById('stockDescription').value
            };

            const url = currentType === 'in' ? '/stock/add' : '/stock/remove';
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    closeModal();
                    location.reload();
                } else {
                    const error = await response.json();
                    alert(error.error);
                }
            } catch (err) {
                console.error(err);
                alert('เกิดข้อผิดพลาด');
            }
        };

        async function showHistory(productId) {
            try {
                const response = await fetch(`/stock/history/${productId}`);
                const movements = await response.json();
                
                const tbody = document.querySelector('#historyTable tbody');
                tbody.innerHTML = movements.map(m => `
                    <tr>
                        <td>${new Date(m.date).toLocaleString()}</td>
                        <td>${m.type === 'in' ? 'รับเข้า' : 'เบิกออก'}</td>
                        <td>${m.quantity}</td>
                        <td>${m.user_name}</td>
                        <td>${m.description || '-'}</td>
                    </tr>
                `).join('');        
                document.getElementById('historyModal').style.display = 'block';
            } catch (err) {
                console.error(err);
                alert('เกิดข้อผิดพลาด');
            }
        }
        function closeHistoryModal() {
            document.getElementById('historyModal').style.display = 'none';
        }
    </script>

</body>
</html>