<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Receipt</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #6f42c1;
            --primary-light: #9d7bd9;
            --primary-dark: #563d7c;
            --secondary-color: #f8f9fa;
            --border-color: #dee2e6;
        }
        
        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 0.92rem;
        }
        
        .card {
            border-top: 3px solid var(--primary-color);
            border-radius: 0.75rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .card-header {
            background: linear-gradient(to right, var(--primary-color), var(--primary-light));
            color: white;
            border-radius: 0.75rem 0.75rem 0 0 !important;
            padding: 1rem;
        }
        
        .section-header {
            font-weight: bold;
            font-size: 1.05rem;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 0.6rem;
            margin-bottom: 1.2rem;
            color: var(--primary-color);
        }
        
        .totals-panel {
            background-color: var(--secondary-color);
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            padding: 12px;
        }
        
        .back-link {
            display: inline-block;
            margin-bottom: 15px;
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .settings-icon {
            position: absolute;
            top: 18px;
            right: 18px;
            font-size: 1.1rem;
            color: white;
            cursor: pointer;
            z-index: 100;
        }
        
        .print-modal-option {
            display: flex;
            align-items: center;
            padding: 8px 0;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        @endif
        
        <a href="{{ route('home') }}" class="back-link">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>
        
        <div class="card">
            <div class="card-header position-relative">
                <h4 class="mb-0"><i class="fas fa-receipt me-2"></i> Create New Receipt</h4>
                <i class="fas fa-cog settings-icon" data-bs-toggle="modal" data-bs-target="#settingsModal"></i>
            </div>
            
            <div class="card-body">
                <form method="POST" action="{{ route('receipts.store') }}" id="receiptForm">
                    @csrf
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="section-header">
                                <i class="fas fa-user me-2"></i> Customer Information
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Invoice Number (optional)</label>
                                <input type="text" id="invoiceSearch" class="form-control" placeholder="Search invoice number...">
                                <div class="mt-2">
                                    <select class="form-select" id="invoiceSelect">
                                        <option value="">Select Invoice</option>
                                    </select>
                                </div>
                                <div class="form-text">Select an invoice to auto-detect customer and outstanding balance.</div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Customer</label>
                                <select name="customer_id" class="form-select" id="customerSelect">
                                    <option value="">Select Customer (optional)</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}"
                                            data-address="{{ $customer->address }}"
                                            data-phone="{{ $customer->contact_1 }}"
                                            data-email="{{ $customer->email }}"
                                            data-vat="{{ $customer->vat }}"
                                            data-tin="{{ $customer->tin }}">
                                            {{ $customer->customer_code }} - {{ $customer->customer_account }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('customer_id')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Walk-in Customer Name</label>
                                <input type="text" name="walk_in_customer_name" id="walkInName" class="form-control" placeholder="Required if no customer/invoice selected">
                                @error('walk_in_customer_name')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Address</label>
                                    <input type="text" id="customerAddress" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Telephone</label>
                                    <input type="text" id="customerPhone" class="form-control" readonly>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Email</label>
                                    <input type="text" id="customerEmail" class="form-control" readonly>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">VAT Reg. No.</label>
                                    <input type="text" id="customerVat" class="form-control" readonly>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">TIN</label>
                                    <input type="text" id="customerTin" class="form-control" readonly>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="section-header">
                                <i class="fas fa-info-circle me-2"></i> Receipt Information
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Receipt Number</label>
                                <input type="text" class="form-control" value="{{ $receiptNumber }}" readonly>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Date <span class="text-danger">*</span></label>
                                <input type="date" name="receipt_date" class="form-control" 
                                       value="{{ now()->format('Y-m-d') }}" required>
                                @error('receipt_date')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Payment Type <span class="text-danger">*</span></label>
                                <select name="payment_type_id" class="form-select" required>
                                    @foreach($paymentTypes as $pt)
                                        <option value="{{ $pt->id }}">{{ $pt->description }}</option>
                                    @endforeach
                                </select>
                                @error('payment_type_id')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Deposit Account <span class="text-danger">*</span></label>
                                <select name="deposit_account_id" class="form-select" required>
                                    <option value="">Select Deposit Account</option>
                                    @foreach($accounts as $account)
                                        <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->account_name }}</option>
                                    @endforeach
                                </select>
                                @error('deposit_account_id')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Reference</label>
                                <input type="text" name="reference" class="form-control" placeholder="Optional reference">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Description</label>
                                <textarea name="description" class="form-control" rows="2" placeholder="Optional description"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="section-header d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <i class="fas fa-list me-2"></i> Payment Items
                        </div>
                        <button type="button" class="btn btn-primary btn-sm" id="addLineBtn">
                            <i class="fas fa-plus me-1"></i> Add Payment
                        </button>
                    </div>
                    
                    <table class="table table-bordered" id="paymentItemsTable">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">#</th>
                                <th width="25%">Description <span class="text-danger">*</span></th>
                                <th width="25%">Reference (Invoice #)</th>
                                <th width="20%">GL Account <span class="text-danger">*</span></th>
                                <th width="20%">Amount <span class="text-danger">*</span></th>
                                <th width="5%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Lines will be added dynamically -->
                        </tbody>
                    </table>
                    
                    <div class="row justify-content-end mt-4">
                        <div class="col-md-5">
                            <div class="totals-panel">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="fw-bold">Total Amount:</span>
                                    <span id="totalAmount" class="fw-bold">$0.00</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between mt-4 pt-3 border-top">
                        <a href="{{ route('home') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i> Cancel
                        </a>
                        <button type="button" class="btn btn-success" id="processReceiptBtn">
                            <i class="fas fa-save me-2"></i> Process Receipt
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-cog me-2"></i> Receipt Settings</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Receipt Prefix</label>
                        <input type="text" id="receiptPrefix" class="form-control" value="{{ substr($receiptNumber, 0, 2) }}">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Starting Number</label>
                        <input type="number" id="startNumber" class="form-control" value="{{ intval(preg_replace('/\D/', '', $receiptNumber)) }}" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveSettings">Save Settings</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Print Options Modal -->  
    <div class="modal fade" id="printOptionsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-print me-2"></i> Print Receipt</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Would you like to print the receipt now?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="confirmPrint">Print</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const invoiceSearch = document.getElementById('invoiceSearch');
        const invoiceSelect = document.getElementById('invoiceSelect');
        // populate customer info
        document.getElementById('customerSelect').addEventListener('change', function() {
            const o = this.options[this.selectedIndex];
            document.getElementById('customerAddress').value = o.dataset.address||'';
            document.getElementById('customerPhone').value   = o.dataset.phone||'';
            document.getElementById('customerEmail').value   = o.dataset.email||'';
            document.getElementById('customerVat').value     = o.dataset.vat||'';
            document.getElementById('customerTin').value     = o.dataset.tin||'';
            if (this.value) {
                fetch(`/api/customers/${this.value}/invoices`)
                  .then(r=>r.json()).then(data=>{
                    window.customerInvoices = data;
                    document.querySelectorAll('.invoice-select').forEach(s=>updateInvoiceDropdown(s));
                  });
            }
        });

        // invoice search + auto-detect customer and amount
        let invoiceSearchTimer = null;
        if (invoiceSearch && invoiceSelect) {
            invoiceSearch.addEventListener('input', function() {
                clearTimeout(invoiceSearchTimer);
                invoiceSearchTimer = setTimeout(async () => {
                    const q = invoiceSearch.value.trim();
                    const res = await fetch(`/api/invoices/search?q=${encodeURIComponent(q)}`, { headers: { 'Accept':'application/json' } });
                    const data = await res.json();
                    invoiceSelect.innerHTML = `<option value="">Select Invoice</option>` + (data || []).map(inv =>
                        `<option value="${inv.id}">${inv.document_number} (${inv.status})</option>`
                    ).join('');
                }, 250);
            });

                invoiceSelect.addEventListener('change', async function() {
                    const id = this.value;
                    if (!id) return;
                    const res = await fetch(`/api/invoices/${encodeURIComponent(id)}`, { headers: { 'Accept':'application/json' } });
                    const data = await res.json();
                    if (data?.customer_account_id) {
                        const customerSelect = document.getElementById('customerSelect');
                        customerSelect.value = String(data.customer_account_id);
                        customerSelect.dispatchEvent(new Event('change'));
                    }

                    // If there are no lines yet, add one
                    if (document.querySelectorAll('#paymentItemsTable tbody tr').length === 0) {
                        document.getElementById('addLineBtn').click();
                    }

                    // Set the first line's invoice + amount
                    const firstRow = document.querySelector('#paymentItemsTable tbody tr');
                    if (firstRow) {
                        const lineInv = firstRow.querySelector('.invoice-select');
                        const lineAmt = firstRow.querySelector('.amount-input');
                        if (lineInv) {
                            // Ensure dropdown includes the selected invoice
                            if (![...lineInv.options].some(o => o.value === String(data.id))) {
                                const opt = document.createElement('option');
                                opt.value = String(data.id);
                                opt.textContent = data.document_number || `Invoice #${data.id}`;
                                lineInv.appendChild(opt);
                            }
                            lineInv.value = String(data.id);
                        }
                        if (lineAmt && typeof data?.outstanding === 'number') {
                            lineAmt.value = Number(data.outstanding).toFixed(2);
                        }
                        updateTotals();
                    }
                });
            }

        // add line
        document.getElementById('addLineBtn').addEventListener('click', function() {
            const tbody = document.querySelector('#paymentItemsTable tbody');
            const idx   = tbody.children.length;
            const row   = document.createElement('tr');
            row.innerHTML = `
                <td>${idx+1}</td>
                <td><input type="text" name="lines[${idx}][description]" class="form-control form-control-sm" required></td>
                <td>
                  <select name="lines[${idx}][invoice_id]" class="form-select form-control-sm invoice-select">
                    <option value="">Select Invoice</option>
                    ${generateInvoiceOptions()}
                  </select>
                </td>
                <td>
                  <select name="lines[${idx}][account_id]" class="form-select form-control-sm account-select" required>
                    <option value="">Select GL Account</option>
                    @foreach($accounts as $account)
                      <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->account_name }}</option>
                    @endforeach
                  </select>
                </td>
                <td><input type="number" name="lines[${idx}][amount]" class="form-control form-control-sm amount-input" min="0.01" step="0.01" required></td>
                <td class="text-center">
                  <button type="button" class="btn btn-sm btn-danger remove-line"><i class="fas fa-trash-alt"></i></button>
                </td>`;
            tbody.appendChild(row);
            row.querySelector('.amount-input').addEventListener('input', updateTotals);
            row.querySelector('.remove-line').addEventListener('click', ()=>{
                row.remove(); renumberRows(); updateTotals();
            });
            updateInvoiceDropdown(row.querySelector('.invoice-select'));
        });

        function generateInvoiceOptions(){
            if (!window.customerInvoices) return '';
            return window.customerInvoices.map(inv=>
                `<option value="${inv.id}" data-amount="${inv.balance_due}">
                   ${inv.document_number} - Balance: $${inv.balance_due.toFixed(2)}
                 </option>`
            ).join('');
        }
        
        function updateInvoiceDropdown(sel){
            const cur=sel.value;
            sel.innerHTML=`<option value="">Select Invoice</option>`+generateInvoiceOptions();
            sel.value=cur;
        }
        
        document.addEventListener('change', async function(e){
            if (e.target.classList.contains('invoice-select')){
                const so = e.target.options[e.target.selectedIndex];
                const row = e.target.closest('tr');
                if (!so.value) return;

                // Auto-set line amount from outstanding
                row.querySelector('.amount-input').value = parseFloat(so.dataset.amount||0).toFixed(2);
                updateTotals();

                // Auto-detect customer if not selected, and prevent cross-customer mixing
                try {
                    const res = await fetch(`/api/invoices/${encodeURIComponent(so.value)}`, { headers: { 'Accept':'application/json' } });
                    const data = await res.json();
                    const customerSelect = document.getElementById('customerSelect');

                    if (data?.customer_account_id) {
                        if (!customerSelect.value) {
                            customerSelect.value = String(data.customer_account_id);
                            customerSelect.dispatchEvent(new Event('change'));
                        } else if (String(customerSelect.value) !== String(data.customer_account_id)) {
                            alert('This receipt can only include invoices for the selected customer.');
                            e.target.value = '';
                            row.querySelector('.amount-input').value = '';
                            updateTotals();
                        }
                    }
                } catch (_) {
                    // ignore lookup failures
                }
            }
        });

        function renumberRows(){
            document.querySelectorAll('#paymentItemsTable tbody tr').forEach((r,i)=>r.querySelector('td:first-child').textContent = i+1);
        }
        
        function updateTotals(){
            let t=0;
            document.querySelectorAll('.amount-input').forEach(i=>t+=parseFloat(i.value)||0);
            document.getElementById('totalAmount').textContent = '$'+t.toFixed(2);
        }

        // settings
        document.getElementById('saveSettings').addEventListener('click', function(){
            fetch("{{ route('settings.update-document') }}", {
                method:'POST',
                headers:{
                  'Content-Type':'application/json',
                  'X-CSRF-TOKEN':'{{ csrf_token() }}'
                },
                body: JSON.stringify({
                  prefix: document.getElementById('receiptPrefix').value,
                  start_number: document.getElementById('startNumber').value,
                  document_type:'receipt'
                })
            }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); });
        });

        // init one line
        document.getElementById('addLineBtn').click();

        // show print modal
        document.getElementById('processReceiptBtn').addEventListener('click', ()=>{
            // Validate form first
            const form = document.getElementById('receiptForm');
            if (form.checkValidity()) {
                new bootstrap.Modal(document.getElementById('printOptionsModal')).show();
            } else {
                form.reportValidity();
            }
        });

        // only submit once
        document.getElementById('confirmPrint').addEventListener('click', ()=>{
            document.getElementById('receiptForm').submit();
            bootstrap.Modal.getInstance(document.getElementById('printOptionsModal')).hide();
        });

        // after save: open pdf then reset
        @if(session('printed_receipt_id'))
        (function(){
          const id = {{ session('printed_receipt_id') }};
          window.open(`{{ url('receipts') }}/${id}/pdf`, '_blank');
          window.location.href = "{{ route('receipts.create') }}";
        })();
        @endif
    });
    </script>
</body>
</html>
