<!DOCTYPE html>
<html lang="th">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Generator</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;600;700&display=swap');

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans Thai', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .tabs {
            display: flex;
            border-bottom: 2px solid #f0f2f5;
            margin-bottom: 30px;
        }

        .tab {
            padding: 15px 25px;
            background: none;
            border: none;
            font-size: 16px;
            font-weight: 500;
            color: #666;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }

        .tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }

        .tab:hover {
            color: #667eea;
            background: #f8f9ff;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-section {
            background: #f8f9ff;
            padding: 25px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
            margin-bottom: 25px;
        }

        .form-section h3 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.3rem;
            font-weight: 600;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #333;
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e4e7;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            font-family: 'Noto Sans Thai', sans-serif;
        }

        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 80px;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .items-table th {
            background: #667eea;
            color: white;
            padding: 15px 10px;
            text-align: center;
            font-weight: 600;
        }

        .items-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #f0f2f5;
        }

        .items-table input {
            border: 1px solid #ddd;
            padding: 8px;
            margin: 0;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
            font-family: 'Noto Sans Thai', sans-serif;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin: 20px 0;
            flex-wrap: wrap;
        }

        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .summary-section {
            background: #f8f9ff;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 5px 0;
        }

        .summary-row.total {
            border-top: 2px solid #667eea;
            padding-top: 15px;
            margin-top: 15px;
            font-weight: bold;
            font-size: 1.1em;
            color: #667eea;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }

            .btn-group {
                flex-direction: column;
            }

            .btn {
                width: 100%;
            }

            body {
                padding: 10px;
            }

            .content {
                padding: 20px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>🧾 Invoice Generator</h1>
            <p>ระบบสร้างและจัดการใบแจ้งหนี้อัตโนมัติ</p>
        </div>

        <div class="content">
            <div class="tabs">
                <button class="tab active" onclick="showTab('company')">ข้อมูลบริษัท</button>
                <button class="tab" onclick="showTab('customer')">ข้อมูลลูกค้า</button>
                <button class="tab" onclick="showTab('invoice')">ข้อมูลใบแจ้งหนี้</button>
                <button class="tab" onclick="showTab('items')">รายการสินค้า/บริการ</button>
                <button class="tab" onclick="showTab('summary')">สรุปและส่งออก</button>
            </div>

            <div id="alert-container"></div>

            <!-- Company Tab -->
            <div id="company" class="tab-content active">
                <div class="form-section">
                    <h3>ข้อมูลบริษัท</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>ชื่อบริษัท</label>
                            <input type="text" id="company_name" placeholder="ชื่อบริษัท">
                        </div>
                        <div class="form-group">
                            <label>เลขประจำตัวผู้เสียภาษี</label>
                            <input type="text" id="company_tax_id" placeholder="เลขประจำตัวผู้เสียภาษี">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>ที่อยู่</label>
                        <textarea id="company_address" placeholder="ที่อยู่บริษัท"></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>เบอร์โทรศัพท์</label>
                            <input type="text" id="company_phone" placeholder="เบอร์โทรศัพท์">
                        </div>
                        <div class="form-group">
                            <label>อีเมล</label>
                            <input type="email" id="company_email" placeholder="อีเมล">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Customer Tab -->
            <div id="customer" class="tab-content">
                <div class="form-section">
                    <h3>ข้อมูลลูกค้า</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>รหัสลูกค้า</label>
                            <input type="text" id="customer_id" placeholder="รหัสลูกค้า">
                        </div>
                        <div class="form-group">
                            <label>เลขประจำตัวผู้เสียภาษี</label>
                            <input type="text" id="customer_tax_id" placeholder="เลขประจำตัวผู้เสียภาษี">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>ชื่อลูกค้า</label>
                        <input type="text" id="customer_name" placeholder="ชื่อลูกค้า">
                    </div>
                    <div class="form-group">
                        <label>ที่อยู่</label>
                        <textarea id="customer_address" placeholder="ที่อยู่ลูกค้า"></textarea>
                    </div>
                </div>
            </div>

            <!-- Invoice Tab -->
            <div id="invoice" class="tab-content">
                <div class="form-section">
                    <h3>ข้อมูลใบแจ้งหนี้</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>เลขที่ใบแจ้งหนี้</label>
                            <input type="text" id="invoice_number" placeholder="เลขที่ใบแจ้งหนี้">
                        </div>
                        <div class="form-group">
                            <label>อ้างอิง</label>
                            <input type="text" id="invoice_reference" placeholder="หมายเลขอ้างอิง">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>วันที่ออกใบแจ้งหนี้</label>
                            <input type="text" id="invoice_date" placeholder="วันที่ออกใบแจ้งหนี้">
                        </div>
                        <div class="form-group">
                            <label>วันครบกำหนด</label>
                            <input type="text" id="invoice_due_date" placeholder="วันครบกำหนด">
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3>ข้อมูลการชำระเงิน</h3>
                    <div class="form-group">
                        <label>ชื่อบัญชี</label>
                        <input type="text" id="payment_account_name" placeholder="ชื่อบัญชี">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>หมายเลขบัญชี</label>
                            <input type="text" id="payment_account_number" placeholder="หมายเลขบัญชี">
                        </div>
                        <div class="form-group">
                            <label>ธนาคาร</label>
                            <input type="text" id="payment_bank_name" placeholder="ชื่อธนาคาร">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>ผู้อนุมัติ</label>
                        <input type="text" id="approved_by" placeholder="ชื่อผู้อนุมัติ">
                    </div>
                </div>
            </div>

            <!-- Items Tab -->
            <div id="items" class="tab-content">
                <div class="form-section">
                    <h3>รายการสินค้า/บริการ</h3>
                    <button type="button" class="btn btn-success" onclick="addItem()">+ เพิ่มรายการ</button>

                    <table class="items-table" id="items-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ลำดับ</th>
                                <th>รายการ</th>
                                <th style="width: 100px;">จำนวนหน่วย</th>
                                <th style="width: 80px;">หน่วย</th>
                                <th style="width: 120px;">ราคาต่อหน่วย</th>
                                <th style="width: 120px;">จำนวนเงิน</th>
                                <th style="width: 80px;">ลบ</th>
                            </tr>
                        </thead>
                        <tbody id="items-tbody">
                        </tbody>
                    </table>

                    <div class="form-row">
                        <div class="form-group">
                            <label>ส่วนลด</label>
                            <input type="number" id="discount" placeholder="0.00" step="0.01"
                                onchange="calculateSummary()">
                        </div>
                        <div class="form-group">
                            <label>ภาษีหัก ณ ที่จ่าย</label>
                            <input type="number" id="withhold_tax" placeholder="0.00" step="0.01"
                                onchange="calculateSummary()">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Summary Tab -->
            <div id="summary" class="tab-content">
                <div class="form-section">
                    <h3>สรุปใบแจ้งหนี้</h3>
                    <div class="summary-section">
                        <div class="summary-row">
                            <span>รวมเงิน:</span>
                            <span id="summary-subtotal">0.00 บาท</span>
                        </div>
                        <div class="summary-row">
                            <span>ส่วนลด:</span>
                            <span id="summary-discount">0.00 บาท</span>
                        </div>
                        <div class="summary-row">
                            <span>ภาษีหัก ณ ที่จ่าย:</span>
                            <span id="summary-tax">0.00 บาท</span>
                        </div>
                        <div class="summary-row total">
                            <span>จำนวนเงินทั้งสิ้น:</span>
                            <span id="summary-total">0.00 บาท</span>
                        </div>
                    </div>

                    <div class="btn-group">
                        <button type="button" class="btn btn-info" onclick="previewInvoice()">
                            <span id="preview-loading"></span>ดูตัวอย่าง
                        </button>
                        <button type="button" class="btn btn-primary" onclick="updateInvoice()">
                            <span id="update-loading"></span>อัพเดทข้อมูล
                        </button>
                        <button type="button" class="btn btn-success" onclick="exportPDF()">
                            <span id="export-loading"></span>ส่งออก PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let invoiceData = {};
        let itemCount = 0;

        // Initialize
        document.addEventListener('DOMContentLoaded', function () {
            loadInvoiceData();
        });

        // Tab functionality
        function showTab(tabName) {
            // Hide all tab contents
            const tabContents = document.querySelectorAll('.tab-content');
            tabContents.forEach(content => content.classList.remove('active'));

            // Remove active class from all tabs
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));

            // Show selected tab content
            document.getElementById(tabName).classList.add('active');

            // Add active class to clicked tab
            event.target.classList.add('active');
        }

        // Alert functions
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-error';

            alertContainer.innerHTML = `
                <div class="alert ${alertClass}">
                    ${message}
                </div>
            `;

            setTimeout(() => {
                alertContainer.innerHTML = '';
            }, 5000);
        }

        // Loading functions
        function showLoading(elementId) {
            const element = document.getElementById(elementId);
            element.innerHTML = '<span class="loading"></span>';
        }

        function hideLoading(elementId) {
            const element = document.getElementById(elementId);
            element.innerHTML = '';
        }

        // Load invoice data from server
        async function loadInvoiceData() {
            try {
                const response = await fetch('/api/invoice');
                invoiceData = await response.json();
                populateForm();
                populateItems();
                calculateSummary();
            } catch (error) {
                showAlert('เกิดข้อผิดพลาดในการโหลดข้อมูล: ' + error.message, 'error');
            }
        }

        // Populate form with data
        function populateForm() {
            // Company data
            document.getElementById('company_name').value = invoiceData.company?.name || '';
            document.getElementById('company_address').value = invoiceData.company?.address || '';
            document.getElementById('company_phone').value = invoiceData.company?.phone || '';
            document.getElementById('company_email').value = invoiceData.company?.email || '';
            document.getElementById('company_tax_id').value = invoiceData.company?.tax_id || '';

            // Customer data
            document.getElementById('customer_id').value = invoiceData.customer?.id || '';
            document.getElementById('customer_name').value = invoiceData.customer?.name || '';
            document.getElementById('customer_address').value = invoiceData.customer?.address || '';
            document.getElementById('customer_tax_id').value = invoiceData.customer?.tax_id || '';

            // Invoice info
            document.getElementById('invoice_number').value = invoiceData.info?.number || '';
            document.getElementById('invoice_date').value = invoiceData.info?.date || '';
            document.getElementById('invoice_due_date').value = invoiceData.info?.due_date || '';
            document.getElementById('invoice_reference').value = invoiceData.info?.reference || '';

            // Payment info
            document.getElementById('payment_account_name').value = invoiceData.payment?.account_name || '';
            document.getElementById('payment_account_number').value = invoiceData.payment?.account_number || '';
            document.getElementById('payment_bank_name').value = invoiceData.payment?.bank_name || '';
            document.getElementById('approved_by').value = invoiceData.approved_by || '';

            // Summary data
            document.getElementById('discount').value = invoiceData.discount || 0;
            document.getElementById('withhold_tax').value = invoiceData.withhold_tax || 0;
        }

        // Populate items table
        function populateItems() {
            const tbody = document.getElementById('items-tbody');
            tbody.innerHTML = '';
            itemCount = 0;

            if (invoiceData.items && invoiceData.items.length > 0) {
                invoiceData.items.forEach(item => {
                    addItemRow(item);
                });
            } else {
                addItem(); // Add one empty row
            }
        }

        // Add new item
        function addItem() {
            addItemRow({
                no: itemCount + 1,
                description: '',
                quantity: 1,
                unit: '',
                unit_price: 0,
                amount: 0
            });
        }

        // Add item row to table
        function addItemRow(item) {
            itemCount++;
            const tbody = document.getElementById('items-tbody');
            const row = document.createElement('tr');

            row.innerHTML = `
                <td>${itemCount}</td>
                <td><input type="text" value="${item.description || ''}" onchange="calculateItemAmount(this)" data-field="description"></td>
                <td><input type="number" value="${item.quantity || 1}" step="0.01" onchange="calculateItemAmount(this)" data-field="quantity"></td>
                <td><input type="text" value="${item.unit || ''}" data-field="unit"></td>
                <td><input type="number" value="${item.unit_price || 0}" step="0.01" onchange="calculateItemAmount(this)" data-field="unit_price"></td>
                <td><input type="number" value="${item.amount || 0}" step="0.01" onchange="calculateSummary()" data-field="amount"></td>
                <td><button type="button" class="btn btn-secondary" onclick="removeItem(this)">ลบ</button></td>
            `;

            tbody.appendChild(row);
            calculateSummary();
        }

        // Remove item
        function removeItem(button) {
            const row = button.closest('tr');
            row.remove();

            // Renumber items
            const rows = document.querySelectorAll('#items-tbody tr');
            rows.forEach((row, index) => {
                row.cells[0].textContent = index + 1;
            });

            itemCount = rows.length;
            calculateSummary();
        }

        // Calculate item amount
        function calculateItemAmount(input) {
            const row = input.closest('tr');
            const unitPriceInput = row.querySelector('[data-field="unit_price"]');
            const quantityInput = row.querySelector('[data-field="quantity"]');
            const amountInput = row.querySelector('[data-field="amount"]');

            if (input.dataset.field === 'unit_price' || input.dataset.field === 'quantity') {
                const unitPrice = parseFloat(unitPriceInput.value) || 0;
                const quantity = parseFloat(quantityInput.value) || 0;
                amountInput.value = (unitPrice * quantity).toFixed(2);
            }

            calculateSummary();
        }

        // Calculate summary
        function calculateSummary() {
            let subtotal = 0;

            // Calculate subtotal from items
            const amountInputs = document.querySelectorAll('[data-field="amount"]');
            amountInputs.forEach(input => {
                subtotal += parseFloat(input.value) || 0;
            });

            const discount = parseFloat(document.getElementById('discount').value) || 0;
            const withholdTax = parseFloat(document.getElementById('withhold_tax').value) || 0;
            const total = subtotal - discount - withholdTax;

            // Update summary display
            document.getElementById('summary-subtotal').textContent = subtotal.toFixed(2) + ' บาท';
            document.getElementById('summary-discount').textContent = discount.toFixed(2) + ' บาท';
            document.getElementById('summary-tax').textContent = withholdTax.toFixed(2) + ' บาท';
            document.getElementById('summary-total').textContent = total.toFixed(2) + ' บาท';
        }

        // Collect form data
        function collectFormData() {
            // Collect items
            const items = [];
            const rows = document.querySelectorAll('#items-tbody tr');

            rows.forEach((row, index) => {
                const description = row.querySelector('[data-field="description"]').value;
                const quantity = parseFloat(row.querySelector('[data-field="quantity"]').value) || 0;
                const unit = row.querySelector('[data-field="unit"]').value;
                const unitPrice = parseFloat(row.querySelector('[data-field="unit_price"]').value) || 0;
                const amount = parseFloat(row.querySelector('[data-field="amount"]').value) || 0;

                if (description.trim()) { // Only add non-empty items
                    items.push({
                        no: index + 1,
                        description: description,
                        quantity: quantity,
                        unit: unit,
                        unit_price: unitPrice,
                        amount: amount
                    });
                }
            });

            return {
                company: {
                    name: document.getElementById('company_name').value,
                    address: document.getElementById('company_address').value,
                    phone: document.getElementById('company_phone').value,
                    email: document.getElementById('company_email').value,
                    tax_id: document.getElementById('company_tax_id').value
                },
                customer: {
                    id: document.getElementById('customer_id').value,
                    name: document.getElementById('customer_name').value,
                    address: document.getElementById('customer_address').value,
                    tax_id: document.getElementById('customer_tax_id').value
                },
                info: {
                    number: document.getElementById('invoice_number').value,
                    date: document.getElementById('invoice_date').value,
                    due_date: document.getElementById('invoice_due_date').value,
                    reference: document.getElementById('invoice_reference').value
                },
                payment: {
                    account_name: document.getElementById('payment_account_name').value,
                    account_number: document.getElementById('payment_account_number').value,
                    bank_name: document.getElementById('payment_bank_name').value
                },
                approved_by: document.getElementById('approved_by').value,
                items: items,
                discount: parseFloat(document.getElementById('discount').value) || 0,
                withhold_tax: parseFloat(document.getElementById('withhold_tax').value) || 0
            };
        }

        // Update invoice data
        async function updateInvoice() {
            showLoading('update-loading');

            try {
                const formData = collectFormData();

                const response = await fetch('/api/invoice/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const result = await response.json();

                if (response.ok) {
                    showAlert('อัพเดทข้อมูลสำเร็จ');
                    await loadInvoiceData(); // Reload to get updated calculations
                } else {
                    showAlert('เกิดข้อผิดพลาด: ' + result.message, 'error');
                }
            } catch (error) {
                showAlert('เกิดข้อผิดพลาดในการอัพเดทข้อมูล: ' + error.message, 'error');
            } finally {
                hideLoading('update-loading');
            }
        }

        // Preview invoice
        async function previewInvoice() {
            showLoading('preview-loading');

            try {
                // Update data first
                await updateInvoice();

                // Open preview in new window
                window.open('/api/preview', '_blank');
                showAlert('เปิดตัวอย่างในหน้าต่างใหม่');
            } catch (error) {
                showAlert('เกิดข้อผิดพลาดในการแสดงตัวอย่าง: ' + error.message, 'error');
            } finally {
                hideLoading('preview-loading');
            }
        }

        // Export PDF
        async function exportPDF() {
            showLoading('export-loading');

            try {
                // Update data first
                await updateInvoice();

                // Create download link
                const link = document.createElement('a');
                link.href = '/api/export/pdf';
                link.download = 'invoice.pdf';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                showAlert('กำลังสร้าง PDF... กรุณารอสักครู่');
            } catch (error) {
                showAlert('เกิดข้อผิดพลาดในการส่งออก PDF: ' + error.message, 'error');
            } finally {
                hideLoading('export-loading');
            }
        }

        // Auto-save functionality
        let autoSaveTimer;

        function setupAutoSave() {
            const inputs = document.querySelectorAll('input, textarea, select');
            inputs.forEach(input => {
                input.addEventListener('input', () => {
                    clearTimeout(autoSaveTimer);
                    autoSaveTimer = setTimeout(() => {
                        updateInvoice();
                    }, 2000); // Auto-save after 2 seconds of inactivity
                });
            });
        }

        // Initialize auto-save after DOM is loaded
        document.addEventListener('DOMContentLoaded', function () {
            setupAutoSave();
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', function (e) {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 's':
                        e.preventDefault();
                        updateInvoice();
                        break;
                    case 'p':
                        e.preventDefault();
                        previewInvoice();
                        break;
                    case 'e':
                        e.preventDefault();
                        exportPDF();
                        break;
                }
            }
        });
    </script>
</body>

</html>