<!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;
        }
        
        .invoice-option {
            display: block;
            font-size: 0.875rem;
        }
        .invoice-balance {
            color: #28a745;
            font-weight: 600;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
        
        .alert {
            border-radius: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <?php if(session('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo e(session('success')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <?php if(session('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo e(session('error')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <a href="<?php echo e(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>
                <div class="text-light mt-1 fw-light" style="font-size: 0.85rem;">
                    Receipt #: <?php echo e($receiptNumber); ?>

                </div>
            </div>
            
            <div class="card-body">
                <form method="POST" action="<?php echo e(route('receipts.store')); ?>" id="receiptForm">
                    <?php echo csrf_field(); ?>
                    
                    <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">Customer <span class="text-danger">*</span></label>
                                <select name="customer_id" class="form-select" id="customerSelect" required>
                                    <option value="">Select Customer</option>
                                    <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($customer->id); ?>"
                                            data-address="<?php echo e($customer->address); ?>"
                                            data-phone="<?php echo e($customer->contact_1); ?>"
                                            data-email="<?php echo e($customer->email); ?>"
                                            data-vat="<?php echo e($customer->vat); ?>"
                                            data-tin="<?php echo e($customer->tin); ?>">
                                            <?php echo e($customer->customer_code); ?> - <?php echo e($customer->customer_account); ?>

                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['customer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="error-message"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </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="<?php echo e($receiptNumber); ?>" readonly>
                                <input type="hidden" name="receipt_number" value="<?php echo e($receiptNumber); ?>">
                            </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="<?php echo e(now()->format('Y-m-d')); ?>" required>
                                <?php $__errorArgs = ['receipt_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="error-message"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </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>
                                    <option value="">Select Payment Type</option>
                                    <?php $__currentLoopData = $paymentTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $type): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($type->id); ?>"><?php echo e($type->description); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['payment_type_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="error-message"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </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%">Invoice Reference</th>
                                <th width="20%">Deposit 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="<?php echo e(route('home')); ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i> Cancel
                        </a>
                        <button type="submit" class="btn btn-success" id="processReceiptBtn">
                            <i class="fas fa-save me-2"></i> Process Receipt
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Print Modal -->
    <?php if(session('processed_receipt_id')): ?>
    <div class="modal fade" id="printModal" 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 text-center">
                    <p>Receipt processed successfully!</p>
                    <p>Do you want to print the receipt now?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Later</button>
                    <a href="<?php echo e(route('receipts.print', session('processed_receipt_id'))); ?>" 
                       class="btn btn-primary" target="_blank">
                        <i class="fas fa-print me-2"></i> Print Now
                    </a>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <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() {
            let customerInvoices = [];
            let lineCounter = 0;

            // Populate customer info
            document.getElementById('customerSelect').addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                document.getElementById('customerAddress').value = selectedOption.dataset.address || '';
                document.getElementById('customerPhone').value = selectedOption.dataset.phone || '';
                document.getElementById('customerEmail').value = selectedOption.dataset.email || '';
                document.getElementById('customerVat').value = selectedOption.dataset.vat || '';
                document.getElementById('customerTin').value = selectedOption.dataset.tin || '';
                
                if (this.value) {
                    fetch(`/receipts/customer-invoices/${this.value}`)
                        .then(response => {
                            if (!response.ok) throw new Error('Network response was not ok');
                            return response.json();
                        })
                        .then(data => {
                            customerInvoices = data;
                            updateInvoiceDropdowns();
                        })
                        .catch(error => {
                            console.error('Error fetching invoices:', error);
                            customerInvoices = [];
                            updateInvoiceDropdowns();
                        });
                } else {
                    customerInvoices = [];
                    updateInvoiceDropdowns();
                }
            });

            // Add payment line
            document.getElementById('addLineBtn').addEventListener('click', function() {
                addNewLine();
            });

            function addNewLine() {
                const tbody = document.querySelector('#paymentItemsTable tbody');
                const row = document.createElement('tr');
                const currentIndex = lineCounter++;
                
                row.innerHTML = `
                    <td>${tbody.children.length + 1}</td>
                    <td>
                        <input type="text" name="lines[${currentIndex}][description]" 
                               class="form-control form-control-sm" required>
                    </td>
                    <td>
                        <select name="lines[${currentIndex}][invoice_id]" 
                                class="form-select form-control-sm invoice-select">
                            <option value="">Select Invoice</option>
                        </select>
                    </td>
                    <td>
                        <select name="lines[${currentIndex}][deposit_account_id]" 
                                class="form-select form-control-sm account-select" required>
                            <option value="">Select Account</option>
                            <?php $__currentLoopData = $accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($account->id); ?>">
                                    <?php echo e($account->code); ?> - <?php echo e($account->account_name); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </td>
                    <td>
                        <input type="number" name="lines[${currentIndex}][amount]" 
                               class="form-control form-control-sm amount-input" 
                               min="0.01" step="0.01" required value="0.00">
                    </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);
                
                // Add event listeners
                row.querySelector('.amount-input').addEventListener('input', updateTotals);
                row.querySelector('.remove-line').addEventListener('click', function() {
                    row.remove();
                    renumberRows();
                    updateTotals();
                });
                
                updateInvoiceDropdown(row.querySelector('.invoice-select'));
                updateTotals();
            }

            function updateInvoiceDropdowns() {
                document.querySelectorAll('.invoice-select').forEach(dropdown => {
                    updateInvoiceDropdown(dropdown);
                });
            }

            function updateInvoiceDropdown(dropdown) {
                const currentValue = dropdown.value;
                let options = '<option value="">Select Invoice</option>';
                
                customerInvoices.forEach(invoice => {
                    if (invoice.outstanding > 0) {
                        options += `
                            <option value="${invoice.id}" 
                                    data-outstanding="${invoice.outstanding}"
                                    data-description="Payment for Invoice ${invoice.document_number}">
                                ${invoice.document_number} - Outstanding: $${invoice.outstanding.toFixed(2)}
                            </option>`;
                    }
                });
                
                dropdown.innerHTML = options;
                
                if (currentValue) {
                    dropdown.value = currentValue;
                }
            }

            // Auto-fill description and amount when invoice is selected
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('invoice-select')) {
                    const selectedOption = e.target.options[e.target.selectedIndex];
                    const row = e.target.closest('tr');
                    
                    if (selectedOption.value) {
                        const outstanding = parseFloat(selectedOption.dataset.outstanding) || 0;
                        const description = selectedOption.dataset.description || '';
                        
                        // Auto-fill description
                        row.querySelector('input[name*="[description]"]').value = description;
                        
                        // Auto-fill amount with outstanding balance
                        const amountInput = row.querySelector('.amount-input');
                        amountInput.value = outstanding.toFixed(2);
                        amountInput.dispatchEvent(new Event('input'));
                    }
                }
            });

            function renumberRows() {
                const rows = document.querySelectorAll('#paymentItemsTable tbody tr');
                rows.forEach((row, index) => {
                    row.querySelector('td:first-child').textContent = index + 1;
                });
            }

            function updateTotals() {
                let total = 0;
                document.querySelectorAll('.amount-input').forEach(input => {
                    total += parseFloat(input.value) || 0;
                });
                document.getElementById('totalAmount').textContent = '$' + total.toFixed(2);
            }

            // Form submission handling
            document.getElementById('receiptForm').addEventListener('submit', function(e) {
                const totalAmount = parseFloat(document.getElementById('totalAmount').textContent.replace('$', '')) || 0;
                if (totalAmount <= 0) {
                    e.preventDefault();
                    alert('Please add at least one payment item with amount greater than 0.');
                    return false;
                }
                
                // Validate that at least one line has amount > 0
                const hasValidAmount = Array.from(document.querySelectorAll('.amount-input'))
                    .some(input => parseFloat(input.value) > 0);
                    
                if (!hasValidAmount) {
                    e.preventDefault();
                    alert('Please add at least one payment item with amount greater than 0.');
                    return false;
                }
            });

            // Initialize with one line
            addNewLine();

            // Show print modal if receipt was processed
            <?php if(session('processed_receipt_id')): ?>
                $('#printModal').modal('show');
            <?php endif; ?>
        });
    </script>
</body>
</html><?php /**PATH /home/melsoftzimco/public_html/demo/resources/views/receipts/create.blade.php ENDPATH**/ ?>